HDU 4034 Graph(Floyd变形——逆向判断)

时间:2023-01-10 17:25:56

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=4034

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
题意描述:
输入使用Floyd算法跑出来的最短路径的邻接矩阵
判断是否有这样的图存在,存在输出图中至少需要几条边,不存在输出impossible
解题思路:
首先分为存在和不存在两种情况
不存在意味该图中存在至少一条边的最短路径是错误的,例如图中存1--->2为3,2--->3为4,而图中存储的是2--->3为8,很明显可以通过2这个点将1--->3这条边松弛为7,那么这条最短路径是错误的,近而判断不存在这样的图;
再说存在这样的图的情况,如果存在这样的图,根据题中所说为单向道路,n个顶点最多有n*(n-1)条边,如果某一条边可以消去,那么必定可以找到与直接路径相等的间接路径,例如图中存1--->2为3,2--->3为4,而图中存储的是1--->3为7,很明显可以将1--->3这条边消去。
另外,每次判断,需要用book数组来记录那一条边已经消去过了,否则可能重复消去。
代码实现:
 #include<stdio.h>
#include<string.h>
int n,map[][],book[][];
int floyd();
int main()
{
int T,t=,i,j,flag;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(i=;i<=n;i++)
for(j=;j<=n;j++)
scanf("%d",&map[i][j]);
flag=floyd();
if(flag)
printf("Case %d: %d\n",++t,flag);
else
printf("Case %d: impossible\n",++t);
}
return ;
}
int floyd()
{
int i,j,k,ans;
memset(book,,sizeof(book));
ans=n*(n-);
for(k=;k<=n;k++)
for(i=;i<=n;i++)
for(j=;j<=n;j++)
if(i != j&&i != k&&j != k)
{
if(!book[i][j] && map[i][j] == map[i][k]+map[k][j])
{
ans--;
book[i][j]=;
}
else if(map[i][j] > map[i][k]+map[k][j])
return ;
}
return ans;
}