Graph
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65768/65768 K (Java/Others)Total Submission(s): 1371 Accepted Submission(s): 689
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.
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,当dp[i][j]==dp[i][k]+dp[k][j]时,说明(i,j)这条边是可以删的;当dp[i][j]>dp[i][k]+dp[k][j],说明还存在比最短路径更短的路径,这是不可能的。AC代码:#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <queue> #include <vector> #include <cmath> #include <stack> #include <cstdlib> using namespace std; int dp[105][105]; bool vis[105][105]; int n; void floyd() { int ans=n*(n-1); memset(vis,false,sizeof(vis)); int flag=1; for(int k=0;k<n;k++) for(int i=0;i<n;i++) { if(k==i) continue; for(int j=0;j<n;j++) { if(j==k) continue; if(dp[i][j]==dp[i][k]+dp[k][j]&&!vis[i][j]) { ans--; vis[i][j]=true; } else if(dp[i][j]>dp[i][k]+dp[k][j]&&!vis[i][j]) { flag=0; break; } } } if(flag) printf("%d\n",ans); else printf("impossible\n"); } int main() { int t,c=0; scanf("%d",&t); while(t--) { scanf("%d",&n); for(int i=0;i<n;i++) for(int j=0;j<n;j++) scanf("%d",&dp[i][j]); printf("Case %d: ",++c); floyd(); } return 0; }

本文探讨了根据已知的各个顶点间最短路径长度来重建原始有向图的问题,并提供了一种通过Floyd算法来计算最少边数的方法。若发现存在比已知最短路径更短的路径,则判定该图不存在。
1733

被折叠的 条评论
为什么被折叠?



