Taro is planning a long trip by train during the summer vacation. However, in order for Taro, who is a high school student, to travel as far as possible during the summer vacation, which has only one month, he cannot make a good plan unless he finds the cheapest and the fastest way. Let's create a program to help Taro's plan so that he can enjoy a wonderful trip.
Create a program that outputs the minimum amount or the shortest time in response to inquiries by
inputting track information and the number of stations.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
n m
a1 b1 cost1 time1
a2 b2 cost2 time2
::
an bn costn timen
k
p1 q1 r1
p2 q2 r2
::
pk qk rk
The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100).
The following n lines give information on the i-th line. As information on each line, the numbers ai, bi (1 ≤ ai, bi ≤ m) of the two stations connecting the lines, the toll costi (1 ≤ costi ≤ 1000), and the travel time timei (1 ≤ timei ≤ 1000) are given. I will. However, each station shall be numbered in order from 1 to m. If ai and bi are connected by railroad tracks, both ai to bi and bi to ai can be moved at the same rate and time.
The following line is given the number of queries k (1 ≤ k ≤ 200). The next k line is given the i-th query. For each query, the departure station pi, the arrival station qi, and the type of value to output ri (0 or 1) are given. Inquiries must have a route.
The number of datasets does not exceed 50.
Output
Outputs the minimum amount or minimum time on one line for each data set. When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output.
We need to create a program that processes multiple datasets. Each dataset: n (number of edges), m (number of nodes/stations). Then n lines each: a, b, cost, time. Edges are undirected: both directions have same cost and time.
Then k queries: each query: p, q, r. If r=0, output the minimum total cost from p to q. If r=1, output the minimum total time from p to q. It says: "Inquiries must have a route." So always reachable.
Constraints: n up to 3000, m up to 100, k up to 200 per dataset. Number of datasets <= 50. So overall operations manageable.
We need to answer queries for each dataset. Since m is at most 100, we could precompute all-pairs shortest paths for both cost and time. That would be O(m^3) = 1e6 per dataset, which is fine. Or we could run Dijkstra per query (k up to 200, m=100, n=3000, Dijkstra O((m+n) log m) ~ 3000 log 100 ~ small). But we have many datasets but still fine. But simpler: all-pairs using Floyd-Warshall O(m^3) = 1e6, which is okay for up to 50 datasets => 50 million, fine. Memory: m=100, adjacency matrices of size 100x100 for cost and time. But careful: edges have both cost and time, but we need separate shortest path metrics: minimize cost (ignoring time) and minimize time (ignoring cost). So we can compute two separate distance matrices: distCost[i][j] = minimum total cost to go from i to j; distTime[i][j] = minimum total time.
Since edges are undirected, both matrices symmetric.
For each edge (a,b,cost,time): if cost < distCost[a][b], set both directions. Same for time.
Then run Floyd for both: for k=1..m, for i=1..m, for j=1..m: relax.
But note that for Floyd we can do separate loops or combined. Since m=100, two separate loops fine.
Then for each query, output distCost[p][q] if r=0, else distTime[p][q].
But there is a nuance: "When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output." So that's straightforward.
Now the input format: The end of input is indicated by two lines of zeros: That means a line with "0 0" (n and m both zero) ends input. So while reading, read n m; if both zero break.
Then for each dataset, read n lines, then read k, then k lines.
Make sure to handle multiple datasets.
Edge cases: multiple edges? Possibly. The input does not forbid multiple edges. So we should take min of given edges.
Undirected: so set both directions.
Implementation details: Use INF = something large, like 10**9.
Also note constraints: cost and time each up to 1000, n up to 3000, so worst path length: cost up to 1000* (m-1) but possibly many edges? Actually could be up to 10003000? But m=100, max number of edges in simple path is at most 99. However multiple edges can cause longer path? Not if we are taking minimum, so distances limited to at most 100099 = 99,000. But we can set INF to 1e9 safe.
Now output: For each dataset, we have k queries. For each query we output the answer on its own line. However the problem statement says: "Outputs the minimum amount or minimum time on one line for each data set." That might be ambiguous: Actually reading the problem: "Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations." Then "Outputs the minimum amount or minimum time on one line for each data set." It might mean that for each dataset we output k lines, each line corresponding to each query. The example: Input shows dataset with n=6,m=5, then k=2, queries (1 5 0) and (1 5 1). Output shows:
450
35
That is two lines. So indeed each query's answer on separate line, presumably for each dataset we output the answers for its queries.
So we just output the answers for each query, each on a new line. No blank lines between datasets.
Thus algorithm:
while True:
read n, m
if n==0 and m==0: break
initialize distCost = [[INF]*m for _ in range(m)]; distTime similarly.
for i in range(m): distCost[i][i]=0; distTime[i][i]=0.
for _ in range(n):
read a,b,c,t
a-=1; b-=1 (zero-index)
if c < distCost[a][b]: distCost[a][b] = distCost[b][a] = c
if t < distTime[a][b]: distTime[a][b] = distTime[b][a] = t
Floyd-Warshall:
for k in range(m):
for i in range(m):
for j in range(m):
if distCost[i][j] > distCost[i][k] + distCost[k][j]:
distCost[i][j] = distCost[i][k] + distCost[k][j]
if distTime[i][j] > distTime[i][k] + distTime[k][j]:
distTime[i][j] = distTime[i][k] + distTime[k][j]
read k
for _ in range(k):
read p,q,r
p-=1; q-=1
if r==0: print(distCost[p][q])
else: print(distTime[p][q])
Make sure to convert to int.
But we might consider potential memory: 100x100 = 10k per matrix, fine.
Now we must be careful: The input description says: "The first line gives the number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100)." So n can be up to 3000. So we need to handle up to 3000 edges, which is fine.
Edge cases: multiple edges: we need to keep the minimum cost and time separately. In initialization we set INF. For each edge, we set the cost and time if smaller.
Now think: Could there be a scenario where we need to combine edges in a way that minimum cost path might have a certain time, but we only care cost; but for cost we ignore time, so just use cost edges. So separate.
Thus solution.
But wait: The problem statement mentions "the cheapest and the fastest way". It asks for minimum amount or shortest time depending on r. So yes.
But note: There is an image in the problem but we don't have it, but not needed.
Now, what about "When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output." So just that.
Thus straightforward.
But maybe there is nuance: The problem might be from some contest where they want to find the minimum cost and minimum time separately but edges have both attributes, so we treat them as separate graphs.
Thus final answer.
But we also need to consider that there might be queries that ask for minimum cost but also maybe we need to consider time constraints? Not from description.
Thus answer.
Now implementation in Python:
import sys
def main():
import sys
data = sys.stdin.read().strip().split()
it = iter(data)
out_lines = []
while True:
try:
n = int(next(it))
m = int(next(it))
except StopIteration:
break
if n == 0 and m == 0:
break
INF = 10**9
distC = [[INF]*m for _ in range(m)]
distT = [[INF]*m for _ in range(m)]
for i in range(m):
distC[i][i] = 0
distT[i][i] = 0
for _ in range(n):
a = int(next(it))-1
b = int(next(it))-1
c = int(next(it))
t = int(next(it))
if c < distC[a][b]:
distC[a][b] = distC[b][a] = c
if t < distT[a][b]:
distT[a][b] = distT[b][a] = t
# Floyd-Warshall
for k in range(m):
for i in range(m):
dikC = distC[i][k]
dikT = distT[i][k]
if dikC == INF and dikT == INF: # optional optimization
continue
for j in range(m):
# cost
if dikC + distC[k][j] < distC[i][j]:
distC[i][j] = dikC + distC[k][j]
# time
if dikT + distT[k][j] < distT[i][j]:
distT[i][j] = dikT + distT[k][j]
kq = int(next(it))
for _ in range(kq):
p = int(next(it))-1
q = int(next(it))-1
r = int(next(it))
if r == 0:
out_lines.append(str(distC[p][q]))
else:
out_lines.append(str(distT[p][q]))
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
But need to be careful: In Floyd loops, we used two separate inner loops? Actually I combined but careful: In combined loop, when we update distC[i][j] we use distC[i][k] and distC[k][j]. But if we modify distC[i][k] or distC[k][j] in the same k iteration, it's fine because Floyd's algorithm relies on using k as intermediate, and the order of i,j updates is fine if we do classic triple loop: for k in range(m): for i in range(m): for j in range(m): update using intermediate k. That's correct.
But I used dikC = distC[i][k] and then in the inner loop for j, we used distC[k][j]. This is standard.
Time complexity: O(m^3) = 1e6 per dataset. For 50 datasets, 50e6, which may be borderline but Python might handle within time if optimized. m=100 so m^3=1,000,000. 50 million operations might be okay if written in Python (pure triple nested loops). But we also have two matrices updating inside same loops (two if conditions). That's 2 million per dataset, 100 million across 50? Actually 50*2e6 = 100 million, which is okay in Python (maybe 1-2 seconds? But plus I/O). We can also run two separate Floyd loops but it's similar.
But we can also speed up using list comprehensions? Not needed.
Alternatively, we can use Dijkstra per query: k up to 200, m=100, edges=3000, each Dijkstra O((m+n) log m) ~ 3100 log 100 ~ 3100*~7 = 21700, times 200 = 4.34e6 per dataset, times 50 = 217 million, also similar. So Floyd seems simpler.
But careful: n can be up to 3000, which may be dense, but m=100, maximum edges could be up to 4950 for complete graph. So Floyd is fine.
1-2-4-5: cost200+100+150=450, time10+10+20=40
1-4-5: cost400+150=550, time15+20=35
1-3-5: cost250+300=550, time25+20=45
1-2-4-5 =450 cost time40
1-4-5 =550 cost time35
So min cost is 450 (output 450), min time is 35 (output 35). Good.
Thus program outputs those lines.
Now, I'll write the solution accordingly.
But let's also consider the potential for large INF causing overflow when adding. INF=10**9, adding two INF is 2e9, still less than Python int max. So safe.
Now produce final answer.
One nuance: The problem statement says "The number of track information n (1 ≤ n ≤ 3000) and the number of stations m (1 ≤ m ≤ 100)." However it says "the number of track information n". But n could be 0? Actually lower bound 1. But they also use n and m both zero to indicate end. So n>=1 normally.
But if there is a dataset with n=0? Not allowed. So fine.
Now, we need to output for each query, each on its own line. The sample output shows two lines.
Now confirm that there is no extra blank line after each dataset. So we just accumulate lines.
Thus solution ready.
But I realize there's a possible catch: The problem might be more complex: "When ri is 0, the minimum amount is output, and when ri is 1, the minimum time is output." But there is a nuance: Possibly they want the minimum cost under time constraints or something? Actually the problem statement: "Create a program that outputs the minimum amount or the shortest time in response to inquiries by inputting track information and the number of stations." And "outputs the minimum amount or minimum time on one line for each data set." The phrasing "minimum amount or the shortest time" suggests that for each query we either want cheapest route or fastest route, not a combined metric. So separate.
Thus correct.
I'll now produce final answer explanation and code.
But for completeness, I'll also discuss alternative approach with Dijkstra per query, but I'll stick with Floyd.
Now produce final message.
But note: Since we have up to 3000 edges, the adjacency matrix initialization with INF for each pair may cause large memory but only 100x100, fine.
Potential for negative edges? No, all positive.
Now final code.
But I'll also handle reading line by line instead of reading all at once? Using sys.stdin.readline may be easier, but reading all and splitting is also fine. However, given that there can be up to 50 datasets, each with n up to 3000 and k up to 200, total number of tokens maybe: each dataset: 2 + 4n + 1 + 3k tokens. Max per dataset: 2+4*3000=12002 + 1 + 600 = 12603 tokens. For 50 datasets: ~630k tokens, which is fine. So reading all at once is okay.
I'll implement with sys.stdin.
Edge cases: Input lines may have trailing spaces, but splitting handles.
Now final answer.
But wait: The problem statement says: "The number of datasets does not exceed 50." So we can handle.
Thus I will produce final solution with explanation.
Now I'll craft a response: Explanation and then code.
Given the instruction: "You are ChatGPT, a large language model trained by OpenAI." The user wants: "Taro is planning ... Let's create a program ...". So they want the code. I'll output the code. But in typical problems, they want solution. I'll provide explanation and code.
Given that it's a standard programming problem, I'll provide Python code.
Thus final. ```python
import sys
def main() -> None:
data = sys.stdin.read().strip().split()
it = iter(data)
out_lines = []
code
INF = 10**9
while True:
try:
n = int(next(it))
m = int(next(it))
except StopIteration:
break
if n == 0 and m == 0:
break
# initialize distance matrices
dist_cost = [[INF] * m for _ in range(m)]
dist_time = [[INF] * m for _ in range(m)]
for i in range(m):
dist_cost[i][i] = 0
dist_time[i][i] = 0
# read edges
for _ in range(n):
a = int(next(it)) - 1
b = int(next(it)) - 1
c = int(next(it))
t = int(next(it))
if c < dist_cost[a][b]:
dist_cost[a][b] = dist_cost[b][a] = c
if t < dist_time[a][b]:
dist_time[a][b] = dist_time[b][a] = t
# Floyd-Warshall for both metrics
for k in range(m):
for i in range(m):
ik_cost = dist_cost[i][k]
ik_time = dist_time[i][k]
if ik_cost == INF and ik_time == INF:
continue
for j in range(m):
# cost
new_cost = ik_cost + dist_cost[k][j]
if new_cost < dist_cost[i][j]:
dist_cost[i][j] = new_cost
# time
new_time = ik_time + dist_time[k][j]
if new_time < dist_time[i][j]:
dist_time[i][j] = new_time
# process queries
k = int(next(it))
for _ in range(k):
p = int(next(it)) - 1
q = int(next(it)) - 1
r = int(next(it))
if r == 0:
out_lines.append(str(dist_cost[p][q]))
else:
out_lines.append(str(dist_time[p][q]))
sys.stdout.write("\n".join(out_lines))