bzoj1050: [HAOI2006]旅行comf MST

44 篇文章 0 订阅
6 篇文章 0 订阅

并查集的思想。

枚举最短边。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;
int gcd(int x,int y)
{
    if (y>x) return gcd(y,x);
    if (!y) return x;
    return gcd(y,x%y);
}
struct node
{
    int v,u,val;
}edge[50000];
int ans1,tmp,ans2;
int n,e;
int father[50000];
bool cmp(node aa,node bb)
{
    return aa.val<bb.val;
}
int getfather(int x)
{
    if(father[x]==x) return x;
    father[x]=getfather(father[x]);
    return father[x];
}
int main()
{
    int st,ed;
    scanf("%d%d",&n,&e);
    for(int i=1;i<=e;i++)
    {
        scanf("%d%d%d",&edge[i].v,&edge[i].u,&edge[i].val);
    }
    scanf("%d%d",&st,&ed);
    sort(edge+1,edge+1+e,cmp);

    for(int i=1;i<=e;i++)
    {
        int j;
        for(j=1;j<=n;j++)
        father[j]=j;
        for(j=i;j<=e;j++)
        {
            int r1=getfather(edge[j].v);
            int r2=getfather(edge[j].u);
            if(r1!=r2)
            {
                father[r1]=r2;
                if (getfather(st)==getfather(ed)) break;//核心,st和ed相同就停止。
            }
        }
        int r1=getfather(st);
        int r2=getfather(ed);

        if ((i==1)&&(r1!=r2))
        {
            printf("IMPOSSIBLE\n");
            return 0;
        }
        if (r1!=r2) break;
        if (ans1*edge[i].val>=ans2*edge[j].val)
            ans1=edge[j].val,ans2=edge[i].val;//如果用double会有精度误差
    }
    int x=gcd(ans1,ans2);
    if (x==ans2) printf("%d\n",ans1/ans2); else printf("%d/%d\n",ans1/x,ans2/x);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值