Count ordered pairs whose shortest-path values differ when Floyd's outer loop skips vertex N as an intermediate.
Medium6Shortest pathDynamic programmingGraphInterviewNo attempts yetTime limit2sMemory limit512 MBJiguui, 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 D of a graph on N 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 N 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 D, count the ordered pairs (i,j) where the value computed by the code with the typo differs from the value computed by the correct Floyd algorithm. Pairs with i=j 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.
The first line contains the number of vertices N (1≤N≤100).
Each of the next N lines contains one row of the adjacency matrix D. The j-th number on the i-th line is D(i,j).
D(i,i)=0 for every i, and 0≤D(i,j)≤10000 for every i and j.
Print the number of ordered pairs (i,j) whose values differ between the two versions.