UVA - 1395 - Slim Span(Kruskal算法+枚举)


将边按权值排序后,枚举最小权值的边,

从第一个边开始,直到往后能够构成生成树,并且记录中间出现过的最大权值和最小权值,

最后不断取最小值即可

切记每次枚举前,都要初始化父亲节点


#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
typedef long long ll;
typedef unsigned long long llu;
const int MAXN = 100 + 10;
const int MAXT = 100000 + 10;
const int INF = 0x7f7f7f7f;
const double pi = acos(-1.0);
const double EPS = 1e-6;
using namespace std;

struct Line{
    int be, en, v;
    Line() : be(0), en(0), v(0) {}
    bool operator < (const Line &b) const{
        return v < b.v;
    }
}p[MAXT];

int fa[MAXN], n, m;

int find(int v){
    return fa[v] = fa[v] == v ? v : find(fa[v]);
}

int init(){
    for(int i = 0; i <= n; ++i)  fa[i] = i;
}

int main(){
    while(scanf("%d%d", &n, &m) == 2 && (n || m)){
        for(int i = 0; i < m; ++i)  scanf("%d%d%d", &p[i].be, &p[i].en, &p[i].v);
        sort(p, p + m);
        int ans = INF;
        for(int i = 0; i < m; ++i){
            int tmp = 0, cnt = n, ma = -1, mi = INF;
            init();
            for(int j = i; j < m; ++j){
                int t1 = find(p[j].be);
                int t2 = find(p[j].en);
                if(t1 != t2){
                    fa[t1] = t2;
                    ma = max(ma, p[j].v);
                    mi = min(mi, p[j].v);
                    if(--cnt == 1)  break;
                }
            }
            if(cnt == 1)  ans = min(ans, ma - mi);
            else  break;
        }
        printf("%d\n", ans == INF ? -1 : ans);
    }
    return 0;
}





你可能感兴趣的:(UVa)