首页 > 其他 > 详细

[BZOJ 2654] tree

时间:2019-01-10 21:27:39      阅读:162      评论:0      收藏:0      [点我收藏+]

tree

参考博客

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

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

BZOJ 2654

技术分享图片

题目大意

给出一个无向图,每个边有一条边权以及一种颜色(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;
}

[BZOJ 2654] tree

原文:https://www.cnblogs.com/ljzalc1022/p/10252338.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!