Time Limit: 10000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3391 Accepted Submission(s): 1162
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.
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.
#include <cstdio> #include <queue> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn = 3010,inf = 0x7ffffff; int n,m,head[110],to[maxn * 2],nextt[maxn * 2],tot = 1,pre[110][110],num[110][110]; int d[110],vis[110],sum[110]; bool flag = true; struct node { int x,y; } e[maxn]; void add(int x,int y) { to[tot] = y; nextt[tot] = head[x]; head[x] = tot++; } void bfs(int s) { queue <int> q; q.push(s); for (int i = 1; i <= n; i++) d[i] = inf; memset(vis,0,sizeof(vis)); vis[s] = 1; d[s] = 0; while (!q.empty()) { int u = q.front(); q.pop(); for (int i = head[u]; i; i = nextt[i]) { int v = to[i]; if (!vis[v]) { pre[s][v] = u; d[v] = d[u] + 1; vis[v] = 1; q.push(v); } } } for (int i = 1; i <= n; i++) { if(d[i] == inf) { flag = false; return; } else sum[s] += d[i]; } } int bfs2(int s) { queue <int> q; q.push(s); for (int i = 1; i <= n; i++) d[i] = inf; memset(vis,0,sizeof(vis)); vis[s] = 1; d[s] = 0; while (!q.empty()) { int u = q.front(); q.pop(); for (int i = head[u]; i; i = nextt[i]) { int v = to[i]; if (!vis[v] && num[u][v]) { d[v] = d[u] + 1; vis[v] = 1; q.push(v); } } } int res = 0; for (int i = 1; i <= n; i++) { if (d[i] == inf) return -1; else res += d[i]; } return res; } int main() { while (scanf("%d%d",&n,&m) != EOF) { memset(head,0,sizeof(head)); tot = 1; flag = true; memset(pre,0,sizeof(pre)); memset(sum,0,sizeof(sum)); memset(num,0,sizeof(num)); for (int i = 1; i <= m; i++) { int x,y; scanf("%d%d",&x,&y); num[x][y]++; num[y][x]++; e[i].x = x; e[i].y = y; add(x,y); add(y,x); } for (int i = 1; i <= n; i++) { bfs(i); if(!flag) break; } if (!flag) { for (int i = 1; i <= m; i++) puts("INF"); } else { for (int i = 1; i <= m; i++) { bool flag2 = true; int ans = 0,x = e[i].x,y = e[i].y; for (int j = 1; j <= n; j++) { if (pre[j][y] != x && pre[j][x] != y) { ans += sum[j]; continue; } else { num[x][y]--; num[y][x]--; int t = bfs2(j); num[x][y]++; num[y][x]++; if (t == -1) { flag2 = false; puts("INF"); break; } else ans += t; } } if (flag2) printf("%d\n",ans); } } } return 0; }