Graph
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65768/65768 K (Java/Others)
Total Submission(s): 950 Accepted Submission(s): 505
Problem Description
Everyone knows how to calculate the shortest path in a directed graph. In fact, the opposite problem is also easy. Given the length of shortest path between each pair of vertexes, can you find the original graph?
Input
The first line is the test case number T (T ≤ 100).
First line of each case is an integer N (1 ≤ N ≤ 100), the number of vertexes.
Following N lines each contains N integers. All these integers are less than 1000000.
The jth integer of ith line is the shortest path from vertex i to j.
The ith element of ith line is always 0. Other elements are all positive.
Output
For each case, you should output “Case k: ” first, where k indicates the case number and counts from one. Then one integer, the minimum possible edge number in original graph. Output “impossible” if such graph doesn't exist.
Sample Input
3
3
0 1 1
1 0 1
1 1 0
3
0 1 3
4 0 2
7 3 0
3
0 1 4
1 0 2
4 2 0
Sample Output
Case 1: 6
Case 2: 4
Case 3: impossible
Source
The 36th ACM/ICPC Asia Regional Chengdu Site —— Online Contest
解题报告:这是去年亚洲区网络预选赛成都的题目,当时是队友做出来的,前几天老师把这次比赛拿出来作为省赛选拔比赛,选拔赛的时候我看的这道题,看见这个题后,感觉在哪见过,题意是:给我们两点间的最短路径(双向),让我们求原来图中的最少有多少条边!能取消边的条件有当一个点到达另一个点的最短路径等于借助于第三个点的最短路径;例如:1-->2的最短路径为4 ,2-->3的最短路径为3而1-->3的最短路径为7所以1-->3的这条边就可以去掉;如果题目给的1-->3的最短路径大于7,这就不可能;因为1-->3借助于2的最短路径是7;
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAX = 110;
int map[MAX][MAX], visit[MAX][MAX];
int N, T, ans;
int Floyd()
{
int i, j, k;
for (k = 0; k < N; ++k)
{
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
if (i != j && j != k && i != k)
{
if (!visit[i][j] && (map[i][j] == map[i][k] + map[k][j]))
{
ans --;//这样的边可以不存在
visit[i][j] = 1;
}
else if (map[i][j] > map[i][k] + map[k][j])
{
return 0;//这种情况是不可能的
}
}
}
}
}
return 1;
}
int main()
{
int i, j, count = 1, flag;
scanf("%d", &T);
while (T --)
{
memset(map, 0, sizeof(map));
memset(visit, 0, sizeof(visit));
scanf("%d", &N);
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
scanf("%d", &map[i][j]);
}
}
ans = N * (N - 1);//假设所有的边都存在
flag = Floyd();
printf("Case %d: ", count);
if (flag)//这样的图存在
{
printf("%d\n", ans);
}
else//这样的图不存在
{
printf("impossible\n");
}
count ++;
}
return 0;
}