hdu 4034 Graph (floyd的深入理解)

时间:2022-05-05
本文章向大家介绍hdu 4034 Graph (floyd的深入理解),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Graph

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

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

题意:  给你一些顶点的最短距离,要你求出原图最少含有多少边。

我们知道,最短路所构成的图已经是最少的边。所以只需要用n个点构成的有向边的和n*(n-1)减去那些合成的边。就是最少的边。

采用floy算法,松弛度来勾结一个最短图...

代码:

 1 #include<cstdio>
 2 #include<cstring>
 3 #define maxn 110
 4 int ds[maxn][maxn];
 5 bool vis[maxn][maxn];
 6 int mat[maxn][maxn];
 7 void floyd(int n)
 8 {
 9     for(int k=0;k<n;k++)
10     {
11         for(int i=0;i<n;i++)
12         {
13             if(i==k) continue;
14             for(int j=0;j<n;j++)
15             {
16                 if(k==j)continue;
17                 if(ds[i][j]>=ds[i][k]+ds[k][j])
18                 {
19                     vis[i][j]=1;
20                     ds[i][j]=ds[i][k]+ds[k][j];
21                 }
22             }
23         }
24     }
25 }
26 int main()
27 {
28  int cas,n;
29    scanf("%d",&cas);
30    for(int tt=1;tt<=cas;tt++)
31    {
32          scanf("%d",&n);
33          for(int i=0;i<n;i++)
34           for(int j=0;j<n;j++)
35         {
36           scanf("%d",mat[i]+j);
37           ds[i][j]=mat[i][j];
38         }
39         memset(vis,0,sizeof(vis));
40         floyd(n);
41         int res=0;
42         bool tag=0;
43       for(int i=0;i<n;i++)
44       {
45           for(int j=0;j<n;j++)
46         {
47           if(vis[i][j]&&ds[i][j]==mat[i][j])
48               res++;
49           else if(ds[i][j]<mat[i][j])
50           {
51                 tag=1;
52               break;
53           }
54         }
55          if(tag)break;
56       }
57         printf("Case %d: ",tt);
58         if(tag)
59             printf("impossiblen");
60         else printf("%dn",n*(n-1)-res);
61 
62    }
63  return 0;
64 }