[BZOJ 2654] tree

tree

参考博客

https://blog.csdn.net/y752742355/article/details/85468855

https://www.cnblogs.com/cjyyb/p/9438101.html

BZOJ 2654

1

题目大意

给出一个无向图,每个边有一条边权以及一种颜色(0/1),问恰好有 \(k\) 条颜色为 \(0\) 的边的最小生成树,保证有解

数据范围

\(V\le50000,E\le100000\)

时空限制

30sec,512MB

分析

\(F(x)\) 为包含 \(x\)\(0\) 边的最小生成树大小,显然 \(F(x)\) 的斜率递增,而题目求最小值,符合这两个条件,那么就可以套用带权二分解决此题

注意 \(kruskal\) 过程中要求出答案上界,将边权相同的 \(0\) 边排在前面

Code

#include <algorithm>
#include <cstdio>
#include <iostream>
using namespace std;
inline char nc() {
    static char buf[100000], *l = buf, *r = buf;
    return l==r&&(r=(l=buf)+fread(buf,1,100000,stdin),l==r)?EOF:*l++;
}
template<class T> void read(T & x) {
    x = 0; int f = 1, ch = nc();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=nc();}
    while(ch>='0'&&ch<='9'){x=x*10-'0'+ch;ch=nc();}
    x *= f;
}
const int maxn = 50000 + 5;
const int maxm = 100000 + 5;
const int maxv = 100 + 5;
int n, m, k;
int MST, mid;
struct data {
    int u, v, w, c;
    bool operator < (const data & other) const {
        int a = w + (c ? 0 : mid);
        int b = other.w + (other.c ? 0 : mid);
        if(a != b) return a < b;
        return c < other.c;
    }
} e[maxm];
struct union_set {
    int fa[maxn];
    void init() {
        for(int i = 1; i <= n; ++i) fa[i] = i;
    }
    int find(int a) {
        return a == fa[a] ? a : fa[a] = find(fa[a]);
    }
    bool merge(int a, int b) {
        a = find(a), b = find(b);
        if(a == b) return 0;
        fa[a] = b; return 1;
    }
} us;
bool judge() {
    sort(e + 1, e + m + 1);
    us.init();
    int cnt = 0; MST = 0;
    for(int i = 1; i <= m; ++i) {
        int u = e[i].u, v = e[i].v;
        if(us.merge(u, v)) {
            MST += e[i].w + (e[i].c ? 0 : mid);
            if(!e[i].c) cnt++;
        }
    }
    return cnt >= k;
}
int solve() {
    int l = -maxv, r = maxv, re;
    while(l <= r) {
        mid = (l + r) >> 1;
        if(judge()) l = mid + 1, re = MST - k * mid;
        else r = mid - 1;
    }
    return re;
}
int main() {
//  freopen("testdata.in", "r", stdin);
    read(n), read(m), read(k);
    for(int i = 1; i <= m; ++i) {
        read(e[i].u), read(e[i].v), read(e[i].w), read(e[i].c);
        e[i].u++, e[i].v++;
    }
    printf("%d\n", solve());
    return 0;
}

转载于:https://www.cnblogs.com/ljzalc1022/p/10252338.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值