Here is the problem link: http://codeforces.com/contest/295/problem/B
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. Greg loves playing with the graph and now he has invented a new game:
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. The shortest path can go through any remaining vertex. Help Greg, print the value of the required sum before each step.
Input:
The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph.
Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j.
The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes.
Output:
Print n integers — the i-th number equals the required sum before the i-th step.
So, basically my approach was to run Floyd-Warshall algorithm before deleting any vertex, and for deletion, I would simply set the value of the vertex which to be deleted as INT_MAX
in the adjacency matrix in both rows and columns.
Basically, this loop is in main
for (int h = 0; h < n; h++)
{
func();
int val = arr[h]; // arr contains the vertices to be deleted
for ( i = 1; i <= n; i++ )
dist[val][i] = INT_MAX;
for ( i = 1; i <= n; i++ )
dist[i][val] = INT_MAX;
}
This is my implementation of Flloyd Warshall algorithm:
void func ()
{
//int i,j,k;
ans = 0;
for ( i = 1; i <= n; i++ )
{
for ( j = 1; j <= n; j++ )
{
if (i == j)
val[i][j][0] = 0;
else if (dist[i][j] != 0)
val[i][j][0] = dist[i][j];
else
val[i][j][0] = INT_MAX;
}
}
for (k = 1; k <= n; k++)
for ( i = 1; i <= n; i++ )
for ( j = 1; j <= n; j++ )
val[i][j][k] = min(val[i][j][k-1],val[i][k][k-1]+val[k][j][k-1]);
//int ans = 0;
for ( i = 1; i <= n; i++ )
for ( j = 1; j <= n; j++ )
ans = ans + val[i][j][n];
cout<<ans<<"\t";
}
Here, val
is the 3-D matrix that I have made global, and arr
contains the vertices that are to be deleted. However, when I run this logic, it gives right answer only initially, that is when no vertex has been deleted. But after that, it gives a wrong value. I don't understand why? Is my logic incorrect?