There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
Input
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads.
Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
Output
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
Examples
Input
2
0 5
5 0
1
1 2 3
Output
3
Input
3
0 4 5
4 0 9
5 9 0
2
2 3 8
1 2 1
Output
17 12
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The matrix of shortest distances for the existing road network. This matrix is guaranteed to be derived from some undirected graph with positive integer edge weights (1 to 1000) and that the graph is connected (since all pairs have finite distances). The matrix satisfies triangle inequality and is shortest path distances.
Then we have k planned roads, each with endpoints a_i, b_i and length c_i.
We need to process these roads sequentially (i from 1 to k), and after adding each road, we need to compute the sum of shortest distances between all unordered pairs of cities (i.e., sum_{1 ≤ i < j ≤ n} d_{ij} after updates). Output these sums after each addition.
We need to be efficient because n ≤ 300, k ≤ 300. For each addition, we could recompute all-pairs shortest paths from scratch (e.g., Floyd-Warshall O(n^3) per addition) which would be O(k * n^3) = 300^4 = 8.1e9 worst-case, too high. But we can update incrementally: when adding a new edge (a,b) with weight w, the distances can only potentially decrease, and we can update the distance matrix using a procedure similar to edge relaxation: For each pair (i, j), new distance = min( old distance, distance(i, a) + w + distance(b, j), distance(i, b) + w + distance(a, j) ). Since distances are symmetric, we can compute efficiently. However, we need to be careful: after we add the first road, the distance matrix changes; subsequent roads rely on the updated distances. So we need to maintain the current all-pairs shortest distances.
Because the graph is undirected and after each addition we have a new graph, we can update the distance matrix in O(n^2) per addition? Let's think: when we add a new edge (a,b) with weight w, we can perform a kind of dynamic all-pairs shortest paths update for undirected graphs. A standard approach: after adding an edge, we can treat it as an extra edge and then for each pair (i,j), new distance = min( old distance, d(i,a) + w + d(b,j), d(i,b) + w + d(a,j) ). But the distances d(i,a), d(b,j) etc. are the current shortest distances before addition. However, note that after addition, the shortest paths may involve the new edge multiple times? Actually, in shortest paths, cycles aren't beneficial, so the new edge can be used at most once. So indeed, the only possible improvement is to use the new edge at most once. Because if you use it twice, you would have a cycle and could remove it to get a possibly shorter path not using the new edge twice. So the formula works: the new shortest distance = min( old d[i][j], d[i][a] + w + d[b][j], d[i][b] + w + d[a][j] ). Since the graph is undirected, both directions are the same.
Thus, we can update the distance matrix by checking all pairs (i,j) and applying this min. That is O(n^2) per addition. However, after we update the matrix, the distances for some pairs may change, and then the distances d[i][a] and d[b][j] used for the update are the old ones. But after we update, it's consistent because the new distances can be computed solely based on the old distances; no further propagation needed because any path that uses the new edge more than once or in combination with other improvements from other pairs is captured by considering all i,j? Actually, let's verify: Suppose we have old distances D_old. After adding edge (a,b,w), the new shortest distances D_new should satisfy:
For any i, j,
D_new[i][j] = min( D_old[i][j], min_{x,y} (D_old[i][x] + w + D_old[y][j]?) But careful: The new edge can be used at most once. However, when we consider a path i -> ... -> a -> (new edge) -> b -> ... -> j, the segments i->a and b->j are shortest paths in the old graph. But is it guaranteed that using the old distances for these segments is sufficient? After adding the new edge, there might be a path that goes i -> ... -> a -> (new edge) -> b -> ... -> j, but the segments i->a and b->j might themselves be improved by the new edge? If the new edge could improve those segments, then we would be using it more than once (i.e., the i->a segment could also use the new edge, leading to a path that uses it twice). However, we argued that using the new edge twice is not beneficial. But could there be a scenario where the best path from i to a after adding the edge is shorter than the old D_old[i][a] because it uses the new edge? For example, i -> ... -> b -> (new edge) -> a? That would indeed be a path that uses the new edge to go from b to a. That would be a candidate: i -> ... -> b -> (new edge) -> a, which is a path from i to a that uses the new edge. So after addition, the distance from i to a might decrease. Similarly, from b to j might decrease. But then a path i -> a -> (new edge) -> b -> j, using potentially improved distances for i->a and b->j, could be even shorter. However, this path would use the new edge once, but the segments i->a and b->j themselves might involve the new edge, which would mean the overall path uses the new edge multiple times (since the i->a segment might also include the new edge). Actually, if i->a uses the new edge, then the overall path would be something like i -> ... -> b -> (new edge) -> a -> (new edge) -> b -> ... -> j, which uses the new edge at least twice. But is that necessarily? Not exactly: The i->a segment might use the new edge in a way that ends at a. For the overall path i->a->(new edge)->b->j, the i->a segment ends at a, so if it used the new edge, it would have to end at a; but any path from i to a that uses the new edge must include the edge either as the last step (b->a) or earlier. For instance, i -> ... -> b -> (new edge) -> a. That uses the new edge once. Then the overall path would be i -> ... -> b -> (new edge) -> a -> (new edge) -> b -> ... -> j. That uses the new edge twice. So indeed, if the i->a segment uses the new edge, then the overall path uses it at least twice. However, could the overall path still be shortest if it uses it twice? Possibly if the double usage cancels out? But since the edge is positive weight, using it twice would add at least 2w, and you could potentially remove the cycle to get a shorter path. Let's examine: Suppose we have a path from i to j: i ... -> b -> (a,b) -> a -> (a,b) -> b ... -> j. The segment from b to b via a is a cycle: b->a (w) and a->b (w) adds 2w. This is not beneficial because you could cut it out and go directly from b to ... j. So any optimal shortest path will not use the same edge twice. In undirected graphs, a simple shortest path (without repeated vertices) exists, so indeed the new edge will appear at most once. Therefore, any shortest path from i to j that uses the new edge will be of the form i -> ... -> a -> b -> ... -> j or i -> ... -> b -> a -> ... -> j, where the subpaths i->a and b->j (or i->b and a->j) are shortest paths in the graph that do not use the new edge? Actually, they could use the new edge? They must not, because if the subpath from i to a itself used the new edge, then the whole path would use it twice. However, could there be a shortest path that uses the new edge twice but in a way that it's still optimal? As argued, because edge weights are positive, any cycle can be removed to get a path with at most the same length, actually less length if the cycle is positive. So no. So the subpaths i->a and b->j must be optimal paths in the old graph (since if they used the new edge, they'd need to include it, causing double usage). However, it's possible that after adding the new edge, there is a better path from i to a that does not use the new edge? No, the old distance D_old[i][a] is already the shortest distance without using the new edge (since the old graph didn't have it). Could the new edge provide a shorter path from i to a? Yes, as we said: i -> ... -> b -> (new edge) -> a. That's a path that uses the new edge exactly once to go from b to a. But that path uses the new edge. So D_new[i][a] could be smaller than D_old[i][a]. But in the expression for D_new[i][j] when we consider using the new edge, we consider the old distances D_old[i][a] and D_old[b][j]. But what if the best path from i to j uses the new edge, but the best subpath from i to a actually also uses the new edge? Then the whole path would be i -> ... -> b -> (new edge) -> a -> (new edge) -> b ... -> j, which uses the new edge at least twice. So that would not be optimal. However, what if the best subpath from i to a uses the new edge but in such a way that the overall path only uses it once? That would require that the subpath from i to a uses the new edge, but the overall path also uses it, leading to at least two appearances. Because the edge is undirected, if the subpath from i to a ends at a and includes the edge, it must traverse the edge at some point; after that, to then go from a to b via the new edge again, you'd traverse it again. So total traversals at least two. Unless the subpath from i to a uses the new edge but then the overall path from a to b uses the same edge in the opposite direction, but that would be traversing it again. So still two times. So not optimal.
Thus, for the optimal path that uses the new edge exactly once, the subpaths i->a and b->j must be shortest paths that do not themselves use the new edge. Therefore, they are indeed the old distances (or possibly improved by other new edges added earlier, but now we are considering incremental addition: each addition is processed sequentially, so the "old" distances are after previous additions. For the current addition, the subpaths i->a and b->j should be the distances before adding this edge, because any path that uses this new edge shouldn't also use it in the subpaths. But could subpaths use the new edge from previous additions? Yes, they could, because those are part of the old graph. That's fine; the old distances already incorporate all previous new edges. So using old distances is correct for the subpaths.
Hence the update rule: For all i,j, D_new[i][j] = min( D_old[i][j], D_old[i][a] + w + D_old[b][j], D_old[i][b] + w + D_old[a][j] ). This can be computed in O(n^2). However, note that after we update D[i][j], we also need to update distances like D[i][a] and D[i][b] for subsequent j's? But since we compute D_new based solely on D_old, we can either compute all D_new in a new matrix, or we can update in place carefully. If we update in place, we must ensure that when we compute for a given i,j, we are using the old values for D[i][a], D[b][j], etc. So we can either store old matrix separately, or we can do the update in two phases: first, we can compute potential improvements for all pairs using the old matrix, but if we modify D in place, later pairs might see updated values and incorrectly apply the relaxation again, possibly leading to incorrect further reductions? But if we update in place, then later we might consider a pair (i,j) where we have already updated D[i][j] to a smaller value; but then for that same pair we might also compute another candidate using the new edge again? That's not a problem because we take min anyway. However, the issue is that when we compute candidate for (i,j), we use D[i][a] and D[b][j]; if D[i][a] gets updated to a smaller value (due to earlier update of that entry) before we process (i,j), then the candidate might be D_new[i][a] + w + D_new[b][j], which could be smaller than the candidate based on D_old, but is that allowed? Actually, that candidate would correspond to a path that uses the new edge twice? Let's analyze: D_new[i][a] might have been updated using the new edge; i.e., D_new[i][a] could be D_old[i][b] + w or something. Then candidate D_new[i][a] + w + D_new[b][j] would be (something) + w + (something). If D_new[i][a] already uses the new edge, then the overall path from i to j would be: path from i to a that uses the new edge (say i -> ... -> b -> a) then edge (a,b) again, then path from b to j that might also use the new edge? Actually, D_new[b][j] might also use the new edge. So the overall path would contain the new edge at least twice. As argued, such a path cannot be better than a path using it at most once (because we can shortcut cycles). However, it's possible that this candidate accidentally yields a smaller number than the true shortest path? No, because if it uses the edge twice, there exists a path without that cycle that is no longer. But the candidate might still be a valid distance, but it's not optimal. However, the true D_new[i][j] should be the minimum over all simple paths; using the edge twice corresponds to a non-simple path, which we should not consider. But if we compute D_new[i][a] + w + D_new[b][j] where D_new[i][a] already used the new edge, then the candidate corresponds to a path that is not necessarily simple, but its length might still be computed; but the true shortest simple path could be shorter. However, if the candidate is smaller than the true shortest distance, that would be an error because it's not actually achievable without repeating vertices? But can a non-simple path be shorter than the shortest simple path? In graphs with positive edge weights, any path with a cycle has length greater than the path obtained by removing the cycle, so the shortest simple path is indeed the global shortest. So the candidate with double use of the new edge would be at least as large as a path that avoids the cycle. But could it be accidentally smaller than the true simple shortest path? That would imply that removing the cycle yields an even shorter path, so the candidate would not be minimal; but the algorithm might incorrectly use the candidate if it is computed. However, note that the true shortest path (without cycles) could be represented by a different combination: either using the new edge zero times or exactly once. The candidate with double use is not needed; but if it happens to be smaller than the true shortest path, that would contradict the fact that removing the cycle yields a shorter path. So it cannot be smaller; it must be >= the length after removing the cycle. That cycle-removed path is either a path with zero or one use of the new edge, which we will also consider (maybe later). However, our update method might incorrectly accept a candidate that is too small if we use updated distances that already incorporate the new edge, because that candidate might be "cheating" by reusing the edge. But since the cycle removal argument shows that such a path cannot be better than the best path with at most one use, the candidate with double use cannot be less than the min of some other candidate we already consider? Not necessarily straightforward. Let's formalize:
We have a graph G (including previous edges and previous new edges). Add a new edge e=(a,b,w). Let d_old be distances in G. Let d_new be distances in G∪{e}.
We want to compute d_new.
Claim: For any i,j,
d_new(i,j) = min( d_old(i,j), d_old(i,a)+w+d_old(b,j), d_old(i,b)+w+d_old(a,j) ).
Proof: Any shortest path in G∪{e} either does not use e, then its length = d_old(i,j). Or uses e at least once. Since weights positive, we can assume it uses e exactly once (if more, we can shortcut cycles to get rid of extra uses without increasing length). So consider a shortest path that uses e exactly once. Then it can be written as i -> ... -> a -> e -> b -> ... -> j or i -> ... -> b -> e -> a -> ... -> j. The subpaths i->a and b->j (or i->b and a->j) are entirely in G, and must be shortest paths between those pairs in G (otherwise we could replace that subpath with a shorter one to get a shorter overall path). Thus their lengths are d_old(i,a) and d_old(b,j) (or symmetric). So the candidate lengths are as given. This is standard for adding an edge to a graph with known APSP.
Thus, the update must use d_old (distances before adding this edge). Therefore, if we update distances in place, we must ensure that we do not use updated values for d[i][a] etc. So we need to either compute all d_new from d_old using a fresh matrix or store a copy of the old matrix. Since n ≤ 300, we can create a copy O(n^2) per addition, which is fine. That yields O(k * n^2) total for updates, plus the initial matrix is given (O(1) input). Then we also need to compute the sum of all pairwise distances after each update. We can compute the sum from the matrix each time, O(n^2) per addition. So total O(k * n^2) = up to 300*90000 = 27 million, which is very manageable.
But careful: The initial matrix is given. However, we need to be sure that the matrix is indeed consistent with some graph; but we don't have the original graph. That's okay because we are just updating distances based on the matrix. After each addition, we compute new distances using the formula. This formula assumes that d_old satisfies the triangle inequality and is the exact shortest distances of the current graph. But initially, we are given the matrix of shortest distances for the old roads. It should be consistent. Then after we update using the rule, the new matrix should also be the exact shortest distances for the graph with the added edge. We should verify that the update rule maintains the property that the matrix represents exact shortest distances, not just an approximation. Since we are using the correct relaxation, it should. But we must also consider that the old distances d_old might not be unique? But they are exact.
However, there is a nuance: The formula uses d_old(i,a) etc. But if after adding the new edge, some distances might improve indirectly via other pairs? For example, after adding edge e, the distance between x and y might improve not only by a direct use of e, but also by combining e with other edges that themselves have been improved? But that would be using e more than once if you try to combine two improvements? Actually, the classic dynamic update for adding a single edge to an APSP matrix is exactly: For all i, j, d_new[i][j] = min(d_old[i][j], d_old[i][a] + w + d_old[b][j], d_old[i][b] + w + d_old[a][j]). This is correct because any shortest path using the new edge can be decomposed into three parts: a shortest path from i to one endpoint of e (without using e), then e, then a shortest path from the other endpoint to j (without using e). Since the subpaths do not contain e, they are shortest in the old graph. So it's correct.
But what about after we add multiple edges sequentially? After the first addition, we have d_new that is correct. For the second addition, we treat d_new as the old distances. Then the same logic applies: the new edge (a2,b2,w2) can be used at most once, and the subpaths are in the graph that includes all previous edges, which is exactly the old graph. So using d_old for subpaths is correct. So sequential application works.
Thus, the algorithm:
Read n.
Read matrix d (n x n). (We can use 2D array of ints.)
Possibly we need to check if the input matrix is indeed a shortest path matrix, but not necessary.
Read k.
For each planned road index t from 1 to k:
read a, b, w.
Make a copy of current d matrix as d_old (or just use it carefully). Since we need d_old values for many pairs, and n is only 300, copying 90k integers is cheap (k times 90k = 27M ints copy, fine).
For each i from 1 to n:
For each j from 1 to n:
Compute candidate1 = d_old[i][a] + w + d_old[b][j]
Note: We can exploit symmetry to reduce work by half, but not needed.
After updating, compute total sum = sum_{i<j} d[i][j].
Output that sum (space-separated).
End.
Check example:
Example 1:
n=2, matrix:
0 5
5 0
k=1, road 1-2 length 3.
Old d: 0,5;5,0.
After addition, d_new[1][2] = min(5, d_old[1][1]+3+d_old[2][2]? Actually, i=1,j=2: candidate1 = d[1][1]? d_old[1][a] + w + d_old[b][j] with a=1,b=2,w=3 -> d_old[1][1]=0 +3+ d_old[2][2]=0 => 3. candidate2 = d_old[1][2]+3+d_old[1][2]? Wait a,b swapped? Actually candidate2 uses i,b and a,j: d_old[1][2] + 3 + d_old[1][2]? That gives 5+3+5=13. So min=3. So d[1][2]=3. Symmetrically d[2][1]=3. Sum over i<j = 3. Output 3. Good.
Example 2:
n=3, matrix:
0 4 5
4 0 9
5 9 0
Roads: (2,3,8) and (1,2,1)
Process first road: a=2,b=3,w=8.
We need to update d. Let's compute:
Old distances:
d(1,2)=4, d(1,3)=5, d(2,3)=9.
Now after adding edge (2,3,8): w=8.
We update each pair.
i=1,j=1 always 0, ignore.
i=1,j=2:
candidate1: d_old[1][2] + w + d_old[3][2]? Actually careful: a=2,b=3. For pair (1,2):
candidate1: d_old[1][a] + w + d_old[b][j] = d_old[1][2]=4 + 8 + d_old[3][2]=d_old[2][3]=9? Actually d_old[3][2] = 9. So 4+8+9=21.
candidate2: d_old[1][b] + w + d_old[a][j] = d_old[1][3]=5 + 8 + d_old[2][2]=0 = 13.
min(old=4,21,13)=4. So unchanged.
i=1,j=3:
candidate1: d_old[1][2]=4 +8+ d_old[3][3]=0 =>12.
candidate2: d_old[1][3]=5 +8+ d_old[2][3]=9? Wait candidate2: d_old[1][b] with b=3 ->5 +8+ d_old[a][j] with a=2,j=3 -> d_old[2][3]=9 =>5+8+9=22.
min(old=5,12,22)=5.
i=2,j=3:
candidate1: d_old[2][2]=0+8+d_old[3][3]=0 =>8.
candidate2: d_old[2][3]=9+8+d_old[2][2]=0 =>17.
min(old=9,8,17)=8.
Thus new distances: (1,2)=4, (1,3)=5, (2,3)=8.
Sum = 4+5+8=17. Output first number: 17.
Now second road: (1,2,1)
Now we have current matrix d (after first addition):
d[1][2]=4, d[1][3]=5, d[2][3]=8.
We add edge (1,2) length 1.
Update:
a=1,b=2,w=1.
For each pair:
i=1,j=2:
candidate1: d_old[1][a]=d_old[1][1]=0 +1+ d_old[2][2]=0 =>1
candidate2: d_old[1][b]=d_old[1][2]=4 +1+ d_old[a][j]=d_old[1][2]=4 =>9
min(old=4,1,9)=1.
i=1,j=3:
candidate1: d_old[1][1]=0+1+d_old[2][3]=8 =>9
candidate2: d_old[1][2]=4+1+d_old[1][3]=5 =>10
min(old=5,9,10)=5.
i=2,j=3:
candidate1: d_old[2][1]=4+1+d_old[2][3]? Wait: a=1,b=2. For i=2,j=3:
candidate1: d_old[2][a]=d_old[2][1]=4 +1+ d_old[b][j]=d_old[2][3]=8 =>13
candidate2: d_old[2][b]=d_old[2][2]=0 +1+ d_old[a][j]=d_old[1][3]=5 =>6
min(old=8,13,6)=6.
Thus new distances: (1,2)=1, (1,3)=5, (2,3)=6. Sum = 1+5+6=12. Output second number: 12. Matches sample.
So the approach works.
Edge cases: The input matrix might have distances up to maybe large, but n≤300, and edge weights ≤1000, so distances ≤ 300*1000 = 300,000. Sum of all pairs could be up to n^2/2 * 300,000 ≈ 45,000 * 300,000 = 1.35e10, which fits in 64-bit integer. So we need to use long long (int64) for sums.
Complexity: O(k * n^2) ~ 300*90,000 = 27 million operations, each operation involves a few additions and mins. That's fine.
Now we must ensure that the update formula is applied to all ordered pairs? Since the matrix is symmetric, we could update only the upper triangle, but then we also need to update the symmetric entries. Simpler: update all i and j from 1 to n (including i=j, but d[i][i] stays 0). Actually d[i][i] remains 0; the formula might produce something else? For i=j, candidate1: d_old[i][a] + w + d_old[b][i]. Since d_old[i][i]=0, the min would be 0 anyway (if d_old[i][a] + w + d_old[b][i] might be >0). So we can just compute for all i,j, it's fine. But careful: When i=j, we should keep 0; but our min might inadvertently set to something positive if we don't ensure that we consider d_old[i][i]=0. But we will compute candidate1 and candidate2 and then min with d_old[i][j] (which is 0). So it's fine.
But we must be careful with indexing: cities are numbered 1..n, we'll use 0-based for arrays but adjust.
Implementation steps:
Use vector<vector> dist(n, vector(n)).
Read n.
For i=0..n-1, for j=0..n-1, read integer into dist[i][j] (might use int, but store as long long to avoid overflow? Not necessary but safe).
Then read k.
For t=0..k-1:
read a, b, w (convert to 0-based indices: a--, b--).
Create a copy of dist (old) as vector<vector> old = dist; (or copy using assignment, or use a 2D array and memcpy if using C arrays)
Compute total sum = sum_{i<j} dist[i][j]. Since symmetric, we can sum for i=0..n-2, j=i+1..n-1.
Print total sum; if not first, print space before.
After loop, newline.
Potential optimization: Because the update uses old, we can compute without full copy by first extracting the rows/columns for a and b? Actually we need old[i][a], old[b][j], etc. We could store the old row a and column a? Not exactly; we need old[i][a] for all i, and old[b][j] for all j, etc. But we need old[i][a] and old[i][b] for each i, and also old[a][j] and old[b][j] for each j. So we could precompute arrays: old_ia[i] = dist[i][a], old_ib[i] = dist[i][b], and old_aj[j] = dist[a][j], old_bj[j] = dist[b][j] before updating. Then we can compute new dist[i][j] = min(dist[i][j], old_ia[i] + w + old_bj[j], old_ib[i] + w + old_aj[j]). However, careful: dist[i][j] might get updated during the loop if we do in-place; we would be using the updated dist[i][j] on the left-hand side, but the min uses the old dist[i][j] as a candidate. But we could store old_ij = dist[i][j] before updating? That would require storing the whole matrix anyway? Actually we need old[i][j] for each pair. So if we update in-place, we need to keep the original value for the comparison. But we could compute the new value as min(current value, candidate1, candidate2) but the current value might have been changed from earlier updates for this same i? Actually we are iterating over i and j; if we update dist[i][j] in place, later when we compute for some other i',j', we might use dist[i'][a] which might have been updated earlier (since i' could be a, or a might be some index). That would be using new values for old_ia etc., which is not allowed. So we cannot update in place without saving old values for all entries that are used in the candidates. However, we only need old values for i,a, b,j, a,j, i,b, and also for the direct old[i][j]. So if we only update dist[i][j] but we also need old values for i,a and b,j etc., these could be overwritten if we process (i,a) or (b,j) before (i,j). So to avoid copying entire matrix, we could order the loops such that we compute new values in a way that doesn't corrupt needed old values. For example, we could compute new matrix in a separate array newDist. That's simplest. Or we could try to update using a temporary matrix (like using a copy of rows for a and b, columns for a and b). But given constraints, copying the whole matrix is fine. n=300 -> 90k entries. Each entry is long long (8 bytes) -> 720KB. Copying k=300 times yields 216MB of copying if we allocate a new matrix each time? Actually each iteration we allocate a new 90k long long matrix, which is 720KB. 300720KB = 216MB, which might be borderline but still within typical memory limits? But if we allocate and deallocate each iteration, the maximum simultaneous memory is about 2720KB = 1.44MB plus overhead, not 216MB. Because each iteration we create a copy then discard it. So memory is fine. Alternatively, we can create a static copy matrix and copy using memcpy or assignment. So I'll do that.
Potential pitfalls:
The given matrix may not be "tight" in the sense that there could be multiple edges, but it's guaranteed to be a shortest path matrix. However, after adding new roads, we might have multiple edges between same cities. That's okay.
The edge we add may be longer than the current shortest distance, so no change.
The edge may be between same pair but there could already be a shorter path; we still update with min.
Could there be negative weights? No, lengths are 1..1000.
Since we compute candidate1 and candidate2 using old distances, we need to ensure that we use old distances for endpoints as they were before update. So copying old matrix is safe.
Sum calculation: after each addition, we need to output sum of shortest distances between all unordered pairs. So we compute sum from updated dist.
Now we need to verify with some additional tests:
Consider n=3, initial distances: triangle with sides: d12=100, d13=100, d23=100 (like three cities far apart, but maybe there is a central? Actually if all pairs 100, it might not be metric? It violates triangle inequality? 100+100 >= 100, okay. But is there a graph that yields all distances =100? Possibly a triangle with each edge 100. That works.
Add new road between 1 and 2 of length 1. Then new distances: d12=1, d13 = min(100, 1+100? Actually candidate: d13 via 2: d_old[1][2]=100? Wait we have to recalc correctly. old d: all 100. Add (1,2,1). New d12 = min(100, 0+1+0=1) =1. d13 = min(100, d_old[1][1]+1+d_old[2][3]=0+1+100=101, d_old[1][2]+1+d_old[1][3]=100+1+100=201) =100. d23 = min(100, d_old[2][1]+1+d_old[2][3]? Actually a=1,b=2. candidate1 for (2,3): d_old[2][1]=100 +1+ d_old[2][3]? wait correct indices: candidate1 = old[2][a] + w + old[b][3] = old[2][1]=100 +1+ old[2][3]=100 =201; candidate2 = old[2][b] + w + old[a][3] = old[2][2]=0 +1+ old[1][3]=100 =101; min(100,101,201)=100. So no change. So sum = 1+100+100=201.
But if we later add road (2,3,1), then d23 becomes 1, and d13 maybe improves: after second addition, we have d12=1, d23=1, d13 might become 2 (via 1-2-3). Using update: old distances before second addition: (1,2)=1, (1,3)=100, (2,3)=100? Wait after first addition, we had d13=100, d23=100. So add (2,3,1). Then update: d23 becomes min(100, 0+1+0=1, 100+1+100=201) =1. d13: min(100, d_old[1][2]=1 +1+ d_old[3][3]=0 =>2, d_old[1][3]=100 +1+ d_old[2][3]=100 =>201) =2. So sum = 1+2+1=4. Works.
Now test scenario where the new edge reduces distances through multiple hops indirectly? Actually the update formula will capture that because any path that uses the new edge exactly once is considered; and that might produce improvements that cascade? But after we update a pair (i,j) using the new edge, this new distance could then be used to improve other distances via the new edge? No, because that would require using the new edge multiple times. However, there could be a scenario where the new edge allows a shortcut that then makes a different pair's distance shorter not directly via the new edge but via the updated distances? For example: Add edge e between A and B. After that, the distance from A to C might decrease if C is far from A but close to B? Actually the update formula will update A-C directly if we consider pair (A,C): candidate via e uses d_old[A][A]=0 + w + d_old[B][C] -> w + d_old[B][C]. So that's handled. Similarly, B-C is updated via candidate: d_old[B][A] + w + d_old[A][C]? Wait that's symmetric. So all pairs that involve either endpoint will be updated directly. What about a pair (C,D) where neither is A nor B? Could the new edge provide a shorter path for (C,D) that goes C -> ... -> A -> e -> B -> ... -> D. That's captured by the pair (C,D) directly: candidate1 = d_old[C][A] + w + d_old[B][D]. So it's directly considered. So no need for cascading updates beyond one hop via the new edge.
Thus the O(n^2) update is sufficient.
Now ensure that we handle the possibility of multiple edges being added that could create shorter paths that involve two new edges? But we add them sequentially, so when we add the second new edge, the graph already includes the first new edge. The update for the second edge uses old distances that incorporate the first edge. So paths that use both new edges (each at most once) will be considered indirectly: For a path that uses both new edges, it would have to use the second edge exactly once, and the old distances (which include the first edge) may already include the first edge in subpaths. For example, after adding edge e1, we have distances that may use e1. Then when adding e2, for a pair (i,j) we consider candidates that go i -> ... -> endpoint of e2 -> e2 -> other endpoint -> ... -> j. The subpaths i->endpoint and other endpoint->j are computed using old distances (which may use e1). That's allowed because those subpaths do not use e2. So the overall path uses e2 once, but may also use e1 within the subpaths. That's valid. So our sequential update handles all combinations.
Hence algorithm correct.
Now we must output k space-separated integers: the total sum after each addition. The sample output shows "3 " and "17 12". Note trailing space maybe accepted.
Compute sum = 0;
for i in 0..n-2:
for j in i+1..n-1:
sum += dist[i][j];
Store or print sum.
Complexities: O(k * n^2) time, O(n^2) memory.
Let's test with a larger random scenario mentally? Not needed.
Potential improvements: Since the matrix is symmetric, we could update only for i ≤ j and set both, but copying and updating all entries is fine.
Now think about the initial matrix: It is given as the shortest distances. It might contain values that are larger than what we would compute if we had the original graph? But it's guaranteed correct.
One nuance: The input matrix might be such that there is no graph with exactly those distances? But it's given that it is a matrix of shortest distances for some set of two-way roads with integer lengths 1..1000. So it's valid.
Now, can we trust that the matrix after updates remains integral? Yes, because we only take min of sums of integers.
Now, confirm that the update formula also works when a = b? No, input ensures a != b.
Now, ensure that we don't exceed time: 27 million operations, each includes a few integer ops. In C++ that's easily under 1 second. Actually 27M is trivial.
But note: k can be 300, n=300 -> n^2 = 90k, product = 27M. However, inside the loop for each addition, we also have two nested loops to compute sum (another 45k operations). So total ~ 27M + 13.5M = 40.5M. Still fine.
Thus the solution is straightforward.
We'll implement.
Potential pitfalls: Using int for distances may overflow? Distances can be up to 300*1000=300,000. Adding three such numbers: d[i][a] + w + d[b][j] could be up to 300k+1000+300k = 601k, fits in 32-bit signed int (max ~2e9). But sums of many distances: total sum could be up to about 45k * 300k = 1.35e10, requires 64-bit. So we'll use long long for sums. We can keep distances as int to save memory, but for safety we can use long long. However, if we use int for distances, candidate sums might overflow int? 600k is fine, but if there were larger distances? Actually maximum shortest distance could be up to (n-1)*1000 = 299000. So sum of two such plus 1000 is < 600k, well within 2^31-1 (2.1e9). So int is safe. But using long long is also fine; memory is still okay. I'll use long long for consistency.
Edge case: The input matrix may have distances that are larger than typical, but still within integer? Since each road length ≤1000 and there could be up to n-1 edges on a path, max distance ≤ 299000. So int is safe.
Now the algorithm is set.
But before finalizing, we should double-check the reasoning regarding the correctness of the update when using old distances after multiple additions. The proof for a single addition is standard. For sequential additions, it's valid because each step uses the exact shortest distances of the current graph as old distances.
We might consider the possibility that after adding the new edge, the matrix might not satisfy triangle inequality? But it should because it's the shortest path matrix of a graph. So it's fine.
Now, think about an alternative: we could maintain the graph edges and run Floyd-Warshall after each addition, but that's O(k * n^3). Our approach is O(k * n^2) which is much better.
But is there any scenario where the update formula fails because the best path uses the new edge but also includes a detour that goes through the new edge's endpoints in a way that the subpaths are not the shortest in the old graph? For instance, consider a path: i -> X -> a -> e -> b -> Y -> j. The subpath i->a might not be the shortest from i to a in the old graph because perhaps there is a shorter path i->a that uses the new edge? But we argued that would cause double usage. But could there be a case where the shortest i->a path in the old graph is longer than a path that uses the new edge? But that path would use the new edge, so it's not allowed for the subpath because the subpath must be within the old graph (no new edge). However, what if the old graph already had a shorter path from i to a that didn't use the new edge? That's the shortest in old graph. If there is a path that uses the new edge that is shorter, then the subpath i->a would be shorter in the new graph but not in the old. However, then the overall path i -> (some path to a that uses e) -> e -> b -> ... j would use e twice? Let's think: Suppose we try to construct a path from i to j that uses e exactly once. The path can be written as i -> ... -> a -> e -> b -> ... -> j. The i...->a segment must not contain e, because if it did, e would appear in that segment and then again in the main edge. So the i...->a segment must be a path in the old graph (G). Therefore, its length must be at least the shortest distance in G between i and a, i.e., d_old(i,a). So the best we can do for that segment is d_old(i,a). Hence the candidate is correct. So no problem.
Thus correct.
Now code.
Implementation details: Reading input. Could use scanf for speed. But n ≤ 300, so cin with ios::sync_with_stdio(false) is fine.
I'll implement with vector<vector>.
Pseudo-code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<vector> dist(n, vector(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> dist[i][j];
}
}
int k;
cin >> k;
for (int t = 0; t < k; ++t) {
int a, b;
ll w;
cin >> a >> b >> w;
a--; b--;
auto old = dist; // copy
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
ll cand1 = old[i][a] + w + old[b][j];
ll cand2 = old[i][b] + w + old[a][j];
ll cur = old[i][j];
if (cand1 < cur) cur = cand1;
if (cand2 < cur) cur = cand2;
dist[i][j] = cur;
}
}
ll total = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
total += dist[i][j];
}
}
if (t > 0) cout << ' ';
cout << total;
}
cout << endl;
return 0;
}
But note: For each addition, we copy the entire matrix. That's fine. However, we can optimize by not copying the whole matrix but only using old values stored in arrays. Since n is small, it's okay.
Potential improvements: Instead of copying, we could compute new distances into a separate matrix and then swap. But copy is simpler.
One thing: The update loop goes over all i, j including i=j. But for i=j, dist[i][i] becomes min(0, ...) =0. So it's fine. But we could skip i=j but not necessary.
Now test with sample.
Now think about the possibility that the new edge length ci could be up to 1000, but the old distances might be large. Use long long for candidate sums to avoid overflow if we used int? Actually int is fine but we'll use long long.
Now consider an edge case: The new road may connect the same pair of cities that already have a direct road? The matrix already includes shortest distances; there might be multiple edges. Our update simply takes min, so it may reduce if the new road is shorter. That's correct.
Now test with another scenario: n=300, initial matrix corresponds to a line: distances increase linearly. Add edges that shortcut. The algorithm should work.
Now verify memory: dist is 300x300 = 90k elements. If long long (8 bytes) = 720KB. old copy similar. So about 1.44MB, fine.
Thus solution is ready.
But wait, there is a subtlety: The input matrix is given as the matrix of shortest distances for the original roads. It might contain zeros on diagonal and symmetry. However, there is also possibility that the graph has multiple edges and the matrix may not be "graph metric"? But it's fine.
Now, after adding each road, we compute the sum. The output requires after each addition, the sum of shortest distances between all unordered pairs.
Now, are there any potential pitfalls due to integer overflow when computing candidate1 = old[i][a] + w + old[b][j]? old values up to 300,000, w up to 1000, so sum up to 601,000, fits in int. But if we used int, it's safe. But using long long is also safe.
Now, I realize that the problem constraints: n up to 300, k up to 300. Our algorithm is O(k n^2) = 27M. But there might be a hidden factor: In each iteration, we have nested loops i and j, each up to n, so n^2 = 90k. Multiply by k = 27M. Actually 300*90,000 = 27,000,000. That's 27 million. Inside loop we have a couple additions and comparisons. This is definitely fine.
Thus we can implement.
However, I recall that there is a known problem "Roads in Berland" or similar, where they ask to compute the sum of shortest distances after each addition. The typical solution is indeed O(n^2) per addition using the given distance matrix.
Let's ensure we handle the case where the new road is between a and b, but the old matrix might have a shorter distance between a and b due to an indirect path. The new road length might be longer than the current shortest distance, so no change. The formula will keep it.
Now, another nuance: In the update, we might be able to improve distances for pairs where i==a or j==b, etc. It works.
Now, test with an example where adding an edge could cause a reduction in distance that involves multiple uses of the new edge? Not possible.
Now, we should consider the possibility that the graph originally had some edges that are not part of the shortest path tree but the matrix is given. We don't need the actual graph.
Thus solution complete.
Now, we can also consider if there is any scenario where the update formula might produce a distance that is not symmetric? Since we compute for all ordered pairs, both (i,j) and (j,i) will be updated similarly, and because old is symmetric, candidates are symmetric, so the resulting matrix remains symmetric.
Now, let's code.
But we need to be careful about reading input: after reading the matrix, there might be extra spaces, but it's fine.
Now, think about performance: copying the matrix each time. In C++, auto old = dist; makes a deep copy because vector<vector<>> allocates new memory. That's O(n^2) for copy. So total copy cost is O(k*n^2) = 27M assignments, which is similar to our update loop. So overall about 54M operations. Still fine.
But to be extra safe, we could avoid copying by using a temporary matrix newDist and then assign, but copying is similar.
Alternatively, we can compute new distances directly into a new matrix and then swap. That would avoid copying the old matrix (we would still need to read from old, which is the original dist). Actually if we create newDist as a copy of old, that's a copy. But we could compute newDist as an empty matrix and then fill it using old values, but we still need old values for i,a etc. So we need the old matrix unchanged. So we must have a copy of old or we must store the old values needed. Since we need old[i][j] for every i,j, we can't avoid having the old matrix accessible. So copying is necessary. But we could store old in a separate matrix and after updating, we discard it. So it's fine.
We could also do the update in place but using a technique: first compute arrays old_ia[i] = dist[i][a], old_ib[i] = dist[i][b]; also old_aj[j] = dist[a][j], old_bj[j] = dist[b][j]; and also keep the original dist[i][j] values? We need original dist[i][j] to compute min with it. If we update dist[i][j] in place, we would lose the original value. However, we could store original value in a temporary variable for each i,j? But that's essentially the same as having a separate matrix? Actually we can compute newDist[i][j] using old values from the original matrix, but we can reuse the same matrix if we ensure we read needed values before overwriting. However, since the update for each (i,j) requires old[i][a], old[b][j], old[i][b], old[a][j], and old[i][j]. If we iterate over i and j in some order, we might overwrite some of these before they are used. Could we order the loops such that for a given i, j, the values we need (like old[i][a] and old[i][b]) are rows i, which we are about to update. If we update row i, we will modify all j in that row. But old[i][a] and old[i][b] are part of row i. So if we update row i for j from 0..n-1, we would lose the original values of dist[i][a] and dist[i][b] if we update those entries early. But we could first compute the entire new row i and store it in a temporary array, then assign to row i. That would avoid overwriting needed values for other rows? However, other rows need old[a][j] and old[b][j], which are rows a and b. If we update rows a and b before other rows, we lose their original values. So we could process rows in a specific order, or we could compute all new values first in a separate matrix. That's simpler.
Thus separate matrix is the best.
Now, I'll implement as described.
Potential edge: k can be 0? But constraints say k ≥ 1. So at least one.
Now, test with a scenario where we add a road that is very long and doesn't change anything: sum remains same.
Now, consider n=300, k=300, all roads are maybe useless, sum unchanged. The algorithm will still loop.
Now, consider the possibility of integer overflow when computing sum? Use long long.
Now, think about the fact that the matrix given might not be "tight" meaning that some distances might be exactly the sum of two other distances, but that's fine.
Now, I'm ready to write final code.
But wait: I recall a known problem "Checkposts" or "Roads in Berland" where after each road you need to output sum. The typical solution uses Floyd-Warshall incremental update, but it's O(n^3) per addition if done naively. However, I'm confident that O(n^2) per addition works.
Double-check proof again: After adding edge (a,b,w), for any i, j, the new shortest path either doesn't use the new edge => length = old d[i][j]; or uses it exactly once. If it uses it exactly once, then it can be written as i -> ... -> a -> b -> ... -> j or i -> ... -> b -> a -> ... -> j. The i->...->a subpath cannot contain the new edge, else it would use it twice. So it is a path in the old graph. Moreover, its length must be equal to the shortest distance from i to a in the old graph, otherwise we could replace it with a shorter path and get a shorter overall path. So its length = old d[i][a]. Similarly, b->...->j length = old d[b][j]. So the total length = old d[i][a] + w + old d[b][j]. Similarly for the other direction. So formula correct.
Thus algorithm stands.
Now, we should consider if there is any scenario where using the new edge more than once could yield a path that is shorter than any path that uses it exactly once, due to negative cycles? But weights are positive, so no.
Hence final.
Now, implement.
Let's produce the final answer in Python? The problem is from Codeforces? Possibly but we can answer in C++.
But the user asked "Help them — for a given matrix ... find out how the sum changes..." I'm to provide solution? Likely they want an explanation or algorithm. But the context says "Help them" but this is a programming problem. The user likely expects a solution in code. Since the instruction says "Answer": I should provide an explanation and possibly code. I'll provide a concise explanation and then the C++ code.
Thus final answer: provide algorithm description and code.
Now, I'll write the final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
int n;
cin >> n;
vector<vector<ll>> dist(n, vector<ll>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> dist[i][j];
}
}
int k;
cin >> k;
for (int idx = 0; idx < k; ++idx) {
int a, b;
ll w;
cin >> a >> b >> w;
--a; --b;
// copy of current distances
auto old = dist;
// relax all pairs using the new edge
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
ll cand1 = old[i][a] + w + old[b][j];
ll cand2 = old[i][b] + w + old[a][j];
ll cur = old[i][j];
if (cand1 < cur) cur = cand1;
if (cand2 < cur) cur = cand2;
dist[i][j] = cur;
}
}
// compute sum over unordered pairs
ll total = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
total += dist[i][j];
}
}
if (idx > 0) cout << ' ';
cout << total;
}
cout << '\n';
return 0;