【BZOJ1196】公路修建问题,二分+最小生成树

[HNOI2006]公路修建问题

Time Limit: 10 Sec Memory Limit: 162 MB
Submit: 1534 Solved: 879
Description

OI island是一个非常漂亮的岛屿,自开发以来,到这儿来旅游的人很多。然而,由于该岛屿刚刚开发不久,所以那里的交通情况还是很糟糕。所以,OIER Association组织成立了,旨在建立OI island的交通系统。 OI island有n个旅游景点,不妨将它们从1到n标号。现在,OIER Association需要修公路将这些景点连接起来。一条公路连接两个景点。公路有,不妨称它们为一级公路和二级公路。一级公路上的车速快,但是修路的花费要大一些。 OIER Association打算修n-1条公路将这些景点连接起来(使得任意两个景点之间都会有一条路径)。为了保证公路系统的效率, OIER Association希望在这n-1条公路之中,至少有k条(0≤k≤n-1)一级公路。OIER Association也不希望为一条公路花费的钱。所以,他们希望在满足上述条件的情况下,花费最多的一条公路的花费尽可能的少。而你的任务就是,在给定一些可能修建的公路的情况下,选择n-1条公路,满足上面的条件。

Input

第一行有三个数n(1≤n≤10000),k(0≤k≤n-1),m(n-1≤m≤20000),这些数之间用空格分开。 N和k如前所述,m表示有m对景点之间可以修公路。以下的m-1行,每一行有4个正整数a,b,c1,c2 (1≤a,b≤n,a≠b,1≤c2≤c1≤30000)表示在景点a与b 之间可以修公路,如果修一级公路,则需要c1的花费,如果修二级公路,则需要c2的花费。

Output

一个数据,表示花费最大的公路的花费。

Sample Input

10 4 20

3 9 6 3

1 3 4 1

5 3 10 2

8 9 8 7

6 8 8 3

7 1 3 2

4 9 9 5

10 8 9 1

2 6 9 1

6 7 9 8

2 6 2 1

3 8 9 5

3 2 9 6

1 6 10 3

5 6 3 1

2 7 6 1

7 8 6 2

10 9 2 1

7 1 10 2
Sample Output

5
写在前面:细节?细节!


思路:我的方法是把所有路的c1,c2放在一起排序,然后对其二分加并查集判断,注意的是要先判断k个一级道路再判断最小生成树的可行性,不能一起判断,也不能颠倒顺序

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,m,k,father[20010],ans=0X7fffffff;
struct os
{
    int x,y,c1,c2;
}a[20010];
struct node
{
    int num,w;
    bool operator<(const node other)const
    {
        return w<other.w;
    }
}b[40010];
int find(int x)
{
    if (father[x]!=x) father[x]=find(father[x]);
    return father[x];
}
main()
{
    scanf("%d%d%d",&n,&k,&m);
    for (int i=1;i<=m-1;i++)
    scanf("%d%d%d%d",&a[i].x,&a[i].y,&a[i].c1,&a[i].c2),
    b[i*2-1].w=a[i].c1,
    b[i*2].w=a[i].c2,
    b[i*2-1].num=b[i*2].num=i;
    sort(b+1,b+2*(m-1)+1);
    int l=1,r=2*m-2,mid;
    while (l<=r)
    {
        mid=(l+r)/2;
        for (int i=1;i<=n;i++) father[i]=i;
        int tot=0;
        for (int i=1;i<=mid;i++)
        {
            int pos=b[i].num;
            if (a[pos].c1>b[mid].w) continue;
            int p=find(a[pos].x),q=find(a[pos].y);
            if (p!=q)
            {
                father[p]=q;
                tot++;
            }
        }
        if (tot<k) {l=mid+1;continue;}
        for (int i=1;i<=mid;i++)
        {
            int pos=b[i].num;
            int p=find(a[pos].x),q=find(a[pos].y);
            if (p!=q)
            {
                father[p]=q;
                tot++;
            }
        }
        if (tot<n-1)l=mid+1;
        else ans=min(b[mid].w,ans),r=mid-1;
    }
    printf("%d",ans);
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值