A Typo in Floyd
InterviewTime limit2sMemory limit512 MB
Count ordered pairs whose shortest-path values differ when Floyd's outer loop skips vertex N as an intermediate.
- Level
Medium6 of 10
- Topics
- Shortest path, Dynamic programming, Graph
- Solved
- No attempts yet
Problem
Jiguui, who felt weak at coding, read a post on an anonymous board that recommended coding without ever pressing the backspace key. At the bottom of the post, five lines of very small type said the method comes with no guarantee, but Jiguui decided it was worth one try and followed it.
The first problem Jiguui attacked was this: given the adjacency matrix of a graph on vertices, find the shortest distance for every pair of vertices. Jiguui went for the Floyd algorithm and made a typo on the first line of the triple loop.
for (int k = 1; k < N; k++)
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
D[i][j] = min(D[i][j], D[i][k] + D[k][j]);
The outer loop says k < N instead of k <= N, so vertex is never used as an intermediate vertex. Having sworn off the backspace key, Jiguui could not erase the typo and finished the code with it, and the submission was wrong.
After solving the problem, Jiguui wants to measure how broken that first attempt was. Given the adjacency matrix , count the ordered pairs where the value computed by the code with the typo differs from the value computed by the correct Floyd algorithm. Pairs with count as well.
Both versions update values with the recurrence above and nothing else. The adjacency matrix holds a value for every ordered pair, so there is no separate infinity.
Input
The first line contains the number of vertices ().
Each of the next lines contains one row of the adjacency matrix . The -th number on the -th line is .
for every , and for every and .
Output
Print the number of ordered pairs whose values differ between the two versions.