您的位置:首页 > 其它

HDU 4034 Graph

2015-10-26 17:07 495 查看
[align=left]Problem Description[/align]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?
[align=left]Input[/align]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.

[align=left]Output[/align]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.

[align=left]Sample Input[/align][align=left]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
[/align][align=left]Sample Output[/align][align=left]Case 1: 6
Case 2: 4
Case 3: impossible
[/align][align=left]Source[/align]The 36th ACM/ICPC Asia Regional Chengdu Site —— Online Contest
[align=left]Recommend[/align]lcy题目大意:给定i~j的最短路径,让你求原始图中可能的最少边数。思路:开始的时候不知道怎么去做尽管老师提示了用floyd去写,可是想到了除了枚举n外并没有想到好办法(但是枚举n不但可能会超时,而且,貌似这种方法是行不通的)!后来看了老师发的题解,又结合网上的资料,才算彻底把问题弄好,正解是统计一下一条最短路由另外两条最短路构成的数量。然后用所有可能的边减去该数量即可!code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=105;
int t,tt,n;
int vis

,mp

;

int solve()
{
int i,j,k,m=0;
memset(vis,0,sizeof(vis));
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)
{
//如果相等则说明ij的连线多余的
if(mp[i][j]==mp[i][k]+mp[k][j]&&!vis[i][j])
{
vis[i][j]=1;
m++;
}
//三角形第三边大于两边之和,形不成三角形,构不成图!
if(mp[i][j]>mp[i][k]+mp[k][j])
return -1;
}
return m;
}

int main()
{
scanf("%d",&t);
for (int ca=1;ca<=t;ca++)
{
printf("Case %d: ",ca);
int i,j;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&mp[i][j]);
int ans=solve();
if (ans==-1)
puts("impossible");
else
printf("%d\n",n*(n-1)-ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: