UVA 1395 Slim Span 最小生成树

UVA 1395     Slim Span

 先上代码,日后写题解

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define inf 1e8
#define maxn 10005
using namespace std;

struct edge{
int to,from,cost;
}s[maxn];

bool cmp(const edge a,const edge b){
    return a.cost < b.cost;
}

int par[maxn],n,m;

void init(){
     for(int i = 1; i <= m; i++)
        par[i] = i;
}
int finds(int x){
    if (par[x] == x) return x;
    else return par[x] =finds(par[x]);
}
void unite(int x,int y){
    x=finds(x),y=finds(y);
    if(x==y) return ;
    par[x]=y;
}
bool same(int x,int y){
    if(finds(x) == finds(y)) return true;
    return false;
}


int kruskal(int x){
    int cnt = 0, l = inf, r = -inf;
    init();
    for(int i = x; i < n; i++){
        edge e = s[i];
        if(!same(e.to,e.from)) {
           unite(e.to,e.from);
           cnt++;
           r = max(r,e.cost);
           l = min(l,e.cost);
           if(cnt == m-1) return r-l;
        }
    }
    return -1;
}
void slove(){
    sort(s,s+n,cmp);
    int res = inf,flag=-1;
    for(int i = 0; i < n; i++){
        int op =kruskal(i);
        if(op!=-1 && op < res){
            res = op;
            flag = 1;
        }
    }
    if(flag == -1) printf("-1\n");
        else printf("%d\n", res);
}
int main(){
   //freopen("data.in.txt","r",stdin);
    while(scanf("%d%d", &m, &n) && (n||m)){
        for(int i = 0; i < n; i++)
            scanf("%d%d%d", &s[i].from, &s[i].to, &s[i].cost);
          slove();

    }

    return 0;
}
View Code

 

posted on 2016-07-17 16:26  disppr  阅读(181)  评论(0编辑  收藏  举报