We need to solve the problem: given a directed weighted graph with possibly negative weights, compute all-pairs shortest paths (APSP). If there is any negative cycle reachable from some vertex? Actually typical all-pairs: we need to detect if the graph contains a negative cycle (anywhere). Since the graph may have negative cycles, and we need to output "NEGATIVE CYCLE" if there is any negative cycle, and not compute distances.
Constraints: |V| up to 100, |E| up to 9900 (which is about V^2). Edge weights up to +/- 2e7. So we can use Floyd-Warshall O(V^3) = 1e6, which is fine. However Floyd-Warshall can detect negative cycles: after the algorithm, if any diagonal entry (distance from i to i) becomes negative, then there is a negative cycle that includes i? Actually in standard Floyd-Warshall, we set initial dist[i][i] = 0. After running, if dist[i][i] < 0, it means there is a negative cycle reachable from i to i (i.e., a cycle that can return to i). However, we need to detect any negative cycle in the graph. In directed graphs, a negative cycle might not be reachable from a vertex? Actually any vertex in a negative cycle can reach itself, so its self-distance would become negative. But what if there is a negative cycle that is not connected to any vertex? That can't happen because vertices in the cycle are vertices, and they are included in the vertex set. So if we include all vertices, we have those vertices, and we set their self-dist to 0 initially. After Floyd, if any vertex has a negative self-distance, then there is a negative cycle through that vertex. However, consider the possibility that the negative cycle is not reachable from all vertices? But we are computing all pairs. In Floyd-Warshall, we consider intermediate vertices. For a vertex i that is part of a negative cycle, the algorithm will propagate and find that dist[i][i] becomes negative (since you can go around the cycle to get a negative path from i to i). Indeed, standard detection: after Floyd, check if any dist[i][i] < 0. So that works.
But careful: Floyd-Warshall with negative weights but no negative cycles: it works. With negative cycles, the distances can become arbitrarily low. However, the algorithm as typically described still computes shortest paths that may go through cycles? Actually it's designed to compute shortest simple paths if there are no negative cycles. If there are negative cycles, the distances are undefined (infinite negative). In Floyd-Warshall, if we run it without any special checks, the distances will become -infinity (but in practice they'll keep decreasing). However, the typical implementation can detect negative cycles by checking for negative diagonal after each iteration or after final. But we need to detect if there is any negative cycle, not compute distances. So we can run Floyd-Warshall, and if after algorithm we find a negative diagonal, output NEGATIVE CYCLE. But if there is a negative cycle, the algorithm might not correctly compute distances because they can be arbitrarily low, but we don't output them anyway.
But we must be cautious: The standard Floyd-Warshall code can be run as usual, but if there is a negative cycle, some distances may be incorrectly computed (like they might be reduced due to negative cycles, but the algorithm will not diverge because we only do V iterations). However, if there is a negative cycle, the distances are not well-defined; we just need to detect that. So we can run Floyd-Warshall with the usual triple loop. After the loops, if any dist[i][i] < 0, then negative cycle exists. But is this condition sufficient? In a graph with a negative cycle, the Floyd algorithm may cause dist[i][i] to become negative for vertices that are not part of the cycle but can reach the negative cycle? Actually no: dist[i][i] is initially 0. In Floyd-Warshall, the update is: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]). If there is a negative cycle that can be reached from i and returns to i, then eventually we can find a path from i to i that goes around the cycle, giving negative. If i can reach the negative cycle but not return to i? To get a negative dist[i][i], we need a cycle that starts and ends at i. If i can reach a negative cycle but not return, that does not give a negative i-i path. So dist[i][i] < 0 only if there is a negative cycle that is reachable from i and that returns to i. But what if there is a negative cycle that doesn't include i and i cannot reach it? Then i's self-distance remains 0. So we need to detect any negative cycle anywhere. If there exists a negative cycle, then let j be a vertex in that cycle. Then j can reach itself via the negative cycle, so dist[j][j] will become negative. So checking all diagonals is sufficient: if any negative cycle exists, at least one vertex on it will have negative self-distance.
But careful: In Floyd-Warshall, if there is a negative cycle, the algorithm may produce negative distances for some vertices but not necessarily for all vertices on the cycle? Actually for a vertex j on a negative cycle, we can set dist[j][j] = min(0, dist[j][k] + dist[k][j]) for some k. After considering intermediate vertices that are part of the cycle, eventually dist[j][j] becomes negative. So it should.
Thus we can implement Floyd-Warshall. However, we need to handle unreachable vertices and INF. Use a large value as infinity, e.g., 1e18 (since max path length could be V * max|d| = 100*2e7 = 2e9, plus negative maybe up to -2e9, but we need INF > any possible path. Use 10**18. Use 64-bit integers (long long in C++, but in Python int arbitrary). OK.
Now the output format: if no negative cycle, print for each vertex i (0 to |V|-1) the shortest distances to all vertices j, space-separated. If no path, print "INF". But careful: For diagonal entries (i to i), if no negative cycle, the distance should be 0 because we set initial to 0, and no negative cycles to make it negative. But after Floyd, it might become negative if there is a negative cycle; but we already check that case. So for non-negative cycles, diagonals remain 0. For unreachable paths, we output INF. Also note: If there is a path but its cost is INF? We'll manage.
Implementation in Python:
Read |V|, |E|
Initialize dist = [[INF]*V for _ in range(V)]
Set dist[i][i] = 0
For each edge: s,t,d: dist[s][t] = d (since no parallel edges)
Then Floyd-Warshall:
for k in range(V):
for i in range(V):
for j in range(V):
if dist[i][k] != INF and dist[k][j] != INF:
new = dist[i][k] + dist[k][j]
if new < dist[i][j]:
dist[i][j] = new
After loops, check for negative cycle: if any dist[i][i] < 0: print NEGATIVE CYCLE.
Else, for i in range(V): for j in range(V): if dist[i][j] == INF: print "INF", else print dist[i][j]. Print newline after each i, spaces between.
Edge Cases:
- Graph with |V|=1, maybe edges 0? dist[0][0]=0 -> output 0.
- Negative self-loop edge? The problem says no self-loops. So no direct self-loop, but negative cycles could be formed with multiple vertices.
- If there are negative weights but no negative cycles, it's fine.
- Very large V=100, E=9900 (almost complete). Floyd O(1e6) fine.
But careful: Since we are using Python, triple nested loops of 100^3 = 1,000,000, with inner Python overhead might be okay. However, the typical way to speed is to use for loops and possibly break early? But it's fine.
But one nuance: In Floyd-Warshall, if we want to detect negative cycles, we should consider that after the algorithm, the distances may be reduced by negative cycles even if we have negative cycles. For i on a negative cycle, dist[i][i] becomes negative. For vertices not on cycle, but can reach and return via cycle? For i to have negative self-dist, i must be able to reach a negative cycle and also return to i. So if there is a negative cycle that is reachable from i and that cycle can also reach i (i.e., i and the cycle are in the same strongly connected component that contains a negative cycle), then i's self-distance becomes negative. So all vertices in that SCC will have negative self-dist after Floyd? Possibly yes, because you can go from i to the cycle, go around the cycle many times to get arbitrarily negative, then return to i. Since Floyd limits to V vertices, it may only capture negative cycles exactly once? Actually Floyd computes shortest paths with at most V vertices (since you allow intermediate vertices up to V). If there is a negative cycle, you can traverse it arbitrarily many times, leading to arbitrarily low distances. But Floyd's algorithm, by considering only paths that use vertices 0..k as intermediate vertices, will not consider paths that repeat vertices? Actually the Floyd algorithm implicitly considers paths that can repeat vertices because after you include all vertices as intermediates, the path can use any vertices any number of times, as long as they are among the allowed ones. But if there is a negative cycle, the shortest path may be unbounded. However, the algorithm will still compute a finite value because it only considers paths where each intermediate appears at most once? Let's recall the Floyd algorithm: It works by dynamic programming: dist[k][i][j] is shortest path from i to j using only vertices from set {0,...,k} as intermediate vertices (not endpoints). The recurrence: dist[k][i][j] = min(dist[k-1][i][j], dist[k-1][i][k] + dist[k-1][k][j]). This DP ensures that the path doesn't repeat vertices? Actually it's known that the Floyd-Warshall algorithm computes shortest paths in graphs with possibly negative edges but no negative cycles, and it works even if there are negative cycles but then some distances become negative infinity. The algorithm as implemented with the triple loop does not automatically detect infinite negative; instead, if there is a negative cycle, then after the algorithm, the distance from i to i may become negative. However, for pairs i,j where a path can go through a negative cycle, the algorithm may produce a finite (negative) number that is not necessarily the true shortest (which is -∞). For example, consider a graph with vertices 0,1, edge 0->1 weight -1, edge 1->0 weight -1 (a negative cycle of length 2, sum -2). Then after Floyd, what is dist[0][0]? Initially 0. After including vertex 0: no change. After including vertex 1: update dist[0][0] = min(0, dist[0][1] + dist[1][0]). At that point dist[0][1] = -1 (from edge), dist[1][0] = -1, sum -2, so dist[0][0] becomes -2. So it becomes negative, indicating negative cycle. But if we ask for dist[0][1] after algorithm: Initially -1, after including vertex 0: still -1, after vertex 1: maybe can update via cycle: dist[0][1] = min(-1, dist[0][0]+dist[0][1]?) Wait careful: typical Floyd: after full run, dist[0][1] could be updated through the negative cycle: dist[0][1] = min(-1, dist[0][0] + dist[0][1])? Actually we don't have dist[0][0] + dist[0][1] because we need intermediate k: for k=0, dist[0][1] = min(-1, dist[0][0]+dist[0][1]) = min(-1, 0 + (-1)) = -1; for k=1, dist[0][1] = min(-1, dist[0][1] + dist[1][1])? Actually dist[1][1] is 0? Wait dist[1][1] = 0 initially, but after including vertex 0, dist[1][1] might become negative via 1->0->1? Let's simulate: Initially: dist[0][0]=0, dist[0][1]=-1, dist[1][0]=-1, dist[1][1]=0.
k=0 (vertex 0):
- Update for all i,j:
i=0,j=1: new = dist[0][0]+dist[0][1]=0+(-1)=-1 -> no change.
i=0,j=0: new = dist[0][0]+dist[0][0]=0 -> no change.
i=1,j=0: new = dist[1][0]+dist[0][0]= -1+0 = -1 -> no change (equal).
i=1,j=1: new = dist[1][0]+dist[0][1] = -1 + (-1) = -2 -> dist[1][1] becomes -2. So after k=0, dist[1][1] = -2.
k=1 (vertex 1):
Now dist[0][0] can be updated: new = dist[0][1]+dist[1][0] = -1 + (-1) = -2 -> dist[0][0] becomes -2.
dist[0][1] can be updated: new = dist[0][1]+dist[1][1] = -1 + (-2) = -3 -> dist[0][1] becomes -3.
dist[1][0]: new = dist[1][1]+dist[1][0] = -2 + (-1) = -3 -> becomes -3.
dist[1][1]: new = dist[1][1]+dist[1][1] = -2 + -2 = -4 -> becomes -4? Actually careful: i=1,j=1: new = dist[1][1] + dist[1][1] = -2 + -2 = -4 -> dist[1][1] becomes -4.
If we continued (but we only have two vertices so loops end). So after Floyd, dist[0][0] = -2, dist[0][1] = -3, etc. In fact, the distances keep decreasing as we use the cycle multiple times? But algorithm stops after V iterations. In this case V=2, so we get finite negative numbers, but the true shortest path from 0 to 1 is -∞ because you can go around the cycle arbitrarily many times before going to 1. But the algorithm only captures a finite number of traversals (at most V vertices? Actually the DP restricts the number of intermediate vertices, but you could still have repeated vertices? In Floyd, the paths considered are not necessarily simple; they can include repeated vertices? Let's analyze: The DP ensures that the path uses intermediate vertices only from {0,...,k} and each intermediate vertex can be used at most once? Actually the property: The path from i to j using vertices from set {0,...,k} as intermediate vertices (i and j not necessarily in set) may repeat vertices? It is known that the Floyd-Warshall algorithm, as standard, computes the shortest paths that may contain repeated vertices if there are negative cycles? For graphs without negative cycles, shortest paths are simple (no repeated vertices), so it's fine. For graphs with negative cycles, the algorithm may produce results that are not meaningful. However, our goal is to detect negative cycles and not output distances if any negative cycle exists. So after running Floyd, we check if any dist[i][i] < 0. In the example above, we find dist[0][0] = -2, so we detect negative cycle. That's correct.
Now what if there is a negative cycle that is not reachable from itself? That doesn't make sense; a cycle is by definition reachable from itself. So detection works.
But caution: In some implementations, to properly detect negative cycles, one must run an extra iteration and see if distances decrease further. However, the standard check after the algorithm is to see if any diagonal entry is negative. That should be safe.
But let's double-check with a case where a negative cycle exists but does not include any vertex directly? Actually any cycle includes vertices; each vertex in the cycle can be used as start and end. So there is at least one vertex i such that i is part of a negative cycle; then dist[i][i] will become negative. However, is it guaranteed that Floyd will set dist[i][i] negative? Consider a graph: vertices 0,1,2. Edges: 0->1 weight 1, 1->2 weight 1, 2->0 weight -3. This is a negative cycle (0->1->2->0 total -1). After Floyd, dist[0][0] should become negative. Let's simulate quickly: Initially dist[0][0]=0, dist[0][1]=1, dist[0][2]=INF? Actually there's no direct edge from 0 to 2. dist[1][2]=1, dist[2][0]=-3, others INF. Run Floyd:
k=0: updates: via 0, we can update dist[1][2]? Actually dist[1][2] = min(1, dist[1][0]+dist[0][2])? dist[1][0] INF, so no. dist[2][1]? etc. Possibly dist[2][0] remains -3. dist[1][0] maybe via 1->2->0? Not yet because k=0 only allows intermediate 0; 1->2->0 uses 2 as intermediate, so not yet. dist[1][0] maybe via 1->? Not.
k=1: intermediate vertex 1. For i=0, j=0: new = dist[0][1] + dist[1][0]? dist[1][0] is still INF? Actually we need to see if there is a path from 1 to 0 yet. At this point, from k=0 we haven't computed any path from 1 to 0. So dist[1][0] is INF? Actually initially edges: only 1->2 weight 1, 2->0 weight -3. So initially dist[1][0] INF. After k=0, still INF. So i=0,j=0: new = dist[0][1] + dist[1][0] = 1 + INF = INF -> no change. i=2,j=0: new = dist[2][1] + dist[1][0]? dist[2][1] INF? So no. i=1,j=0: new = dist[1][1] + dist[1][0]? dist[1][1]=0, so 0+INF = INF. Not change. i=2,j=2: maybe? Not.
k=2: intermediate vertex 2. For i=0,j=0: new = dist[0][2] + dist[2][0]. At this point, what is dist[0][2]? Initially INF, but after k=0 and k=1 maybe improved? Let's compute step by step:
Initialize:
dist[0][0]=0; dist[0][1]=1; dist[0][2]=INF
dist[1][0]=INF; dist[1][1]=0; dist[1][2]=1
dist[2][0]=-3; dist[2][1]=INF; dist[2][2]=0
After k=0 (vertex 0):
Update for each i,j:
i=0: j=2: dist[0][2] = min(INF, dist[0][0]+dist[0][2]=0+INF) -> no.
i=1: j=2: dist[1][2] = min(1, dist[1][0]+dist[0][2]=INF+INF) -> stays 1.
i=1: j=0: dist[1][0] = min(INF, dist[1][0]+dist[0][0]=INF+0? Actually formula: new = dist[1][0] (current) vs dist[1][0]+dist[0][0]? Wait it's dist[i][k] + dist[k][j]. So for i=1, k=0, j=0: new = dist[1][0] + dist[0][0] = INF + 0 = INF -> no.
i=1: j=1: new = dist[1][0] + dist[0][1] = INF+1 = INF -> no.
i=2: j=1: new = dist[2][0] + dist[0][1] = -3+1 = -2 -> dist[2][1] becomes -2 (since initially INF). So now dist[2][1] = -2.
i=2: j=2: new = dist[2][0] + dist[0][2] = -3+INF = INF -> no.
i=0: j=1: new = dist[0][0]+dist[0][1]=0+1=1 -> no.
i=0: j=0: new = dist[0][0]+dist[0][0]=0 -> no.
i=2: j=0: new = dist[2][0]+dist[0][0] = -3+0 = -3 -> no (equal).
i=0: j=2: etc.
So after k=0, dist[2][1] = -2.
After k=1 (vertex 1):
Now we use k=1. Updates:
We'll compute some relevant:
dist[0][2] = min( current INF, dist[0][1]+dist[1][2] = 1+1=2 ) -> dist[0][2] becomes 2.
dist[0][0] = min(0, dist[0][1]+dist[1][0] = 1+INF) -> remains 0.
dist[2][0] = min(-3, dist[2][1]+dist[1][0] = -2+INF) -> remains -3.
dist[2][2] = min(0, dist[2][1]+dist[1][2] = -2+1 = -1) -> dist[2][2] becomes -1.
dist[1][0] = min(INF, dist[1][1]+dist[1][0]=0+INF? Actually dist[1][1]=0, dist[1][0] is INF, so INF) -> remains INF.
dist[1][2] remains 1? Actually maybe could improve via 1->1? No.
dist[2][1] currently -2: maybe new = dist[2][1] + dist[1][1] = -2+0 = -2 -> stays.
dist[0][1] remains 1.
dist[1][1] might become negative? new = dist[1][1] + dist[1][1] = 0+0 =0 -> no.
dist[0][0] remains 0.
After k=1, dist[0][2]=2, dist[2][2]=-1.
After k=2 (vertex 2):
Now updates:
dist[0][0] = min(0, dist[0][2]+dist[2][0] = 2 + (-3) = -1) -> becomes -1. So dist[0][0] becomes negative.
dist[0][1] = min(1, dist[0][2]+dist[2][1] = 2 + (-2) = 0) -> becomes 0.
dist[0][2] = min(2, dist[0][2]+dist[2][2] = 2 + (-1) = 1) -> becomes 1.
dist[1][0] = min(INF, dist[1][2]+dist[2][0] = 1 + (-3) = -2) -> becomes -2.
dist[1][1] = min(0, dist[1][2]+dist[2][1] = 1 + (-2) = -1) -> becomes -1.
dist[1][2] = min(1, dist[1][2]+dist[2][2] = 1 + (-1) = 0) -> becomes 0.
dist[2][0] = min(-3, dist[2][2]+dist[2][0] = -1 + (-3) = -4) -> becomes -4.
dist[2][1] = min(-2, dist[2][2]+dist[2][1] = -1 + (-2) = -3) -> becomes -3.
dist[2][2] = min(-1, dist[2][2]+dist[2][2] = -1 + -1 = -2) -> becomes -2.
After final, many distances are negative, and self-distances for all vertices are negative (0: -1, 1: -1, 2: -2). So negative cycle detected.
So detection works.
Thus approach: Floyd-Warshall.
But there is also the possibility of using Johnson's algorithm, but Floyd is simpler.
Now we need to ensure we handle INF correctly. Since we have up to 100 vertices and edge weights up to 2e7, longest simple path could be up to 992e7 = about 2e9, but with negative edges, it could be negative but if no negative cycles, the min path could be as low as - (992e7) = -2e9. So INF must be > 1e10, and also we need to avoid overflow when adding: if dist[i][k] is INF and we add dist[k][j], we should not overflow. We'll check if dist[i][k] == INF or dist[k][j] == INF then skip. Using Python arbitrary integers, no overflow, but we want to keep performance and not cause large numbers. So we can use a sentinel like INF = 10**18, and check before addition.
Alternatively, we can use Floyd but also need to output "INF" for unreachable. So okay.
Now what about negative cycle detection? As argued, if any dist[i][i] < 0, negative cycle exists. But is it possible that a graph contains a negative cycle but after Floyd all diagonals are non-negative? I doubt it. Because for any vertex v in the cycle, the path v->...->v using the cycle will be negative. Since Floyd considers paths that can include all vertices as intermediates, it will capture that cycle (possibly multiple times). However, there is nuance: In Floyd, the path considered for v to v might be restricted to at most V vertices? Actually the DP allows any number of intermediate vertices as long as they are from the set, but does it allow repeating vertices? The recurrence ensures that the set of intermediate vertices is increasing, but it doesn't guarantee that a vertex appears more than once. For a cycle, you need to repeat vertices. In the DP, we consider paths where intermediate vertices are distinct and in increasing order? The Floyd-Warshall algorithm, as described by the recurrence, computes the shortest path among all paths where the intermediate vertices (excluding endpoints) are from {1,...,k} and no vertex appears twice? Actually it allows paths that may have repeated vertices? Let's analyze the classic Floyd-Warshall algorithm:
Let d_{ij}^{(k)} be the shortest distance from i to j using only vertices from {1,...,k} as intermediate vertices. Recurrence: d_{ij}^{(k)} = min(d_{ij}^{(k-1)}, d_{ik}^{(k-1)} + d_{kj}^{(k-1)}). Base: d_{ij}^{(0)} = weight(i,j) or INF if no edge, and 0 if i=j.
It is known that this recurrence correctly computes shortest paths for all pairs if there are no negative cycles. If there are negative cycles, then d_{ii}^{(k)} can become negative. The recurrence does not directly consider cycles that repeat vertices, but the DP may still capture them because you can use the same vertex multiple times in a path if it appears as both intermediate and endpoint? Actually the DP defines "intermediate vertices" as vertices that appear strictly between the start and end. In the path i -> ... -> j, if we allow only vertices from {1,...,k} as intermediate, and we require that these vertices are distinct? The recurrence does not enforce distinctness; however, the DP is proven to work for shortest paths when no negative cycles because the shortest path will be simple (no repeated vertices). If there is a negative cycle, then the DP can still find a negative weight path from i to i that uses the cycle once (not necessarily simple), because the cycle may be captured as a concatenation of paths that themselves may repeat vertices? I'm not fully sure.
But empirical evidence and standard textbooks (e.g., CLRS) say: After running Floyd-Warshall, one can check for negative cycles by looking at the diagonal entries: if any d_{ii} < 0, then there is a negative cycle. So it's standard.
Thus we will implement.
Now about the output: "Print a space between the costs." Means each line has values separated by single spaces, no trailing space? Usually okay. In Python we can print using join.
Implementation details:
Read input: first line: V, E. Then E lines.
But note: Input may be multiple spaces? Use split.
We'll store dist as list of lists of integers, with INF defined.
After reading edges, run Floyd.
Potential optimization: Since V up to 100, loops fine.
Edge Cases: |E| can be 0, then distances are 0 on diagonals, INF elsewhere.
Now let's think about negative cycle detection more thoroughly. Suppose there is a negative cycle that is not reachable from any vertex because the graph is directed and maybe the cycle is isolated? But it is reachable from itself; vertex on cycle can reach itself. So detection works.
But what about negative cycles that involve all vertices? Still works.
Now we have to consider that the graph may contain negative cycles, but maybe the Floyd algorithm might set dist[i][i] negative only for vertices that are on cycles that have at most V-1 edges? Actually the DP can capture cycles of length up to V (since you can use each vertex at most once as intermediate in the DP? But a cycle of length V uses V vertices as intermediates? For a cycle i->v1->v2->...->vk->i, the intermediate vertices are v1,...,vk (k vertices). In Floyd, the path i -> i using intermediates from set {0,...,V-1} can be formed if we can break the cycle into two parts: i -> k and k -> i for some k. This is exactly the recurrence: if we have a negative cycle, then for some i and k, dist[i][k] + dist[k][i] < 0. This sum might be discovered during the algorithm. Since we check all k, we will eventually set dist[i][i] to a negative value if there is any such pair. So detection is reliable.
Thus algorithm stands.
Now let's test with sample inputs.
Sample 1:
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
Run Floyd: Should output as given.
Sample 2:
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
Output matches.
Sample 3:
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
Edge 3->2 weight -7 creates a negative cycle? Let's check: vertices: 2->3 weight 1? Actually there is edge 2->3 weight 1, and 3->2 weight -7, so cycle 2->3->2: total -6, negative cycle. So output NEGATIVE CYCLE. Indeed.
Now we should confirm: Our detection would detect dist[2][2] < 0 or dist[3][3] < 0. So prints NEGATIVE CYCLE.
Now we need to ensure that we don't overflow or incorrectly treat INF additions. We'll check if dist[i][k] != INF and dist[k][j] != INF before adding.
Now coding.
Implementation:
def solve():
import sys
data = sys.stdin.read().strip().split()
if not data: return
it = iter(data)
V = int(next(it))
E = int(next(it))
INF = 10**18
dist = [[INF]*V for _ in range(V)]
for i in range(V):
dist[i][i] = 0
for _ in range(E):
s = int(next(it)); t = int(next(it)); d = int(next(it))
dist[s][t] = d # no parallel edges, so direct assignment
# Floyd-Warshall
for k in range(V):
for i in range(V):
if dist[i][k] == INF:
continue
for j in range(V):
if dist[k][j] == INF:
continue
new = dist[i][k] + dist[k][j]
if new < dist[i][j]:
dist[i][j] = new
# check for negative cycles
for i in range(V):
if dist[i][i] < 0:
print("NEGATIVE CYCLE")
return
# output
out_lines = []
for i in range(V):
line = []
for j in range(V):
if dist[i][j] == INF:
line.append("INF")
else:
line.append(str(dist[i][j]))
out_lines.append(" ".join(line))
sys.stdout.write("\n".join(out_lines))
We need to be careful: In Python, reading all and splitting may be fine. Input size small.
Now test with sample.
But before finalizing, consider potential pitfalls:
- The graph may have multiple edges? It says no parallel edges. So fine.
- The graph may have edges with weight exactly INF? No, weights within -2e7 to 2e7.
- Negative zero? Not relevant.
Now let's consider if the detection may give false positive due to overflow? Not in Python.
Now consider if we should check for negative cycles after each k? The typical detection can be done after the loops by checking diagonal. However, some implementations also check during the algorithm by seeing if dist[i][i] becomes negative, but we can just do after.
Now think about negative cycles that might cause the algorithm to produce negative self-distances for vertices not on the cycle but reachable and from which the cycle can be returned? As argued, if a vertex i can go to cycle C and come back, then i is in the same SCC as the cycle. In that case, there is a path from i to some vertex v in C, and from v to i (via the rest of SCC). Then the cycle formed by i -> ... -> v -> ... -> i includes the negative cycle? Actually the composed path may not be a simple cycle; it might contain the negative cycle as a subcycle. But we can use the negative cycle to make arbitrarily negative path from i to i: go from i to v, traverse the negative cycle many times, then return to i. That yields a negative i-i path. However, Floyd, with limited intermediate vertices, might capture some finite number of traversals, resulting in a negative value, so detection works.
Now think about the case where the graph contains a negative cycle but none of the vertices on that cycle are reachable from themselves? That is impossible; a vertex in a cycle can reach itself via the cycle.
Thus detection works.
Now we should consider potential issues with the condition dist[i][i] < 0: Since we set initial dist[i][i]=0, and there are no self-loops, the only way dist[i][i] becomes negative is via a negative cycle.
Alright.
Now the problem description: "If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print NEGATIVE CYCLE." So it's straightforward.
Now we might consider using faster algorithms like Bellman-Ford from each vertex, but V=100, that would be O(V^2 E) = 100^2 * 9900 = 99M, which might be borderline but possibly okay in Python? 99M operations maybe okay? But Floyd 1M is better.
Now about output: "Print a space between the costs." So we must have spaces. The examples show spaces, and no trailing space but we don't have to worry.
Now we need to ensure that we use the correct input format: first line: |V| |E|, then |E| lines. So we parse accordingly.
Now test with sample 1:
V=4,E=6.
Initialize dist:
0: [0, INF, INF, INF] but edges: 0->1:1,0->2:5 -> dist[0][1]=1, dist[0][2]=5; others INF.
1: edges: 1->2:2,1->3:4 -> dist[1][2]=2,dist[1][3]=4.
2: edges:2->3:1 -> dist[2][3]=1.
3: edges:3->2:7 -> dist[3][2]=7.
After Floyd:
Let's quickly simulate or trust.
Our code will produce that.
Now sample 2: with negative edge 0->2 -5: likely output as given.
Now sample 3: must detect negative cycle.
Now potential tricky: Graph with zero-weight cycle? That is not negative, so fine. Negative cycle detection only for negative sum.
Now consider if there is a negative cycle but also some vertices unreachable; detection still positive.
Now edge case: V=100, E=0, all INF except diagonal 0, output lines with 0 and INF.
Now about large INF: 10**18 is safe.
Now is there any risk that due to negative cycles, the algorithm might set dist[i][j] to a value that is less than INF but path does not exist? For example, if there is a negative cycle reachable from i but not from j? But we only care detection.
Thus solution is correct.
Now we should test manually with some small graphs.
Case 1: Single vertex V=1, E=0. Output: 0.
Our code: dist[0][0] = 0; after Floyd, diagonal 0, not negative; output "0". Good.
Case 2: Two vertices: V=2, E=1: 0->1 weight -5. No cycle. After Floyd: dist[0][0]=0, dist[0][1]=-5, dist[1][0]=INF, dist[1][1]=0. Output:
0 -5
INF 0. Should be fine.
Case 3: Two vertices: edges 0->1 weight -5, 1->0 weight 2. Sum cycle = -3? Actually 0->1->0: -5+2 = -3 negative. Negative cycle. Floyd should detect dist[0][0] negative. Let's test: Initially dist[0][0]=0, dist[0][1]=-5, dist[1][0]=2, dist[1][1]=0.
After k=0: update via 0: dist[1][1] = min(0, dist[1][0]+dist[0][1]=2+(-5)=-3) => -3. dist[1][0] maybe? new = dist[1][0]+dist[0][0]=2+0=2 no change. dist[0][0] new = dist[0][0]+dist[0][0]=0; dist[0][1] new = dist[0][0]+dist[0][1]= -5; etc.
After k=1: update via 1: dist[0][0] = min(0, dist[0][1]+dist[1][0] = -5+2 = -3) => -3. So detection works.
Thus fine.
Now think about the possibility that the graph contains a negative cycle but the diagonal entry for some vertex in that cycle does not become negative because we skip updates due to INF? That can't happen because in a cycle all vertices are connected, so distances are finite.
Thus solution is correct.
Now we may also consider the scenario where negative cycle is not detected because of order of vertices and the way we skip INF? For example, if there is a path from i to j that goes through k but dist[i][k] is INF, we skip; but if both are finite we update. That is correct.
Now about performance: triple loops with condition checks inside may be okay. Alternatively, we can use for i, for j and check inside, but we used the common optimization: if dist[i][k] is INF, skip inner j loop; else for j, if dist[k][j] != INF, then update. That's good.
Now one nuance: In Floyd, if we use INF as a sentinel, we must ensure that INF + something doesn't overflow or become a huge number. In Python, INF + something is still a huge int, but we skip those. So fine.
Now final code.
But before finalizing, double-check problem statement: Input format: first line: |V| |E|. Then each edge line: s t d. s and t are vertex indices (0 to |V|-1). No parallel edges, no self-loops. Output: If negative cycle, print NEGATIVE CYCLE. Else print matrix with spaces.
Edge Cases: Graph may have negative edges but no cycle, fine.
Now potential issue: In Floyd, we must use range(V) for k, i, j. Some textbooks use 0-indexing.
Now confirm that we set initial distances: for i=j 0; others INF; then assign edges. But what about multiple edges? Not present.
Now final code as above.
But wait: The problem may require handling of large negative values such that dist[i][j] becomes less than -2e9. That's fine in Python.
Now, what about output format: "Print a space between the costs." It also says: "If there is no path from vertex i to vertex j, print "INF"." So we must output exactly "INF". Not "inf" or "Inf". So we use "INF".
Now also note: The sample output for negative cycle is "NEGATIVE CYCLE" all caps, exactly.
Now, we should also consider that in some Floyd implementations, they detect negative cycles by checking after the algorithm if any distance on diagonal is negative. However, there is also a nuance: If there is a negative cycle, the algorithm may propagate negative infinite distances, but after finishing, the diagonal entries may become negative but not necessarily for all vertices in the cycle. But at least one will. So check all i.
Now we need to ensure we return after printing negative cycle, and not print matrix.
Now test with sample 3: Our algorithm will detect negative cycle. Let's manually simulate quickly: 4 vertices as sample. Dist initially: edges: (0,1,1), (0,2,5), (1,2,2), (1,3,4), (2,3,1), (3,2,-7). Dist matrix:
0: [0,1,5,INF]
1: [INF,0,2,4]
2: [INF,INF,0,1]
3: [INF,INF,-7,0]
After Floyd:
k=0: via 0, update:
- dist[1][2] = min(2, dist[1][0]+dist[0][2]=INF+5) -> no.
- dist[1][3] = min(4, INF+INF) -> no.
- dist[2][?] etc.
- dist[3][2] = min(-7, INF+5) -> no.
- dist[3][1] maybe? new = dist[3][0]+dist[0][1]=INF+1 -> no.
- dist[?] Actually important: dist[2][?], dist[?][?] maybe not.
- But dist[?][?] no.
- However, we may compute dist[3][?] via 0? dist[3][0] is INF, so nothing.
k=1: via 1:
Update using dist[i][1] and dist[1][j]:
- dist[0][2] = min(5, dist[0][1]+dist[1][2]=1+2=3) => becomes 3.
- dist[0][3] = min(INF, dist[0][1]+dist[1][3]=1+4=5) => becomes 5.
- dist[2][3]? current 1, new = dist[2][1]+dist[1][3] = INF+4 -> no.
- dist[3][2]? current -7, new = dist[3][1]+dist[1][2] = INF+2 -> no.
- dist[3][3]? current 0, new = dist[3][1]+dist[1][3]= INF+4 -> no.
- dist[2][?] etc.
- dist[0][?] done.
- dist[2][0] maybe? dist[2][1]+dist[1][0] INF+INF -> no.
- dist[?] etc.
k=2: via 2:
Now we have dist[0][2]=3, dist[2][3]=1, dist[3][2]=-7, dist[2][2]=0, dist[1][2]=2, etc.
Updates:
- dist[0][3] = min(5, dist[0][2]+dist[2][3] = 3+1=4) => becomes 4.
- dist[1][3] = min(4, dist[1][2]+dist[2][3] = 2+1=3) => becomes 3.
- dist[0][2] could be updated via 2? dist[0][2] = min(3, dist[0][2]+dist[2][2]=3+0=3) -> no.
- dist[0][0] = min(0, dist[0][2]+dist[2][0] = 3+INF) -> no.
- dist[3][3] = min(0, dist[3][2]+dist[2][3] = -7+1 = -6) => becomes -6. So dist[3][3] negative! So negative cycle detected.
Thus algorithm works.
Now final code.
Potential improvements: Use sys.setrecursionlimit, but not needed.
Now we need to ensure we read input correctly even if there are extra spaces/newlines. We used sys.stdin.read().split() which will handle.
Now final answer: Provide solution explanation and code.
But the problem might be from an online judge that expects specific output style. Ensure newline at end? Our join will produce final newline if we write to stdout? Usually print adds newline, but we are using sys.stdout.write with join, which does not add trailing newline. Some judges are fine, but many expect newline at end. To be safe, we could add a newline after the last line? Actually join with "\n" will produce lines separated by newline, and no trailing newline. But many judges accept that. Alternatively, we can print each line. But using print might be simpler. However, we used sys.stdout.write to avoid extra newline? Actually print adds newline by default, but it's fine. Let's use print for each line? But we need to output many lines; we can build string and print, but print adds newline. But we can also use print("\n".join(lines)). This will print with newline at end? Actually print adds a newline after the entire output, so there will be an extra newline at the end. That is typically acceptable. For safety, we can use sys.stdout.write("\n".join(lines)) which does not add extra newline. But many judges ignore trailing whitespace. I'll use print("\n".join(lines)). This will output with newline at the end. That's fine.
But if we print "NEGATIVE CYCLE", we should print just that line. Use print("NEGATIVE CYCLE").
Thus code:
import sys
def main():
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
V = int(next(it))
E = int(next(it))
INF = 10**18
dist = [[INF]*V for _ in range(V)]
for i in range(V):
dist[i][i] = 0
for _ in range(E):
s = int(next(it)); t = int(next(it)); d = int(next(it))
dist[s][t] = d
for k in range(V):
for i in range(V):
if dist[i][k] == INF:
continue
for j in range(V):
if dist[k][j] == INF:
continue
nd = dist[i][k] + dist[k][j]
if nd < dist[i][j]:
dist[i][j] = nd
for i in range(V):
if dist[i][i] < 0:
print("NEGATIVE CYCLE")
return
out_lines = []
for i in range(V):
line = []
for j in range(V):
if dist[i][j] == INF:
line.append("INF")
else:
line.append(str(dist[i][j]))
out_lines.append(" ".join(line))
print("\n".join(out_lines))
if name == "main":
main()
That should be fine.
Now think about time: 1e6 iterations, each with a few operations; in Python, 1e6 is trivial.
Now, there is an alternative: Using 'for k in range(V): dk = dist[k]; for i in range(V): dik = dist[i][k]; if dik == INF: continue; di = dist[i]; for j in range(V): if dk[j] == INF: continue; new = dik + dk[j]; if new < di[j]: di[j] = new' may be slightly faster by reducing attribute lookups. But not necessary.
But we can optimize slightly:
for k in range(V):
dk = dist[k]
for i in range(V):
dik = dist[i][k]
if dik == INF: continue
di = dist[i]
for j in range(V):
if dk[j] == INF: continue
nd = dik + dk[j]
if nd < di[j]:
di[j] = nd
This is common. Might be good for V=100. I'll adopt that for efficiency.
Now final code.
But wait: The detection for negative cycle: after loops we check dist[i][i] < 0. However, during the loops, if we ever set dist[i][i] negative, it's fine. But we check after.
Now one more nuance: In the Floyd algorithm, if there is a negative cycle, it's possible that some distances become less than actual due to using cycles more than once, but we don't output them anyway.
Now about reading input: We used .strip().split() which will remove whitespace. But if there is trailing newline, it's fine. However, if input is large (9900 lines), reading all is fine.
Now we should confirm that we handle the case where there are extra spaces at the end or blank lines.
Now final answer: Write explanation and code.
But the problem says: "Constraints: 1 ≤ |V| ≤ 100, 0 ≤ |E| ≤ 9900". So V >= 1. So no empty graph.
Now answer.
Now I'll produce final response. We can solve this problem by computing all-pairs shortest paths (APSP) using the Floyd–Warshall algorithm. The graph may contain negative edge weights. If after the algorithm any vertex has a negative distance to itself (dist[i][i] < 0), then a negative cycle exists. In that case we output NEGATIVE CYCLE. Otherwise we output the distance matrix, using INF for unreachable pairs.
The Floyd–Warshall algorithm runs in O(|V|³) which is fine for |V| ≤ 100.
Steps
- Read
V and E.
- Initialize a
V×V matrix dist with INF (a very large number, e.g., 10**18). Set dist[i][i] = 0 for each vertex i.
- For each edge
(s, t, d), set dist[s][t] = d (there are no parallel edges).
- Run Floyd–Warshall:
for k in range(V):
for i in range(V):
if dist[i][k] == INF: continue
for j in range(V):
if dist[k][j] == INF: continue
nd = dist[i][k] + dist[k][j]
if nd < dist[i][j]:
dist[i][j] = nd
- Check for negative cycles: if any
dist[i][i] < 0, print NEGATIVE CYCLE and exit.
- Otherwise, for each
i produce a line with the distances to all j. Replace INF with the string "INF". Print the lines.
Complexity
- Time:
O(V³) = 1 000 000 operations for V = 100, easily within limits.
- Space:
O(V²) = 10 000 integers.
import sys
def main() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
V = int(next(it))
E = int(next(it))
INF = 10**18
dist = [[INF] * V for _ in range(V)]
for i in range(V):
dist[i][i] = 0
for _ in range(E):
s = int(next(it))
t = int(next(it))
d = int(next(it))
dist[s][t] = d # no parallel edges
# Floyd-Warshall
for k in range(V):
dk = dist[k]
for i in range(V):
dik = dist[i][k]
if dik == INF:
continue
di = dist[i]
for j in range(V):
if dk[j] == INF:
continue
nd = dik + dk[j]
if nd < di[j]:
di[j] = nd
# Negative cycle detection
for i in range(V):
if dist[i][i] < 0:
print("NEGATIVE CYCLE")
return
# Output the distance matrix
out_lines = []
for i in range(V):
line = []
for j in range(V):
if dist[i][j] == INF:
line.append("INF")
else:
line.append(str(dist[i][j]))
out_lines.append(" ".join(line))
print("\n".join(out_lines))
if __name__ == "__main__":
main()