首页 > 代码库 > Floyd最小环Hdu1599

Floyd最小环Hdu1599

http://acm.hdu.edu.cn/showproblem.php?pid=1599

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <iostream>
using namespace std;
const int INF=0xfffffff;
int Min(int a,int b)
{
    return a>b?b:a;
}
int Map[1111][1111];
int dp[1111][1111];
int main()
{
    int n,m;
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    while(scanf("%d%d",&n,&m)!=EOF){
        int ans=INF;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
            Map[i][j]=INF;
        for(int i=0;i<m;i++){
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            if(Map[a][b]>c){
                Map[a][b]=Map[b][a]=c;
            }
        }
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
            dp[i][j]=Map[i][j];
        for(int k=1;k<=n;k++){
            for(int i=1;i<=n;i++){
                for(int j=1;j<=n;j++)
                    ans=Min(ans,dp[i][j]+Map[k][i]+Map[k][j]);//i,j,k需要互异
            }
            for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++){
                if(dp[i][j]>dp[i][k]+dp[k][j])
                    dp[i][j]=dp[i][k]+dp[k][j];
            }
        }
        if(ans==INF)
            printf("It‘s impossible.\n");
        else
            printf("%d\n",ans);
    }
    return 0;
}