苗条生成树

题目参见

枚举生成最小生成树,维护一下答案。

注意int的函数会默认返回0

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>

using namespace std;
const int maxn =100000;
const int INF = 0x7ffffff;
struct Edge
{
    int from,to,dist;
    Edge(int from,int to,int dist):from(from),to(to),dist(dist){}    
    bool operator < (const Edge& b) const{
        return dist < b.dist;
    }
};
vector<Edge> edges;
int p[maxn];
int n,m;
int find(int x)
{
    return p[x] == x?x:p[x]=find(p[x]);
}
int ans;
int sovle(int i)
{
            int MIN = INF,MAX = 0;int cnt = 0;
            for(int j = 1;j <= m;j++) p[j] = j;
            for(int j = i;j < m;j++)
            {
                Edge& e = edges[j];int x = find(e.from),y = find(e.to);
                if(x != y) {MAX = max(MAX,e.dist),MIN = min(MIN,e.dist);p[x] = y;cnt++;}
            }
            if(cnt == n-1){return MAX-MIN;}
    return INF;    
}


int main()
{
    while(scanf("%d%d",&n,&m) == 2&&n)
    {
        edges.clear();
        for(int i = 0;i < m;i++)
        {
            int from,to,dist;
            scanf("%d%d%d",&from,&to,&dist);
            edges.push_back(Edge(from,to,dist));     
        }
        sort(edges.begin(),edges.end());
        ans = INF;
        for(int i = 0;i < m;i++)
        {
          ans = min(ans,sovle(i));
        }
        if(ans == INF) cout<<"-1"<<endl;
        else cout<<ans<<endl; 
    }
    return 0;
}

 

posted @ 2017-02-15 20:29  rsqppp  阅读(144)  评论(0)    收藏  举报