HDU 4034 Graph The 36th ACM/ICPC Asia Regional Chengdu Site —— Online Contest

 

Graph

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


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

Recommend
lcy
 
統計一下一條最短路由另外兩條最短路構成的數量。
代碼:
#include<cstdio>
#include<cstring>

int t,tt,n,a[105][105];
int solve()
{
	int i,j,k,m=0,f[105][105]={0};
	for(k=0;k<n;k++)
		for(i=0;i<n;i++)
			for(j=0;j<n;j++)
				if(i!=j&&i!=k&&k!=j)
				{
					if(a[i][j]==a[i][k]+a[k][j]&&!f[i][j])
					{
						f[i][j]=1;
						m++;
					}
					if(a[i][j]>a[i][k]+a[k][j])
						return -1;
				}
	return m;
}
int main()
{
	scanf("%d",&t);
	while(t--)
	{
		int i,j,k;
		scanf("%d",&n);
		for(i=0;i<n;i++)
			for(j=0;j<n;j++)
				scanf("%d",&a[i][j]);
		printf("Case %d: ",++tt);
		if((k=solve())==-1)
			puts("impossible");
		else
			printf("%d\n",n*(n-1)-k);
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章