We are given a directed weighted complete graph on n vertices (i.e., between any two distinct vertices there is an edge in both directions, but weights can be different for each direction). Greg will remove vertices one by one according to a given order x1, x2, ..., xn. Before each deletion (i.e., at step i, we consider the graph before removing vertex xi, which still includes all vertices that have not been removed yet? Actually careful: The description: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. So before step i, we consider the graph that currently exists (i.e., after previous i-1 deletions). Then we compute the sum of all-pairs shortest paths among the vertices that will remain after deletion? Wait: The definition: "Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices." That seems ambiguous: "remaining vertices" at that moment? But step i is about to remove xi. At that moment, before removal, all vertices that have not yet been removed are present (including xi). However, the sum they want is for all pairs of the remaining vertices? Could be interpreted as: before deleting xi, we consider the graph as it is (with all vertices not yet deleted, i.e., vertices from {x_i, x_{i+1},...,x_n}? Actually the deletion order is given: x1, x2, ..., xn are the vertices deleted at each step. So at step 1, we delete x1. At that moment before deletion, all n vertices are present. The "remaining vertices" after deletion would be n-1 vertices (excluding x1). But the phrase "between all pairs of the remaining vertices" might refer to vertices that will remain after the deletion? Or perhaps it's the vertices that are still present before deletion (including xi) but "remaining" meaning those not yet removed? Since they say "the sum of lengths of the shortest paths between all pairs of the remaining vertices." In typical "removal order" problems (like Floyd-Warshall in reverse), they ask for the sum of distances among the vertices that have not yet been removed at that point in time (i.e., after previous deletions). But here the phrasing: "Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices." Typically, "remaining vertices" are those that are still in the graph at that moment, i.e., after previous deletions? Let's read: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. That suggests: At step i, before executing the removal, the graph currently has certain vertices (those not removed yet). But which ones have been removed already? Steps 1 to i-1 have already removed vertices x1,...,x_{i-1}. So before step i, those vertices are already gone. The "remaining vertices" are those that are still present, i.e., the set V_i = {x_i, x_{i+1}, ..., x_n} (since those are the ones not yet removed). And they want the sum of all-pairs shortest paths over those vertices, using the graph that exists at that moment (which has edges only among the vertices that have not been removed). Then after computing that sum, they proceed to delete vertex xi, moving to step i+1.
But wait: The example: Input 2:
0 5
4 0
1 2
Output: 9 0
We have two vertices: 1 and 2. Deletion order: 1 then 2.
Let's compute: Initially before any deletion (step 1) the graph has both vertices. Sum of distances: shortest paths between all pairs of remaining vertices (which at step 1 are vertices 1 and 2? But also 1 is still present, because it hasn't been removed yet. But after step 1 removal, vertex 1 will be removed, but before removal we consider the graph with both vertices. "Remaining vertices" could be interpreted as the vertices that will remain after removal (i.e., after deleting vertex 1, the remaining vertex is 2). But then the sum over all pairs among {2} is 0. That would be for step 1? But output first number is 9, then 0. So step 1 output is 9, which corresponds to sum over both vertices? Let's compute all-pairs shortest path sum for both vertices: distances: d(1,1)=0, d(2,2)=0, d(1,2) =? There is an edge from 1 to 2 weight 5, and also possibly other paths? Could there be a shorter path via other vertices? Only two vertices, so the direct edge weight 5 is the shortest from 1 to 2. Similarly from 2 to 1, weight 4. So sum = 0+5+4+0 = 9. So that's 9. Then step 2: before deleting vertex 2, the remaining vertices? At step 2, after deleting vertex 1, the graph contains only vertex 2. So sum over all pairs (just 2) is 0. Output second number is 0. This matches interpretation: at step i, we consider graph after previous deletions, i.e., vertices that are still present (not yet removed), and compute all-pairs shortest paths among them. Then we remove xi.
Thus the process: Initially we have all vertices. Then for i from 1 to n: compute sum of distances among current set of vertices (those that have not been removed yet, which are {xi, xi+1, ..., xn}) and output it; then remove xi from the graph.
So we need to output n numbers: first for the initial full graph (i=1) before any deletion? Actually step 1: before removing x1, graph has all n vertices. So sum over all pairs among all n vertices. Then remove x1. Then step 2: before removing x2, graph has n-1 vertices (all except x1). So sum over that subset. Then step 3: before removing x3, graph has n-2 vertices (all except x1,x2). ... Finally step n: before removing xn, graph has only vertex xn. Sum=0. Output after that? They print n numbers: the i-th number equals the required sum before the i-th step. So the first number corresponds to i=1 (full graph), last number corresponds to i=n (graph with only xn). That matches example.
Now constraints: n ≤ 500. Edge weights up to 1e5. Directed graph.
We need to compute the sum of all-pairs shortest paths for each "phase" (i.e., after some vertices have been removed) efficiently.
The natural approach: process deletions in reverse order. That is, start from an empty graph (no vertices) and add vertices in reverse order of deletion (i.e., start from the last vertex to be removed, then second last, ... up to the first). When we add a vertex, we need to update the all-pairs distances to incorporate the new vertex and edges to/from existing vertices. Then at each addition step, we can compute the sum of distances among the current set of vertices. Then output these sums in reverse order (since we will compute sums after adding vertices in reverse order; but we need sums before each deletion step, which correspond to the state after adding vertices in reverse order: after adding vertex xn, we have set {xn} (which corresponds to state before deletion of xn). After adding vertex x_{n-1}, we have set {x_{n-1}, xn} (corresponds to state before deletion of x_{n-1}), etc. After adding all vertices we have full set (state before first deletion). So we can produce outputs in reverse order: the sum after adding the k-th vertex (starting from the last) corresponds to the sum before deletion step (n - k + 1). So we can compute sums and store them in an array ans[1..n] where ans[i] is sum before deletion step i. Then we will fill ans from n down to 1.
Thus problem reduces to: We have a dynamic graph where we insert vertices one by one (with all edges connecting the new vertex to existing vertices). After each insertion, we need to compute the sum of all-pairs shortest distances among the current vertex set (size s). Need to support up to 500 vertices, so we can afford O(n^3) overall if we do Floyd-Warshall updates? Floyd-Warshall normally O(n^3). If we run Floyd-Warshall from scratch after each insertion, that would be O(n^4) (n insertions * O(n^3)) which is 500^4 = 62.5e9, too high. But we can use a variant: since we are adding vertices in reverse order, we can treat the process as building the graph gradually. The classic approach: Use Floyd-Warshall but in reverse order: When we add a new vertex k, we consider it as an intermediate node for shortest paths. Since we are adding vertices, we can update the distance matrix by considering the new vertex as a possible intermediate node for all pairs. But also we need to add direct edges from and to the new vertex.
Specifically, we maintain a distance matrix dist for the current set of vertices. Initially, before any insertion, the set is empty. We'll maintain the vertex labels (original indices). As we add vertices in order: let's denote the order of addition as y1 = xn, y2 = x_{n-1}, ..., yn = x1. So at step t we add vertex yt. At that moment we have a set of vertices V_current with size t-1. We have a mapping from label to index? We'll maintain dist as a square matrix over the vertices that have been added, but we need to know which positions correspond to which original vertices. Since n ≤ 500, we can maintain an n x n matrix for all vertices, but only consider distances for vertices that are present. We could maintain the full n x n distance matrix with INF for distances involving vertices not yet added. However, when we compute sum of distances only among present vertices, we can simply ignore non-present. But the Floyd update with new vertex as intermediate should work across all vertices (including not yet added?) Not needed. Let's think.
We can maintain a full n x n matrix dist[i][j] representing the current shortest path distance between i and j considering only the vertices that have been added so far (i.e., those that are "active"). For vertices not yet added, we may treat them as not existing, so we can set dist[i][j] = INF initially for all, and as we add vertices, we will incorporate edges.
When we add a new vertex v, we need to:
- Set dist[v][v] = 0.
- For each already active vertex u, we set dist[v][u] = weight of edge from v to u (direct), and dist[u][v] = weight of edge from u to v (direct). These edges may not be the final shortest path because there could be paths via other vertices, but we will then update all pairs using v as intermediate node: for all i,j active (including v), we can do dist[i][j] = min(dist[i][j], dist[i][v] + dist[v][j]). However, since we are adding v, the distances among existing vertices might improve if going through v. So we need to run two loops: for every active i (including v) and active j (including v), consider dist[i][v] + dist[v][j] as a candidate.
But note that the order: when we add v, we have already had distances among previous vertices optimized (they are all-pairs shortest paths using those vertices). Adding v might create shortcuts. So we need to update the distance matrix accordingly.
So we can do:
for i in active_vertices:
for j in active_vertices:
if dist[i][v] + dist[v][j] < dist[i][j]:
dist[i][j] = dist[i][v] + dist[v][j]
This is essentially one iteration of Floyd-Warshall with v as intermediate. Since we process vertices in a specific order, doing this when adding v will produce correct all-pairs shortest paths for the enlarged set.
Complexity: each addition, we loop over all active vertices (i and j). Initially size s, after insertion s+1. But worst-case, s up to n. So for each addition, we do O(s^2) updates. Over all additions, total O(n^3) because sum_{s=1}^{n} s^2 = n(n+1)(2n+1)/6 = O(n^3). So overall O(n^3). n=500 => 125 million operations approx, which is fine in C++.
But we also need to compute the sum of distances after each insertion. That sum can be maintained incrementally: we can compute total sum of all distances among current active vertices. When we add a new vertex v, we need to update the total sum to include distances between v and all existing vertices (both directions) and also account for improvements in distances among existing vertices due to v acting as intermediate.
If we simply recompute sum from scratch each time O(s^2), total O(n^3) as well, still fine. But we might as well update incrementally for efficiency. Since O(n^3) already, recomputing sum O(s^2) per insertion adds also O(n^3) total, so total O(n^3) still okay. 500^3 = 125 million, plus constant factor. That's okay in 2 seconds in C++ with simple loops.
But careful: We also need to handle that after adding v, distances among existing vertices may change because they can go via v. So the sum of distances among existing vertices may decrease. To update the total sum correctly, we could recalc the whole sum each time by iterating over all pairs of active vertices. That would be O(s^2) per step, sum O(n^3). Acceptable.
Thus approach:
- Read n, adjacency matrix w[1..n][1..n] (weights, note w[i][i]=0).
- Read deletion order x[1..n].
- Prepare reverse order: add_order = reverse(x) i.e., [x_n, x_{n-1}, ..., x_1].
- Initialize an array active[1..n] bool false.
- Initialize dist[n+1][n+1] with INF (maybe large number). We'll use long long (64-bit).
- For each step t from 1 to n:
v = add_order[t] (1-indexed t? we can loop from 0 to n-1)
active[v] = true.
dist[v][v] = 0.
// set direct edges from v to all active u and from active u to v.
for each u such that active[u] is true:
if u == v: continue
dist[v][u] = w[v][u];
dist[u][v] = w[u][v];
// now update all pairs using v as intermediate.
// We need to consider all i,j that are active.
// Since v may improve distances between i and j, we need to loop i,j over active vertices.
// The typical Floyd-Warshall update: for all i,j: if dist[i][v] + dist[v][j] < dist[i][j], update.
// But careful: When we update some dist[i][j], that could affect later comparisons using updated dist[i][v]? Usually Floyd order is such that we fix intermediate and update all pairs. Doing it with v as the intermediate, we can safely update all i,j in any order because we only use dist[i][v] and dist[v][j] which are not going to change in this iteration if we ensure we use the current values? Actually if we update dist[i][j], that's fine. But if we later update dist[i][v] or dist[v][j] during the same loops, that could cause further improvements? However, we are only setting direct edges from v to u and u to v earlier. Those dist[i][v] and dist[v][j] should be final for this step (since we haven't yet considered paths that go through other vertices to reach v, but v is the new vertex, so the only way to reach v is via direct edges from other vertices because v was not previously present. However, could there be a shorter path from i to v that goes through some other vertex j that is also active? For i to v, with v as the new vertex, the shortest path from i to v could potentially be i -> k -> v if there is an edge from k to v. But we set dist[i][v] initially as w[i][v] (direct). If there is a path i -> k -> v that is shorter, that would be discovered when we consider k as intermediate? But k is already active, and before adding v, we had distances between i and k (which are correct). After adding v, we need to consider paths that go via v? But for i to v, v is target, so the only possible intermediate vertices that could be used are among existing vertices (excluding v). Since we have correct distances among existing vertices, we could compute the shortest path from i to v as min over k active (dist[i][k] + w[k][v]). But we haven't set that. However, in the Floyd update phase, if we do for all i,j: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) with k = v, this only considers paths that go through v as intermediate, not paths that go through other vertices to reach v. So to correctly compute dist[i][v], we need to consider paths from i to v that may use other intermediate vertices (other than v). But v is the new vertex; such paths would use existing vertices as intermediate. How can we compute them? One approach: After setting direct edges, we should run a full Floyd-Warshall step: for each i active, for each j active, consider dist[i][v] + dist[v][j] and dist[i][v] and dist[v][j] are being updated? Actually we need to consider that dist[i][v] could be improved by going via some other vertex k that was already active. But that would be discovered when we later consider k as intermediate in future insertions, but since we are adding vertices one by one, we must ensure that after adding v, all distances involving v are correct, including paths that go i -> k -> v. This suggests that we need to run a full Floyd-like update using all vertices as intermediates, but only for pairs involving v? Alternatively, we can treat the insertion as: we have current distance matrix D for set S (size s). When adding new vertex v, we need to compute shortest paths between all pairs in S ∪ {v}. This can be done by initializing D(v, u) = w(v, u) and D(u, v) = w(u, v) for u in S. Then for all i,j in S ∪ {v}, we can set D(i,j) = min(D(i,j), D(i,v) + D(v,j)). However, does this capture paths like i -> k -> v? Let's test: For D(i, v), initially set to w(i, v). After we run the update step with v as intermediate, we might update D(i, v) as min(D(i, v), D(i, v) + D(v, v)? That is D(i, v) + 0, no improvement. Or D(v, v)+ D(v, v)? Not relevant. The update D(i, v) = min(D(i, v), D(i, v) + D(v, v)) = D(i, v). So no change. But could there be a path i -> k -> v that is shorter than w(i, v)? That would require using an intermediate k from S. However, we are not using k as intermediate in this update. But note: The all-pairs shortest paths for the set S∪{v} can be computed by running Floyd-Warshall where we allow all vertices in S∪{v} as intermediates. Since we already have correct distances among S, and we are adding v, we need to consider all pairs i,j and consider both possibilities: i->v->j and also i->k->v and v->k->j? Actually to get correct distances, we need to consider all intermediates from S∪{v}. The classic way to insert a vertex is to use it as a pivot: for all i,j in S∪{v}, we can update D(i,j) = min(D(i,j), D(i,v) + D(v,j)). However, does this also incorporate paths that use other vertices as intermediates for paths involving v? For distances between two existing vertices, the update with v as intermediate may improve them. For distances from existing vertex i to v, we need to consider paths i -> ... -> v that might go through other existing vertices before reaching v. But such a path would be i -> k -> v, where k is in S. Since we already have D(i,k) (correct), and we have D(k, v) initially set as w(k, v) (direct). So D(i,k) + D(k,v) is a candidate for D(i, v). However, to capture that, we need to consider k as an intermediate. Since we are only doing an update with v as intermediate, we won't capture i -> k -> v. But note: In the final all-pairs distances for S∪{v}, the distance from i to v can be expressed as min( w(i,v), min_{k in S} (D_S(i,k) + w(k,v)) ). Where D_S(i,k) are the correct distances among S. So we need to compute this min. Similarly for v to j: min(w(v,j), min_{k in S} (w(v,k) + D_S(k,j)) ). And for i to j: min( D_S(i,j), min_{k in S} (D_S(i,k)+w(k,v)+D_S(v,j)? Actually not symmetric) Wait, careful: The Floyd update with v as intermediate will compute for i,j: min(D_S(i,j), D_S(i,v) + D_S(v,j)). But D_S(i,v) we only have as w(i,v) initially. So it does not consider paths i -> k -> v. So it will not capture improvements like i -> k -> v -> ...? But for i to j, it might capture paths i -> v -> k -> j? Actually if we have i -> v -> k -> j, that would be i->v and then a path from v to j that might go through other vertices. But after update with v as intermediate, we are only doing one hop via v. However, we could also have i -> k -> v -> ... This would require two intermediates (k and v). But we are not performing updates that use both k and v as intermediates. However, if we later in subsequent insertions use other vertices as intermediates, but we are only inserting vertices in this order; after insertion of v, we won't be inserting any more vertices that could serve as intermediates for these paths? Actually after insertion of v, all vertices that will be present are exactly S∪{v}. We have not yet added other vertices? But we are adding vertices in reverse deletion order: we start with empty, then add the last deleted vertex, then second last, etc. So when we add v, the set S is the set of vertices that were deleted later than v (i.e., will be removed after v in original order). But in the original process, at the state before deletion of v (i.e., after some deletions?), the graph includes v and also vertices that were deleted later? Let's map: In the original process, vertices are deleted in order x1, x2, ..., xn. So before deletion of xi, the remaining vertices are {xi, x_{i+1}, ..., xn}. So the set of vertices present when we consider before deleting xi includes xi and all vertices with larger index in deletion order. So in reverse order insertion, we first add xn (the last to be deleted). That corresponds to state before deletion of xn (which is only xn). Then we add x_{n-1} (the second last) to get state before deletion of x_{n-1} (which has {x_{n-1}, xn}). So the insertion order is exactly the order of vertices as they appear in the graph when moving backwards. So when we add a vertex v = x_{i} (with i from n down to 1), the set S already contains vertices that were deleted after v (i.e., x_{i+1}, ..., x_n). In the original graph at the time before deletion of v, all vertices present are exactly v ∪ S. So the all-pairs distances should be computed on the induced subgraph of the original full graph (which has edges between all pairs) but only using those vertices. So the shortest path between any two vertices can go through any of the vertices in v ∪ S. Since we are adding vertices in increasing order of "time" in the original process, we need to compute distances correctly for the entire set at each step. The standard trick for such dynamic APSP under vertex additions (in reverse deletion order) is to treat the added vertex as the latest (i.e., as the "new" intermediate) and run Floyd-Warshall updates using that vertex as intermediate, because the order of intermediates in Floyd-Warshall can be any order. If we add vertices in some order, and each time we consider the newly added vertex as the next intermediate, then after processing all vertices, the distance matrix will be the all-pairs shortest paths for the full graph. And crucially, after each insertion, the distances among the current set will be correct for that set, provided that the order of intermediates corresponds to the order of insertion. This is essentially Floyd-Warshall algorithm with a specific vertex order. Floyd-Warshall works as: for k from 1 to n: for i, j: d[i][j] = min(d[i][j], d[i][k] + d[k][j]). The algorithm yields correct APSP for the graph (if we consider all vertices) regardless of the order of vertices as long as we include all vertices as intermediates exactly once. However, if we stop after processing some set of vertices (say we processed vertices in a certain order, and we have only included first t vertices as intermediates), then the distance matrix will be the shortest paths that are allowed to use only those t vertices as intermediates (plus directly as endpoints). But we also have edges among all vertices? Actually in Floyd-Warshall, initially d[i][j] is set to direct edge weight (or INF if no edge). Then as we iterate over k, we allow paths that go through vertices 1..k as intermediates. After processing all k, we have shortest paths using any vertices. If we process vertices in a different order, after processing a subset of vertices as intermediates, the distances will be the shortest paths using only those vertices (in any order). But the intermediate set is exactly the vertices that have been processed as k. So if we add vertices in some order, and after adding a vertex v we run the update using v as k (i.e., consider paths that go through v), and we have previously processed all vertices in S as intermediates, then the resulting distance matrix will be the all-pairs shortest paths where allowed intermediate vertices are exactly S ∪ {v}. That is precisely what we want: For the set of vertices that are currently active (which is S ∪ {v}), we want shortest paths that can use any of them as intermediates. Since we have already included all of them as intermediates (by processing them in the order of addition), the distances will be correct for the current set.
But careful: In our process, when we add a new vertex v, we also need to initialize direct distances to/from v. If we then perform the Floyd update with k = v (i.e., for all i,j active, dist[i][j] = min(dist[i][j], dist[i][v] + dist[v][j])), does that guarantee that we have considered all possible intermediate vertices? Prior to this step, we had already processed all vertices in S as intermediates (i.e., distances among S are already shortest using S). Adding v as a new intermediate will allow paths that go through v, but also will allow paths that go through v and then other vertices? Actually after we perform the update with v, the distances may still not be optimal if there exists a path that goes i -> v -> k -> j where k is in S, because that would require using two intermediates: v and k. However, in the Floyd-Warshall algorithm, when we process a new intermediate k = v, we only consider paths that go through v as the last intermediate (i.e., i -> ... -> v -> ... -> j, where the inner part on either side may use vertices that are already intermediates? The standard Floyd-Warshall invariant is: after processing vertices 1..k, the distance d[i][j] is the shortest path that uses only vertices among {1,..,k} as intermediate vertices (and i, j as endpoints). The recurrence d[i][j] = min(d[i][j], d[i][k] + d[k][j]) works because d[i][k] and d[k][j] are already shortest paths using vertices among {1,..,k-1} as intermediates. So the order of processing matters: we need to process vertices in a fixed order, and when we process k, we assume that the distances d[i][k] and d[k][j] are already optimal with intermediates among previous ones. So if we add vertices in some order, and each time we process the new vertex as the next k in that order, then we must have already initialized d[i][k] and d[k][j] to the direct edges? But are d[i][k] and d[k][j] already optimal with intermediates among previously added vertices? For i -> k, initially we set d[i][k] = w[i][k] (direct). But there might be a shorter path i -> ... -> k using previously added vertices (S) as intermediates. That path would have been captured if we had already processed those vertices as intermediates? However, i is in S ∪ {v}? For i in S, and k = v (new), we need d[i][v] to be the shortest path from i to v using only vertices in S as intermediates. But we haven't computed that yet because we haven't considered paths that go from i to v via S. However, in the Floyd-Warshall algorithm, before processing k = v, the distances d[i][v] are supposed to be the shortest path using only vertices in S as intermediates (since v hasn't been allowed as intermediate yet). But we only set d[i][v] to the direct edge weight. We haven't considered paths i -> some s in S -> v. So d[i][v] is not guaranteed to be optimal with intermediates from S. That breaks the Floyd invariant. So we cannot simply treat the insertion as just running the k-loop with v as the new k, because d[i][v] and d[v][j] might not be correctly computed for i, j in S.
Thus we need a more careful update when adding a new vertex.
There is known approach for this problem (reverse deletion with Floyd-Warshall) often used in problems like "Greg and Graph" (actually this is a known Codeforces problem: "Greg and Graph", CF 295B? Possibly). The typical solution: Read edges, read deletion order. Then process vertices in reverse order, each time adding the vertex and updating distances by considering the new vertex as intermediate for all pairs. But the key is to update the distance matrix by doing three nested loops over all vertices (including those not yet added?) Actually many solutions for the problem "Greg and Graph" (CF 295B?) go like this:
const int N = 505;
long long d[N][N];
int x[N];
bool used[N];
long long ans[N];
for (int k = n; k >= 1; --k) {
int v = x[k];
used[v] = 1;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
d[i][j] = min(d[i][j], d[i][v] + d[v][j]);
// then compute sum over all pairs with used vertices, store ans[k]
}
But this code snippet seems to assume that the distance matrix is initially set to the original adjacency matrix (or INF for non-edges) and that we process deletions in reverse order. Actually the typical problem: We have a graph with n vertices, and we are given deletion order. We need to output sum of all-pairs shortest path lengths after each deletion (or before each deletion). Many solutions use Floyd-Warshall in reverse: they start with an empty distance matrix (only direct edges) and then "add" vertices in reverse order, each time using that vertex as an intermediate to update all pairs, and then compute the sum for that stage. However, careful reading of such solutions reveals that they often initialize the distance matrix with the original edge weights, and then for k from n down to 1, they take v = x[k], set used[v] = true, then run two loops: for i=1..n: for j=1..n: d[i][j] = min(d[i][j], d[i][v] + d[v][j]). After that, they compute the answer for step k by summing d[i][j] for all i,j that are used (i.e., active). But note: In this algorithm, they are using d[i][v] and d[v][j] which may involve vertices that are not yet "used"? Actually they run the loops over all i,j from 1..n regardless of whether i,j are used. However, they only compute sum over used vertices. The key is that at each step (when adding vertex v), the distance matrix d[i][j] is being updated using v as an intermediate, but d[i][v] and d[v][j] might have been previously updated using other intermediates? Let's examine the state before processing step k (reverse order). Initially (before any reverse steps), we haven't processed any vertex, and d is set to the original adjacency matrix (with INF for missing edges, but here graph is complete directed, so edges exist). Then we start from k=n: v = x[n] (the last deleted vertex). We set used[v]=true. Then we run the double loop over all i,j (1..n). This will update d[i][j] = min(d[i][j], d[i][v] + d[v][j]). Since d[i][v] and d[v][j] are just direct edges (because we haven't updated them with other intermediates yet), this update might find shorter paths that go through v. But also, note that i and j can be any vertex, including those not yet used. However, later when those vertices become used, the distances may have been improved. Then after the update, we compute the answer for this step (which corresponds to the state where only vertices with used=true are present, i.e., only v is used? Actually after step k=n, used contains only x[n], so sum should be 0. They compute sum over i,j used (i.e., only v) => d[v][v]=0 => sum=0. Good.
Then we go to k=n-1: v = x[n-1], set used[v]=true. Then run the double loop over all i,j (1..n) to update distances using v as intermediate. Now note: d[i][v] and d[v][j] might have been updated in previous steps: For i that are used (maybe only x[n]), d[i][v] might have been updated? Actually after the previous step, we had run update with x[n] as intermediate, so d[x[n]][x[n-1]] could have been updated to something like d[x[n]][x[n]] + d[x[n]][x[n-1]]? That would be 0 + direct edge from x[n] to x[n-1], which is just the direct edge. But also maybe there were other paths via x[n]? Not needed. So d[i][v] is essentially the direct edge? But could there be a shorter path from i to v via x[n]? That would be i -> x[n] -> v, but i is any vertex, and if i is not used? But if i is not used (i.e., not yet added), we don't care? Actually we might have d[i][v] computed as the shortest path using only vertices that have been processed as intermediates (which are those vertices added so far, i.e., the ones with index > n-1: only x[n] initially). So for any i (even not yet used), the distance d[i][v] might be something: originally it's direct edge weight, but after processing x[n] as intermediate, we could have updated d[i][v] = min( original d[i][v], d[i][x[n]] + d[x[n]][v] ). That would incorporate a path via x[n] if shorter. So d[i][v] now is the shortest path from i to v using only vertices among {x[n]} as intermediates. That matches the Floyd invariant: After processing k = x[n], distances are shortest paths using only {x[n]} as intermediates. Then when we process v = x[n-1] as next intermediate, we want to compute shortest paths using intermediates {x[n], x[n-1]}. The Floyd algorithm would do: for i,j: d[i][j] = min(d[i][j], d[i][v] + d[v][j]), assuming that d[i][v] and d[v][j] are already shortest using intermediates {x[n]}. Are they? Yes, because after previous step, we had d[i][v] computed as the shortest using only x[n] as intermediate. That's correct. So the algorithm works if we process vertices in reverse deletion order, and we run the triple loop in that order over all vertices (i,j from 1..n, not just active), because the Floyd-Warshall algorithm with k in the order of addition (reverse deletion) will correctly compute all-pairs distances for the set of all vertices but with the restriction that only vertices that have been processed as k are allowed as intermediates. However, we are interested only in distances among a subset of vertices (the ones that are "active" at each step). But note: The Floyd-Warshall algorithm with k processed in order (like from last deleted to first) ensures that after processing a certain set of vertices as k, the distance matrix d[i][j] represents the shortest path between i and j that can use only those processed vertices as intermediates. However, the direct edges for all pairs are present initially. So for any two vertices i and j, the distance d[i][j] after processing some set of intermediates is the shortest path that may go through any of those intermediates (in any order). That is exactly the distance in the subgraph induced by all vertices? Not exactly, because the endpoints i and j themselves might not be among the processed intermediates; but the path can include any vertex as an intermediate only if it has been processed as k. So if we want the distances for the subgraph consisting only of vertices in set V_active, we need that all vertices in V_active are allowed as intermediates. In the process, at reverse step corresponding to before deletion of xi, the set of active vertices is {xi, x_{i+1}, ..., xn}. In our reverse processing, after we have added vertices in order xn, x_{n-1}, ..., x_i, we have processed exactly those vertices as k. That is exactly the set V_active (since we added them). So at that point, we have allowed all vertices in V_active as intermediates. Therefore, for any pair (u, v) both in V_active, the distance d[u][v] (computed after processing all k's up to the current point) will be the shortest path that can use any vertex in V_active as intermediate. That is exactly the distance we want.
But note: In the Floyd algorithm, the distance for a pair (u, v) is computed using all processed vertices as intermediates, but does it also consider using vertices not yet processed as endpoints? Endpoints are u and v themselves; they are allowed as endpoints regardless of whether they have been processed as k? In Floyd, endpoints are just vertices; they are part of the graph. So if both u and v are in the set V_active (which is exactly the set of processed vertices so far, because we only add vertices to used set; we never have a vertex that is in V_active but not yet processed as k? Actually when we are at reverse step after processing k = x_i (i.e., after adding x_i), the set of processed k's is {x_n, x_{n-1}, ..., x_i}. But V_active is exactly {x_i, x_{i+1}, ..., x_n} = the same set. So indeed, the set of vertices that have been used (marked used) is exactly the set of vertices processed as k. So at that moment, for any u,v in used, we have both u and v are in the processed set. However, does Floyd require that endpoints are also processed as intermediates? Not necessary; endpoints can be any vertices. But in our setting, the used set is exactly the set of vertices that have been added and thus we have allowed them as intermediates. So distances among used vertices are correctly computed.
Thus the algorithm:
- Input n, adjacency matrix w.
- Initialize d[i][j] = w[i][j] for all i,j.
- Read deletion order x[1..n].
- Initialize used[1..n] = false.
- For k from n down to 1:
v = x[k];
used[v] = true;
// Use v as intermediate to update all pairs distances
for i in 1..n:
for j in 1..n:
d[i][j] = min(d[i][j], d[i][v] + d[v][j]);
// Compute sum over all pairs where both i and j are used
sum = 0;
for i in 1..n:
if used[i]:
for j in 1..n:
if used[j]:
sum += d[i][j];
ans[k] = sum;
- Then output ans[1], ans[2], ..., ans[n].
This is the classic solution for problem "Greg and Graph". Let's verify with example 2:
n=2, w:
0 5
4 0
x: [1,2]
Processing reverse: k=2: v=2, used[2]=true.
Update: for i=1..2, j=1..2: d[i][j] = min(d[i][j], d[i][2] + d[2][j]).
Initially d[1][2]=5, d[2][1]=4, d[1][1]=0, d[2][2]=0.
Now:
i=1,j=1: d[1][1] = min(0, d[1][2]+d[2][1]=5+4=9) -> 0.
i=1,j=2: d[1][2] = min(5, d[1][2]+d[2][2]=5+0=5) ->5.
i=2,j=1: d[2][1] = min(4, d[2][2]+d[2][1]=0+4=4) ->4.
i=2,j=2: 0.
Sum used: used={2}: sum = d[2][2] =0 => ans[2]=0.
k=1: v=1, used[1]=true.
Before update, d matrix remains as above. Now update with v=1:
Loop i,j:
i=1,j=1: min(0, d[1][1]+d[1][1]=0) ->0.
i=1,j=2: d[1][2] currently 5; candidate d[1][1]+d[1][2]=0+5=5 => stays 5.
i=2,j=1: d[2][1] currently 4; candidate d[2][1]+d[1][1]=4+0=4 => stays 4.
i=2,j=2: min(0, d[2][1]+d[1][2]=4+5=9) ->0.
Now sum over used {1,2}: d[1][1]=0, d[1][2]=5, d[2][1]=4, d[2][2]=0 => sum=9. ans[1]=9.
Output ans[1], ans[2] => 9 0. matches.
Example 3: We'll test later.
Now we need to ensure that this algorithm correctly captures distances that go through multiple added vertices. Yes, because we are essentially performing Floyd-Warshall with k in reverse deletion order. Since Floyd-Warshall works for any order, the state after processing a set of vertices as k yields distances that are shortest paths using those vertices as intermediates. At the point where used set = V_active, the distances among used vertices are correct for the subgraph induced by V_active, because all possible intermediate vertices in that subgraph are exactly V_active, and they have all been processed as k. Note: In Floyd-Warshall, we process vertices one by one, and after processing a set of vertices, the distances are correct for paths that only use those vertices as intermediates. However, endpoints themselves are allowed even if not processed as k. But here endpoints are within the set, and they have also been processed as k (since they are in used). However, if a vertex is an endpoint but hasn't been processed as k yet? At the step when it's just been added (i.e., used true), it has just been processed as k in that same iteration. But after processing it as k, the distance from that vertex to others might still rely on it being an endpoint? Actually, consider after adding vertex v, we run the update with v as k. At that point, v is now allowed as an intermediate for other pairs. But distances from v to other vertices: we initially had direct edges from v to others (from original adjacency matrix). However, could there be a shorter path from v to u via some other vertex w that is already used? For example, v -> w -> u might be shorter than direct v->u. In Floyd-Warshall with order, after processing v as k, we have allowed v as intermediate but we haven't yet considered paths that use other vertices as intermediates after v? Actually, Floyd-Warshall's update with k = v uses d[i][v] and d[v][j] which are the current distances. At the moment of processing v, d[i][v] is supposed to be the shortest path from i to v using only previously processed vertices (i.e., those added later) as intermediates. For i = v? Not needed. For u (another used vertex), d[v][u] initially is direct edge weight. But there could be a path v -> w -> u where w is another used vertex (added later). Since w has been processed before v (in reverse order, we added w earlier), after processing w as k, the distance d[w][u] should be shortest using intermediates among those processed before w? Actually, careful: In reverse order, we first add xn (last deleted), then x_{n-1}, etc. So at the time we add v = x_i, the vertices added earlier are those with indices > i (i.e., deleted later). Those vertices have already been processed as k. So they are allowed as intermediates. When we run the update with v as k, we will consider paths i -> v -> j. But for the path v -> w -> u, this would be a path from v to u that uses w as intermediate. However, at the moment we process v, we are not directly considering w as intermediate for that path. But note: In Floyd-Warshall, after processing all vertices in some order, the distances are correct. For the order O = (x_n, x_{n-1}, ..., x_1), after processing v = x_i, the distances will be correct using intermediates from set {x_n,...,x_i}. The path v -> w -> u uses w as intermediate, and w is in the set (since it was processed earlier). The Floyd algorithm should capture that path when processing w? Actually, when we processed w earlier (i.e., as a previous k), we updated distances for all pairs including (v, u)? At that time, v was not yet added (not used) so distances involving v might not have been considered because d[v][][v] might have been INF? In the typical Floyd algorithm that initializes d with direct edges among all vertices, even if a vertex is not yet "used" as intermediate, its distances are still present. So initially, d[i][j] is defined for all i,j (including all vertices). So when we process w as k, we consider all i, j (including those not yet marked used). So at that time, v is a vertex but its distances are defined (direct edges). So updating with w could affect distances involving v, even though v is not yet used. For example, when we processed w = x_{i+1} earlier, we had d[v][w] = weight from v to w, d[w][u] = maybe something, and we updated d[v][u] = min(d[v][u], d[v][w] + d[w][u]). So indeed, before we even add v (i.e., before v is marked used), its distances to other vertices may have been improved by paths that go through w (a vertex added earlier). Then when we later add v and run the update with v as intermediate, we will further improve distances using v. So the distances are maintained correctly.
Thus the algorithm that updates all pairs (i,j) for all i,j from 1..n at each step, irrespective of whether they are used, works fine.
Now we need to ensure that we initialize d with direct edge weights. The graph is complete directed, so for all i != j, we have an edge weight a[i][j], and a[i][i]=0. So we can set d[i][j] = a[i][j] (int). Also, we may need to consider that there may be no direct edge? But problem says any pair of distinct vertices has an edge between them in both directions. So it's complete.
Now about INF: Since weights up to 1e5 and n up to 500, maximum path length could be up to (n-1)1e5 = 4991e5 = 4.99e7, which fits in 32-bit int? Actually 4.99e7 < 2^31, but we may have sum of distances over all pairs up to about n^2 * maxDist = 250k * 5e7 = 1.25e13, which fits in 64-bit (long long). So we need 64-bit for sums. For distances, we can use long long as well (though 32-bit is okay for individual distances). But to be safe, use long long.
We'll implement:
int n;
long long d[501][501];
int x[501];
bool used[501];
long long ans[501];
Read input.
Set d[i][j] = given weight.
Read x[1..n].
for (int k = n; k >= 1; --k) {
int v = x[k];
used[v] = true;
// Update distances with v as intermediate
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
// Check if d[i][v] and d[v][j] are not INF? Since graph is complete, all distances are finite, but we can still check.
if (d[i][v] + d[v][j] < d[i][j]) {
d[i][j] = d[i][v] + d[v][j];
}
}
}
// Compute sum
long long sum = 0;
for (int i = 1; i <= n; ++i) {
if (!used[i]) continue;
for (int j = 1; j <= n; ++j) {
if (!used[j]) continue;
sum += d[i][j];
}
}
ans[k] = sum;
}
// Output ans[1..n] in order.
That yields O(n^3) total: For each of n steps, we have two nested loops over n for the update (n^2) but wait: The update is triple loops? Actually we have for i in 1..n, for j in 1..n, which is O(n^2). But we also have an inner addition? No, the update is just a min operation inside two loops. So each step is O(n^2). Wait, we have for i and j only, but we also need to compute d[i][v] + d[v][j]. That's constant. So each step O(n^2). But earlier we thought O(n^3) for insertion? Let's see: The classic Floyd-Warshall is O(n^3) because we have three nested loops: for k, for i, for j. Here we are effectively doing for each k (n times), for i (n), for j (n). That's exactly O(n^3). But we only have two loops inside per k? Actually we have three loops: outermost is k (over n steps). Then inside we have i and j loops. That's n * n * n = n^3. Right, we have three levels: k (n), i (n), j (n). Yes, that's O(n^3). So that's fine.
But careful: In the above pseudo, the outermost loop is over k from n down to 1. Inside, we have two loops: for i, for j. So that's three loops: k (n), i (n), j (n). So O(n^3). Good.
Now verify with example 3:
Example input:
4
0 3 1 1
6 0 400 1
2 4 0 1
1 1 1 0
4 1 2 3
Let's compute manually to confirm algorithm yields output: 17 23 404 0.
We'll simulate.
n=4.
Edge matrix:
Row1: 0 3 1 1
Row2: 6 0 400 1
Row3: 2 4 0 1
Row4: 1 1 1 0
Deletion order: x1=4, x2=1, x3=2, x4=3. So deletion: first remove 4, then 1, then 2, then 3.
We need sums before each deletion:
Before step1 (full graph) sum=?
Before step2 (graph after removing 4) sum=?
Before step3 (after removing 4 and 1) sum=?
Before step4 (after removing 4,1,2) only vertex 3 sum=0.
Output: 17 23 404 0.
Let's compute with algorithm in reverse:
Reverse order: add vertices in order: x4=3, x3=2, x2=1, x1=4.
Initialize d as original matrix.
Step k=4: v=3, used[3]=true.
Update with v=3: for i=1..4, j=1..4, d[i][j] = min(d[i][j], d[i][3] + d[3][j]).
We need initial d:
d[1][1]=0, d[1][2]=3, d[1][3]=1, d[1][4]=1.
d[2][1]=6, d[2][2]=0, d[2][3]=400, d[2][4]=1.
d[3][1]=2, d[3][2]=4, d[3][3]=0, d[3][4]=1.
d[4][1]=1, d[4][2]=1, d[4][3]=1, d[4][4]=0.
Now update with v=3:
We'll compute for each i,j the candidate d[i][3] + d[3][j].
We'll compute systematically:
i=1:
j=1: d[1][1] min(0, d[1][3]+d[3][1]=1+2=3) ->0
j=2: d[1][2]=3, candidate 1+4=5 -> stays 3
j=3: d[1][3]=1, candidate 1+0=1 ->1
j=4: d[1][4]=1, candidate 1+1=2 ->1
i=2:
d[2][1]=6, candidate d[2][3]+d[3][1]=400+2=402 ->6
d[2][2]=0, candidate 400+4=404 ->0
d[2][3]=400, candidate 400+0=400 ->400
d[2][4]=1, candidate 400+1=401 ->1
i=3:
d[3][1]=2, candidate 0+2=2 ->2
d[3][2]=4, candidate 0+4=4 ->4
d[3][3]=0, candidate 0+0=0 ->0
d[3][4]=1, candidate 0+1=1 ->1
i=4:
d[4][1]=1, candidate d[4][3]+d[3][1]=1+2=3 ->1
d[4][2]=1, candidate 1+4=5 ->1
d[4][3]=1, candidate 1+0=1 ->1
d[4][4]=0, candidate 1+1=2 ->0
So no changes, essentially because v=3 doesn't help shorten any path (since direct edges are better). So d unchanged.
Now used={3}. Sum = d[3][3]=0. ans[4]=0.
Step k=3: v=2, used[2]=true.
Now we have used={2,3}. But we will update d using v=2 as intermediate (consider all i,j).
Current d as above.
Compute updates with v=2:
Candidate = d[i][2] + d[2][j].
We need d[i][2] and d[2][j] values.
d[1][2]=3, d[2][1]=6, d[2][2]=0, d[2][3]=400, d[2][4]=1, d[3][2]=4, d[4][2]=1.
Now loop i,j:
i=1:
j=1: candidate d[1][2]+d[2][1]=3+6=9 vs d[1][1]=0 ->0
j=2: candidate 3+0=3 vs 3 ->3 (equal)
j=3: candidate 3+400=403 vs d[1][3]=1 ->1
j=4: candidate 3+1=4 vs d[1][4]=1 ->1
i=2:
j=1: candidate 0+6=6 vs d[2][1]=6 ->6
j=2: candidate 0+0=0 vs 0
j=3: candidate 0+400=400 vs 400
j=4: candidate 0+1=1 vs 1
i=3:
j=1: candidate d[3][2]+d[2][1]=4+6=10 vs d[3][1]=2 ->2
j=2: candidate 4+0=4 vs 4 ->4
j=3: candidate 4+400=404 vs d[3][3]=0 ->0
j=4: candidate 4+1=5 vs d[3][4]=1 ->1
i=4:
j=1: candidate d[4][2]+d[2][1]=1+6=7 vs d[4][1]=1 ->1
j=2: candidate 1+0=1 vs 1 ->1
j=3: candidate 1+400=401 vs d[4][3]=1 ->1
j=4: candidate 1+1=2 vs d[4][4]=0 ->0
Again, no changes. So d remains unchanged.
Now used={2,3}. Sum = sum over i,j in {2,3} of d[i][j]:
d[2][2]=0
d[2][3]=400
d[3][2]=4
d[3][3]=0
Sum = 404. So ans[3] = 404. (Matches output third number? Output says third is 404? Actually output: 17 23 404 0, so third is 404, good.)
Step k=2: v=1, used[1]=true. Now used = {1,2,3} (since we haven't added 4 yet). Update with v=1.
Current d unchanged.
Candidate = d[i][1] + d[1][j].
We have d[1][1]=0, d[1][2]=3, d[1][3]=1, d[1][4]=1.
d[2][1]=6, d[3][1]=2, d[4][1]=1.
Now update:
i=1:
j=1: 0+0=0 vs 0
j=2: 0+3=3 vs 3
j=3: 0+1=1 vs 1
j=4: 0+1=1 vs 1
i=2:
j=1: 6+0=6 vs 6
j=2: 6+3=9 vs d[2][2]=0? Actually d[2][2] is 0. candidate 9 > 0, so no change.
j=3: 6+1=7 vs d[2][3]=400 -> becomes 7? Check: d[2][3] currently 400, candidate 6+1=7 is smaller, so update d[2][3] to 7.
j=4: 6+1=7 vs d[2][4]=1 -> no change (1<7).
i=3:
j=1: 2+0=2 vs 2
j=2: 2+3=5 vs d[3][2]=4 -> 4 is smaller, no change.
j=3: 2+1=3 vs 0 -> no.
j=4: 2+1=3 vs d[3][4]=1 -> no.
i=4:
j=1: 1+0=1 vs 1
j=2: 1+3=4 vs d[4][2]=1 -> no.
j=3: 1+1=2 vs d[4][3]=1 -> no.
j=4: 1+1=2 vs 0 -> no.
So the only update is d[2][3] becomes 7.
Now used = {1,2,3}. Compute sum over these three vertices:
We need d matrix after update:
d[1][1]=0
d[1][2]=3
d[1][3]=1
d[2][1]=6
d[2][2]=0
d[2][3]=7 (updated)
d[3][1]=2
d[3][2]=4
d[3][3]=0
Now compute sum:
(1,1):0
(1,2):3
(1,3):1
(2,1):6
(2,2):0
(2,3):7
(3,1):2
(3,2):4
(3,3):0
Sum = 0+3+1+6+0+7+2+4+0 = 23. Indeed ans[2] = 23 matches output second number.
Step k=1: v=4, used[4]=true. Now used all 4. Update with v=4.
Current d after previous updates:
We also have d values for vertex 4? They are still as initial (since we haven't changed them much):
d[4][1]=1, d[4][2]=1, d[4][3]=1, d[4][4]=0,
d[1][4]=1, d[2][4]=1, d[3][4]=1 (these are unchanged).
We also have the updated d[2][3]=7, etc.
Now update with v=4: candidate = d[i][4] + d[4][j].
Compute relevant d[i][4] and d[4][j]:
d[1][4]=1, d[2][4]=1, d[3][4]=1, d[4][4]=0.
d[4][1]=1, d[4][2]=1, d[4][3]=1, d[4][4]=0.
Now iterate over all i,j (1..4). We'll see which distances improve.
We'll compute systematically:
i=1:
j=1: candidate d[1][4]+d[4][1]=1+1=2 vs d[1][1]=0 -> no.
j=2: candidate 1+1=2 vs d[1][2]=3 -> update d[1][2] to 2.
j=3: candidate 1+1=2 vs d[1][3]=1 -> no.
j=4: candidate 1+0=1 vs d[1][4]=1 -> no.
i=2:
j=1: candidate d[2][4]+d[4][1]=1+1=2 vs d[2][1]=6 -> update d[2][1] to 2.
j=2: candidate 1+1=2 vs d[2][2]=0 -> no.
j=3: candidate 1+1=2 vs d[2][3]=7 -> update d[2][3] to 2.
j=4: candidate 1+0=1 vs d[2][4]=1 -> no.
i=3:
j=1: candidate d[3][4]+d[4][1]=1+1=2 vs d[3][1]=2 -> no (equal)
j=2: candidate 1+1=2 vs d[3][2]=4 -> update d[3][2] to 2.
j=3: candidate 1+1=2 vs d[3][3]=0 -> no.
j=4: candidate 1+0=1 vs d[3][4]=1 -> no.
i=4:
j=1: candidate 0+1=1 vs d[4][1]=1 -> no.
j=2: candidate 0+1=1 vs d[4][2]=1 -> no.
j=3: candidate 0+1=1 vs d[4][3]=1 -> no.
j=4: candidate 0+0=0 vs 0.
Thus updates:
d[1][2] becomes 2 (was 3)
d[2][1] becomes 2 (was 6)
d[2][3] becomes 2 (was 7)
d[3][2] becomes 2 (was 4)
Now used all 4. Compute sum over all pairs:
We'll compute new d matrix:
d[1][1]=0
d[1][2]=2
d[1][3]=1
d[1][4]=1
d[2][1]=2
d[2][2]=0
d[2][3]=2
d[2][4]=1
d[3][1]=2
d[3][2]=2
d[3][3]=0
d[3][4]=1
d[4][1]=1
d[4][2]=1
d[4][3]=1
d[4][4]=0
Now sum all 16 entries:
Row1: 0+2+1+1 = 4
Row2: 2+0+2+1 = 5
Row3: 2+2+0+1 = 5
Row4: 1+1+1+0 = 3
Total = 4+5+5+3 = 17. Indeed ans[1]=17 matches first output.
Thus algorithm works.
Now we need to implement. Note that we must use 64-bit integers for sums. Also distances may be up to 1e5 * 500? Actually max path length: 499 * 1e5 = 49,900,000? Actually 500-1=499 * 100000 = 49,900,000, less than 2^31 (2,147,483,647). So 32-bit int can hold each distance, but sum of many such distances can be up to n^2 * 5e7 = 500^2 * 5e7? Wait 500^2 = 250k, times 5e7 = 1.25e13, which exceeds 2^31. So we need long long for sum. For distances, we can keep as int to save memory? But we do additions d[i][v]+d[v][j], and that sum could be up to about 1e8, still within 32-bit signed? Actually two distances each up to ~5e7, sum up to 1e8, which fits within 2^31. But safer to use long long for distances as well.
Implementation details:
-
Use 1-indexed arrays.
-
Input: n, then n lines each with n integers.
-
Then read n integers x[1..n].
-
Initialize d as long long with given weights.
-
bool used[501] = {false}.
-
long long ans[501].
-
for k = n downto 1:
v = x[k];
used[v] = 1;
for i in 1..n:
for j in 1..n:
// if d[i][v] and d[v][j] are not INF (they are finite)
// but we can simply compute sum and compare.
if (d[i][v] + d[v][j] < d[i][j]) {
d[i][j] = d[i][v] + d[v][j];
}
// compute sum
long long sum = 0;
for i in 1..n:
if (used[i]) {
for j in 1..n:
if (used[j]) {
sum += d[i][j];
}
}
}
ans[k] = sum;
-
Print ans[1] to ans[n] separated by spaces.
Complexities: O(n^3) = 125e6 operations, which is fine in C++ with simple loops and optimizations (like using local variables, perhaps using int for indices). 125 million min operations is okay within 2 seconds? Typically 1e8 simple operations in C++ can be borderline but usually passes with optimizations (O2). n=500 -> n^3 = 125,000,000. With additional inner loop for sum (which is O(n^2) each step, also 125 million) so total about 250 million operations. Might be a bit high but still feasible in 2 seconds with optimized code? Actually the sum step itself is O(n^2) per outer k, so total O(n^3) as well: 125 million again. So total ~250 million operations. 250 million integer operations in C++ can run within 2-3 seconds on modern CPUs if optimized. We can also combine or compute sum more cleverly? But it's okay.
We can also compute sum incrementally to reduce constant factor: but not necessary.
But we can also note that we can compute sum as we update distances? However, the distances change during the update phase, which would affect sum. But we can compute sum after update. That's fine.
Edge cases: n=1. Input: 1; matrix 0; deletion order: 1. Our algorithm:
Initialize d[1][1]=0.
k=1: v=1, used[1]=true. Update loops: i=1, j=1: candidate d[1][1]+d[1][1]=0+0=0, d[1][1]=0. No change. Sum = d[1][1]=0. ans[1]=0. Output 0. correct.
Now about the problem statement: "Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier." That's typical for Codeforces. We'll use long long and cout.
Now think about potential pitfalls: In the update loops, we must ensure we use the current values of d[i][v] and d[v][j] that may have been updated earlier in the same k-iteration. In Floyd-Warshall, when we loop over i and j, if we update d[i][j] using d[i][k] and d[k][j], we must be careful that we don't inadvertently use an updated d[i][k] or d[k][j] that has been improved in the same iteration. However, the classic Floyd-Warshall algorithm processes k as the intermediate, and the inner loops over i and j can be in any order because d[i][k] and d[k][j] are not supposed to change during the k-iteration if we only update d[i][j]. Actually d[i][k] might be updated if we later process i as some j? Wait, when we fix k and iterate over i and j, we might update d[i][k] if j == k? For i any, j=k, we would update d[i][k] = min(d[i][k], d[i][k] + d[k][k]). That doesn't change because d[k][k]=0, so it's the same. Similarly d[k][j] when i=k, we update d[k][j] = min(d[k][j], d[k][k] + d[k][j]) again no change. So only when i or j equals k, the candidate is d[i][k]+d[k][k]=d[i][k] or d[k][k]+d[k][j]=d[k][j], so no improvement. Thus d[i][k] and d[k][j] remain unchanged during the k-iteration. So the order doesn't matter. Good.
Now what about d[i][v] and d[v][j] when v is the current k? They won't change because as argued above. So safe.
Thus the algorithm is correct.
Now we implement.
One more nuance: The graph is directed, but Floyd works for directed as well.
Now the problem: "Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions." So indeed it's a complete directed graph.
Thus solution: As described.
Now we need to output n integers separated by spaces.
Now we might want to use fast I/O because of large input (n=500, reading 500*500=250k numbers + 500 deletion indices). That's fine with cin/cout but we can speed up by using scanf/printf. However, they mention using cin/cout or %I64d. I'll use scanf for reading ints, and printf for output. But careful: long long printing with printf using %I64d or %lld? They say "It is preferred to use the cin, cout streams of the %I64d specifier." That suggests that if using printf, use %I64d. However, on many judges, %lld works. I'll use cout to avoid issues.
But to be safe and fast, we can use:
ios::sync_with_stdio(false);
cin.tie(0);
Then read with cin, output with cout.
Now, implementation details:
#define MAXN 505
long long d[MAXN][MAXN];
int x[MAXN];
bool used[MAXN];
long long ans[MAXN];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> d[i][j];
}
}
for (int i = 1; i <= n; i++) {
cin >> x[i];
}
// reverse order
for (int k = n; k >= 1; k--) {
int v = x[k];
used[v] = true;
// update
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (d[i][v] + d[v][j] < d[i][j]) {
d[i][j] = d[i][v] + d[v][j];
}
}
}
// compute sum
long long sum = 0;
for (int i = 1; i <= n; i++) {
if (!used[i]) continue;
for (int j = 1; j <= n; j++) {
if (!used[j]) continue;
sum += d[i][j];
}
}
ans[k] = sum;
}
// output ans[1..n]
for (int i = 1; i <= n; i++) {
cout << ans[i] << (i == n ? '\n' : ' ');
}
return 0;
}
Check: For n=500, three nested loops: k * i * j = 500500500 = 125M. The sum computation also does about the same: for each k, we do i (1..n) and j (1..n) with two ifs, but it's also O(n^2) per k, so total ~125M. Combined 250M. Might be okay.
We could micro-optimize: In the sum computation, we can iterate only over used vertices, but the used set size grows from 1 to n, so average size ~n/2, so total number of iterations in sum across all k is sum_{s=1}^{n} s^2 = n(n+1)(2n+1)/6 ~ (2/6)n^3 = n^3/3 ≈ 41.7M for n=500? Actually 500^3 = 125,000,000; dividing by 3 gives ~41.7M. That's less than 125M. So if we loop only over used vertices, we reduce the sum computation cost. However, our current loops over all i and j and check if used[i] and used[j] will still iterate n^2 per k, but the inner condition will skip many. However, the loop body still runs n^2 times (with branch). It's still 125M checks. But that's okay.
We could store list of used vertices to iterate over, but it's not necessary.
But note: The update loops also run over all i and j (n^2) each k, regardless of whether i or j are used. That's necessary because we need to update distances for all pairs, even those involving not-yet-used vertices, as they may be improved via used intermediates.
Thus total operations: ~125M (update) + 125M (sum with branches) = 250M. Should be okay in C++ with -O2.
But we could combine the sum computation with the update? Actually after updating, we need the sum. Could compute sum by initializing sum = previous sum? But distances change due to updates, so maintaining incremental sum would be complicated. Not worth it.
We'll proceed.
One more thought: The edges weights are up to 1e5 and we add them many times, but distances fit in int, but we use long long to avoid overflow when summing. In the update, we compute d[i][v] + d[v][j], which might be up to about 1e8, but still fits in int, but we store in long long anyway.
Now double-check: The algorithm uses d[i][v] and d[v][j] which may be updated earlier in the same k iteration? As argued, d[i][v] won't change because when j = v? Actually, when i is any, j = v, we compute d[i][v] = min(d[i][v], d[i][v] + d[v][v]) => no change. When i = v, j any, d[v][j] = min(d[v][j], d[v][v] + d[v][j]) => no change. So safe.
Now test with random small n to ensure.
Thus final solution.
Now let's write final answer.
But I should provide explanation in output.
Now I think it's ready.
Edge Cases: The problem states n can be 1. Works.
Now implement.
But note: In the input, the adjacency matrix may have weights for self loops as 0. So okay.
Now produce final solution.
We'll also consider using faster I/O: ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
Now code.
But one more optimization: In the update loops, we can use local variables for d, v, etc. Compiler will optimize.
Now we should test with given examples.
First example: n=1, matrix 0, order 1. Output 0.
Second: n=2, as above. Output 9 0.
Third: as above. Output 17 23 404 0.
Works.
Now about memory: d[501][501] of long long: 5015018 ≈ 2,008,008 bytes ~ 2 MB, fine.
Now finalize.
We'll produce final answer in code.
But maybe we need to consider that the graph is directed and we must compute sum over all ordered pairs? The examples indicate ordered pairs: For two vertices, sum includes both directions (i to j and j to i). In example 2, sum = 9, which includes 5+4. So yes ordered pairs.
Thus code.
Now produce final answer.
But wait: In problem statement, they said "the sum of lengths of the shortest paths between all pairs of the remaining vertices." Usually "pairs" could be unordered, but example shows ordered. Also they use d(i, v, u) defined as shortest path between v and u; it's ambiguous if it's ordered (v,u) or unordered. But from example, it's ordered. So we treat ordered pairs (i.e., sum over all ordered pairs (v,u) with v and u in remaining set). Our algorithm sums d[i][j] for all i,j used, which is ordered.
Now output.
Now done.
Let's also think if there is any trick: The Floyd update loop can be optimized by noting that we only need to update distances for pairs where either i or j is used? But we need to update all because distances for pairs (i,j) where both are not used may become used later, and we need correct distances by that time. So must update all.
Now final answer.
One more note: In the sum calculation, we might overflow if we use int, so use long long.
Now I'll produce final code.
Also, we can store ans as long long.
Now I'll produce final answer in explanation. ```cpp
#include
#include
using namespace std;
typedef long long ll;
const int MAXN = 505;
ll d[MAXN][MAXN]; // distance matrix
int x[MAXN]; // deletion order
bool used[MAXN]; // whether vertex is already added (in reverse)
ll ans[MAXN]; // answers for each step
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
// read adjacency matrix
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
cin >> d[i][j];
// read deletion order
for (int i = 1; i <= n; ++i)
cin >> x[i];
// process in reverse order
for (int k = n; k >= 1; --k) {
int v = x[k];
used[v] = true;
// Floyd‑Warshall update using v as intermediate
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
if (d[i][v] + d[v][j] < d[i][j])
d[i][j] = d[i][v] + d[v][j];
// compute sum over all ordered pairs of currently used vertices
ll sum = 0;
for (int i = 1; i <= n; ++i) {
if (!used[i]) continue;
for (int j = 1; j <= n; ++j) {
if (!used[j]) continue;
sum += d[i][j];
}
}
ans[k] = sum;
}
// output answers in original order (1 .. n)
for (int i = 1; i <= n; ++i)
cout << ans[i] << " \n"[i == n];
return 0;
}