【HAOI2006】旅行(并查集暴力)

传送门

Solution:

并查集暴力搞。

挺像kruskal找最小生成树的,按边权从小到大排序,枚举最小边,然后不停的加比这条边大的边,直到s,t连通。

#include<bits/stdc++.h>
#define N 505
#define M 5005
using namespace std;
int n,m,s,t,father[N];
struct node
{
    int from,to,val;
}edge[2*M];

inline bool cmp(const node &a,const node &b)
{
    return a.val<b.val;
}
inline int getfather(int x)
{
    if(father[x]==x)    return x;
    return father[x]=getfather(father[x]);
}
inline int gcd(int x,int y)
{
    if(y>x) return gcd(y,x);
    if(!y)  return x;
    return gcd(y,x%y);
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL),cout.tie(NULL);
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        cin>>x>>y>>z;
        edge[i].to=y;
        edge[i].from=x;
        edge[i].val=z;
    }
    cin>>s>>t;
    sort(edge+1,edge+m+1,cmp);
    int ans_max,ans_min;
    for(int i=1;i<=m;i++)
    {
        int j;
        for(j=1;j<=n;j++)   father[j]=j;
        for(j=i;j<=m;j++)
        {
            int ax=getfather(edge[j].from);
            int bx=getfather(edge[j].to);
            if(ax!=bx)
            {
                father[ax]=bx;
                if(getfather(s)==getfather(t))  break;
            }
        }
        if(i==1&&getfather(s)!=getfather(t))
        {
            cout<<"IMPOSSIBLE"<<endl;
            return 0;
        }
        if(getfather(s)!=getfather(t))  break;  //小小的剪枝 
        if(ans_max*edge[i].val>=ans_min*edge[j].val){//只是移一下项 
            ans_max=edge[j].val;
            ans_min=edge[i].val;
        }
    }
    int a=gcd(ans_max,ans_min);
    if(a==ans_min)  cout<<ans_max/ans_min<<endl;
    else cout<<ans_max/a<<"/"<<ans_min/a<<endl;
    return 0;
}

转载于:https://www.cnblogs.com/Patrickpwq/articles/9446294.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值