UVA 1395 Slim Span(MST)

http://vjudge.net/problem/UVA-1395

题目大意:让求最小生成树满足苗条度最小的条件(苗条度:最大边与最小边的差值)

思路:在书上。根据Kruskal的思想,当所有点连通了就停止枚举左边界,记录最小苗条度。紫书的代码好稠

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 105;

struct node
{
    int u,v,w;
    bool operator < (const node & p)const
    {
        return w < p.w;
    }
}e[N*N];
int n,m,counter;
int f[N];

int getf(int t)
{
    if(t != f[t])
        f[t] = getf(f[t]);
    return f[t];
}

void Init()
{
    for(int i = 1;i <= n;i++)
        f[i] = i;
    counter = 0;
}

int main()
{
    while(~scanf("%d%d",&n,&m) && (n || m))
    {

        for(int i = 1;i <= m;i++)
            scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);

        sort(e+1,e+1+m);

        int minn = INF;
        for(int L = 1;L <= m;L++)
        {
            Init();
            for(int R = L;R <= m;R++)
            {
                int x = getf(e[R].u);
                int y = getf(e[R].v);
                if(x != y)
                {
                    f[y] = x;
                    counter++;
                }

                if(counter == n-1)
                {
                    minn = min(minn,e[R].w-e[L].w);
                    break;
                }
            }
        }
        if(minn == INF)
            printf("-1\n");
        else
            printf("%d\n",minn);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值