POJ3522-类最小生成树

题目:题目链接

题意:题目的意思就是给你n个点和m条边,然后构造一个生成树,使得在这颗生成树里面权值最大的和权值最小的差值最小;


分析:并查集,直接对边进行一次排序,按照权值由小到大,一次枚举一条边,求一次生成树,寻求过程中,是每次

一个边加入图中,判断图是否连通判断过程用并查集,一直更新最小值就可以了(练习写了一下最小生成树,略慢):


#include <iostream>
#include <cstdio>
#include <string>
#include <string.h>
#include <map>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <queue>
#include <set>
#include <stack>
#include <functional>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cassert>
#include <bitset>
#include <stack>
#include <ctime>
#include <list>
#define INF 0x7fffffff
#define max3(a,b,c) (max(a,b)>c?max(a,b):c)
#define min3(a,b,c) (min(a,b)<c?min(a,b):c)
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
#define maxn 105
const int maxm = maxn*maxn/2;

struct Edge
{
    int a, b, w;
} edge[maxm];

int n, m;
int father[maxn];

bool operator < (const Edge &a, const Edge &b)
{
    return a.w < b.w;
}

void input()
{
    for(int i = 0; i < m; ++i)
    {
        int a, b, w;
        scanf("%d%d%d", &a, &b, &w);
        a--;
        b--;
        edge[i].a = a;
        edge[i].b = b;
        edge[i].w = w;
    }
}

int getanc(int a)
{
    if(a == father[a])
        return a;
    return father[a] = getanc(father[a]);
}

int cal(int l)
{
    for(int i = 0; i < n; ++i)
        father[i] = i;
    int i = l;
    int block_num = n;
    while(i < m && block_num > 1)
    {
        int a = getanc(edge[i].a);
        int b = getanc(edge[i].b);
        if(a != b)
        {
            block_num--;
            father[a] = b;
        }
        i++;
    }
    if(block_num > 1)
        return -1;
    return edge[i-1].w - edge[l].w;
}

void work()
{
    int ans = cal(0);
    if(ans == -1)
    {
        printf("-1\n");
        return;
    }
    for(int i = 1; i < m; ++i)
    {
        if(edge[i].w == edge[i-1].w)
            continue;
        int temp = cal(i);
        if(temp == -1)
            break;
        ans = min(ans, temp);
    }
    printf("%d\n", ans);
}

int main()
{
    while(scanf("%d%d", &n, &m), n|m)
    {
        mem(edge, 0);
        input();
        sort(edge, edge+m);
        work();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值