[最小生成树+二分] bzoj1196: [HNOI2006]公路修建问题

bzoj1196: [HNOI2006]公路修建问题:http://www.lydsy.com/JudgeOnline/problem.php?id=1196

n-1条边联通n个城市且长度最小 考虑kruskal
只对最大边有要求的话 考虑二分?

因为只对最大边有要求所以其他的是1还是mid-1都没关系
所以排序只是为了把一级公路涌上来

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct node
{
    int x,y,c1,c2,c,next,u;//u:==1:选的是c1 u==2 选的是c2 u==3不选
}a[21000];
int last[11000],len;
int l,r,mid,ans;
int n,m,k;
int fa[11000];
void build(int x,int y,int c1,int c2)
{
    len++;
    a[len].x=x;a[len].y=y;a[len].c1=c1;a[len].c2=c2;a[len].c=999999999;a[len].next=last[x];last[x]=len;
    a[len].u=0;
}
int findfa(int x)
{
    if (x==fa[x]) return fa[x];
    else {fa[x]=findfa(fa[x]);return fa[x];}
}
bool cmp(node x,node y)
{
    return x.u<y.u;
}
bool solve()
{
    int len=0; 
    for (int i=1;i<=m;i++)
    {
        a[i].c=999999999;a[i].u=3;
        if (a[i].c1<=mid)
        {
            len++;
            a[i].u=1;
            a[i].c=a[i].c1; 
        } 
        else if (a[i].c2<=mid)
        {
            len++;
            a[i].u=2;
            a[i].c=a[i].c2;
        }
    }
    if (len<n-1) return 0;
    for (int i=1;i<=n;i++) fa[i]=i;
    sort(a+1,a+m+1,cmp);//吧一级公路尽量放到前面做 
    int sum1=0,sum12=0;
    for (int i=1;i<=len;i++)
    {
        if (a[i].u!=0)
        {
            int x=a[i].x,y=a[i].y;
            int fx=findfa(x),fy=findfa(y);
            if (fx!=fy)
            {
                fa[fx]=fy;
                sum12++;
                if (a[i].u==1) sum1++;
                if (sum12==n-1) break;
            }
        }
    }
    if (sum12<n-1) return 0;
    if (sum1<k) return 0;
    return 1; 
}
int main()
{
    scanf("%d%d%d",&n,&k,&m);
    m--;
    for (int i=1;i<=m;i++)
    {
        int x,y,c1,c2;
        scanf("%d%d%d%d",&x,&y,&c1,&c2);
        build(x,y,c1,c2);
    }
    l=0;r=30000;
    while (l<=r)
    {
        mid=(l+r)/2;
        if (solve())
        {
            ans=mid;
            r=mid-1;
        }
        else
        {
            l=mid+1;
        }
    }
    printf("%d\n",ans);
    return 0;
}
    原文作者:道路修建问题
    原文地址: https://blog.csdn.net/qq_36038511/article/details/79566782
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞