HDOJ/HDU 4034 2011成都网络赛D题

Graph

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65768/65768 K (Java/Others)
Total Submission(s): 355    Accepted Submission(s): 195


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
 


判断这个图是否合理很简单,就是利用floyd算法在做一次松弛操作。如果发现还有边可以进行松弛的话就输出impossible

然后接下来统计最小边就是去找dis[i][j]能不能表示为dis[i][k]+dis[k][j]的形式

所以说这个题实际上是考察了floyd算法的理解

 

我的代码:

#include<stdio.h>
#include<string.h>

int dis[105][105];

int main()
{
	int n,i,j,t,T,k;
	scanf("%d",&T);
	for(t=1;t<=T;t++)
	{
		scanf("%d",&n);
		for(i=1;i<=n;i++)
			for(j=1;j<=n;j++)
				scanf("%d",&dis[i][j]);
		bool flag=true;
		int ans=0;
		for(k=1;k<=n;k++)
			for(i=1;i<=n;i++)
				for(j=1;j<=n;j++)
				{
					if(i!=j&&j!=k&&i!=k)
					{
						if(dis[i][j]>dis[i][k]+dis[k][j])
						{
							if(flag)
								printf("Case %d: impossible\n",t);
							flag=false;
						}
					}
				}
		if(flag)
		{
			for(i=1;i<=n;i++)
				for(j=1;j<=n;j++)
				{
					bool loop=true;
					if(i!=j)
					{
						for(k=1;k<=n;k++)
						{
							if(i!=k&&j!=k)
							{
								if(dis[i][j]==dis[i][k]+dis[k][j])
									loop=false;
							}
						}
						if(loop)
							ans++;
					}
				}
			printf("Case %d: %d\n",t,ans);
		}
	}
	return 0;
}


 

你可能感兴趣的:(HDOJ/HDU 4034 2011成都网络赛D题)