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.
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.
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 题目大意:给一张已经用floyd求好最短路的图,问最少可由多少条边得到。
题目解析:对于边e[i][j],如果存在e[i][j]=e[i][k]+e[k][j],则边i->j没有必要存在;如果存在e[i][j]>e[i][k]+e[k][j],则图有误,impossible。将最外层循环放到最内层即可。 代码如下:
# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;
int mp[][],n;
int ok()
{
int i,j,k;
int cnt=,vnt=;
for(i=;i<=n;++i){ ///枚举每
for(j=;j<=n;++j){ ///一条边
if(mp[i][j]!=)
++vnt;
if(i==j)
continue;
for(k=;k<=n;++k){ ///枚举中间节点
if(i==k||j==k)
continue;
if(mp[i][j]>mp[i][k]+mp[k][j]&&mp[i][k]&&mp[k][j]){
return -;
}else if(mp[i][j]==mp[i][k]+mp[k][j]&&mp[i][k]&&mp[k][j]){
++cnt;
break;
}
}
}
}
return vnt-cnt;
}
int main()
{
int T,i,j,cas=;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(i=;i<=n;++i)
for(j=;j<=n;++j)
scanf("%d",&mp[i][j]);
printf("Case %d: ",++cas);
int ans=ok();
if(ans!=-)
printf("%d\n",ans);
else
printf("impossible\n");
}
return ;
}