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
分析:
对于一个有向图,最多可能有n*(n-1)条边.我们只要枚举这n*(n-1)条边,然后看看这条边是否必须存在即可.
假设我们现在考虑边i->j,看看它是否必须存在.首先我们必须假定边i->j的长度.由于我们知道i到j的最短距离,所以我们只能假定i->j边长==其最短距离.(想想为什么,更短的话,出现矛盾.更长的话,直接没有存在的必要)
如果存在d[i][k]+d[k][j]==d[i][j],那么说明i->j的边长可以由别的边生成,所以i->j的边没有存在的必要,必须被删除。
(其实我在想这种发现一条非必要边就删一条的策略是否正确?有没有可能因为我们删除边的顺序不同,最终导致多种不同的解?不会有多解的,因为最基本的那些边一定是不可替换的,即最终肯定只有一个解)
如果存在d[i][k]+d[k][j]<d[i][j], 那么有矛盾,直接输出impossible.
上面两种情况都不存在,说明没有任何其他边的最短距离能生成i到j的最短距离,那么i只能通过一条直边到达j来产生最短距离.
代码:
#include<cstdio>
using namespace std;
const int maxn = 100+10;
int d[maxn][maxn];
int main()
{
int n,T; scanf("%d",&T);
for(int kase=1;kase<=T;kase++)
{
printf("Case %d: ",kase);
scanf("%d",&n);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%d",&d[i][j]);
bool flag = true;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)//检测每条边
for(int k=1;k<=n;k++)if(i!=j&&j!=k&&i!=k)
if(d[i][j]> d[i][k]+d[k][j]) flag=false;
if(!flag) { printf("impossible\n"); continue; }
int ans=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)if(i!=j)//检测每条边
{
bool flag=true;
for(int k=1;k<=n;k++)if(j!=k&&i!=k)
if(d[i][j] == d[i][k]+d[k][j])
flag=false;
if(flag) ++ans;
}
printf("%d\n",ans);
}
return 0;
}