POJ 2263 Heavy Cargo(二分+并查集)

题目地址:POJ 2263

这题是在网上的一篇关于优先队列的博文中看到的。。但是实在没看出跟优先队列有什么关系。。我用的二分+并查集做出来了。。。

二分路的载重量。然后用并查集检查是否连通。

代码如下:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <queue>
#include <map>
#include<algorithm>
using namespace std;
struct node
{
    int u, v, w;
}bian[20000];
int bin[300], n, tot;
int find1(int x)
{
    return bin[x]==x?x:bin[x]=find1(bin[x]);
}
void merger(int x, int y)
{
    int f1=find1(bin[x]);
    int f2=find1(bin[y]);
    if(f1!=f2)
    {
        bin[f2]=f1;
    }
}
int main()
{
    int m, x, s, t, max1, ans, num=0, i;
    char s1[100], s2[100];
    map<string,int>q;
    q.clear();
    while(scanf("%d%d",&n,&m)!=EOF&&n&&m)
    {
        num++;
        tot=0;
        max1=-1;
        for(i=0;i<m;i++)
        {
            scanf("%s %s%d",s1,s2,&x);
            if(!q[s1])
                q[s1]=++tot;
            if(!q[s2])
                q[s2]=++tot;
            bian[i].u=q[s1];
            bian[i].v=q[s2];
            bian[i].w=x;
            if(max1<x)
                max1=x;
        }
        scanf("%s%s",s1,s2);
        s=q[s1];
        t=q[s2];
        int low=0, high=max1, mid;
        while(low<=high)
        {
            mid=(low+high)>>1;
            for(i=1;i<=n;i++)
                bin[i]=i;
            for(i=0;i<m;i++)
            {
                if(bian[i].w>=mid)
                {
                    merger(bian[i].u,bian[i].v);
                }
            }
            if(find1(bin[s])==find1(bin[t]))
            {
                low=mid+1;
                ans=mid;
            }
            else
            {
                high=mid-1;
            }
        }
        printf("Scenario #%d\n%d tons\n\n",num,ans);
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值