Travel
One day, Tom traveled to a country named BGM. BGM is a small country, but there are N (N <= 100) towns in it. Each town products one kind of food, the food will be transported to all the towns. In addition, the trucks will always take the shortest way. There are M (M <= 3000) two-way roads connecting the towns, and the length of the road is 1.
Let SUM be the total distance of the shortest paths between all pairs of the towns. Please write a program to calculate the new SUM after one of the M roads is destroyed.
Input
The input contains several test cases.
The first line contains two positive integers N, M. The following M lines each contains two integers u, v, meaning there is a two-way road between town u and v. The roads are numbered from 1 to M according to the order of the input.
The input will be terminated by EOF.
Output
Output M lines, the i-th line is the new SUM after the i-th road is destroyed. If the towns are not connected after the i-th road is destroyed, please output “INF” in the i-th line.
Sample Input
5 4 5 1 1 3 3 2 5 4 2 2 1 2 1 2
Sample Output
INF INF INF INF 2 2
#include"stdio.h"
#include"string.h"
#include"queue"
#include"iostream"
#define inf 10000
#define M 111
using namespace std;
int n,dis[M],use[M];
struct st
{
int u,v,w,next;
}edge[M*M];
int head[M],t;
void init()
{
t=0;
memset(head,-1,sizeof(head));
}
void add(int u,int v,int w)
{
edge[t].u=u;
edge[t].v=v;
edge[t].w=w;
edge[t].next=head[u];
head[u]=t++;
}
void spfa(int s)
{
int i;
queue<int>q;
memset(use,0,sizeof(use));
for(i=1;i<=n;i++)
dis[i]=inf;
dis[s]=0;
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
use[u]=0;
for(i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
if(dis[v]>dis[u]+edge[i].w)
{
dis[v]=dis[u]+edge[i].w;
if(!use[v])
{
use[v]=1;
q.push(v);
}
}
}
}
}
int x[3009],y[3009],sum[M];
int main()
{
int m,i,j,sum_v,sum_u;
while(scanf("%d%d",&n,&m)!=-1)
{
init();
for(i=1;i<=m;i++)
{
scanf("%d%d",&x[i],&y[i]);
add(x[i],y[i],1);
add(y[i],x[i],1);
}
int ans=0;
for(i=1;i<=n;i++)
{
sum[i]=0;
spfa(i);
for(j=1;j<=n;j++)
sum[i]+=dis[j];
ans+=sum[i];
}
for(i=1;i<=m;i++)
{
edge[i*2-1].w=edge[i*2-2].w=inf;
spfa(x[i]);
sum_u=0;
for(j=1;j<=n;j++)
sum_u+=dis[j];
if(sum_u>=inf)
{
edge[i*2-1].w=edge[i*2-2].w=1;
printf("INF\n");
continue;
}
sum_v=0;
spfa(y[i]);
for(j=1;j<=n;j++)
sum_v+=dis[j];
printf("%d\n",ans+sum_u+sum_v-sum[x[i]]-sum[y[i]]);
edge[i*2-1].w=edge[i*2-2].w=1;
}
}
}