Slim Span UVA - 1395

版权声明:欢迎转载!拒绝抄袭. https://blog.csdn.net/qq_36257146/article/details/88413916
#include <iostream>
#include <bits/stdc++.h>
#define inf 10000000
#define maxn 110
#define maxm 110*50
using namespace std;
struct Node
{
    int u,v,w;
    bool operator < (const Node & a) const
    {
        return w<a.w;
    }
};
int n,m,ans,flag;
int p[maxn];
Node nodes[maxm];

int Find(int x)
{
    return x==p[x]?x:p[x] = Find(p[x]);
}


void kruskal()
{
    flag = 0;
    ans = inf;
    flag = 0;
    sort(nodes,nodes+m);
    for(int l = 0; l<m; l++) //L
    {
        int cnt = 0;
        for(int i = 1; i<=n; i++) p[i] = i;
        for(int r = l; r<m; r++) //R
        {
            int x = Find(nodes[r].u);
            int y = Find(nodes[r].v);
            if(x!=y)
            {
                cnt++;
                p[x] = y;
            }
            if(cnt==n-1)
            {
                int a = nodes[l].w;
                int b = nodes[r].w;
                flag = 1;
                ans = min(ans,b-a);
                break;
            }
        }
    }

}

int main()
{
    while(cin>>n>>m&&n+m)
    {
        for(int i = 0; i<m; i++) cin>>nodes[i].u>>nodes[i].v>>nodes[i].w;
        kruskal();
        if(flag)
            cout<<ans<<endl;
        else
            cout<<-1<<endl;
    }
    return 0;
}
/**
4 5
1 2 3
1 3 5
1 4 6
2 4 6
3 4 7
4 6
1 2 10
1 3 100
1 4 90
2 3 20
2 4 80
3 4 40
2 1
1 2 1
3 0
3 1
1 2 1
3 3
1 2 2
2 3 5
1 3 6
5 10
1 2 110
1 3 120
1 4 130
1 5 120
2 3 110
2 4 120
2 5 130
3 4 120
3 5 110
4 5 120
5 10
1 2 9384
1 3 887
1 4 2778
1 5 6916
2 3 7794
2 4 8336
2 5 5387
3 4 493
3 5 6650
4 5 1422
5 8
1 2 1
2 3 100
3 4 100
4 5 100
1 5 50
2 5 50
3 5 50
4 1 150
0 0
**/

猜你喜欢

转载自blog.csdn.net/qq_36257146/article/details/88413916