BZOJ2654 tree 题解(最小生成树+二分答案)

本文探讨了如何通过调整边权并使用二分查找与最小生成树算法,来精确控制生成树中特定类型边的数量,以满足特定需求。

传送门

考虑直接求一个最小生成树,取到的白边数量可能会多于need条或者少于need条,这取决于白边的边权大小。

因此为了取need条白边,我们可以尝试给白边的边权都加上一个值。

白边的边权越大,出现在最小生成树中的白边就越少,因此答案满足很好的单调性,考虑二分答案 m i d mid mid,给所有白边的边权都加上 m i d mid mid,然后求最小生成树,看看取到的白边数量够不够 n e e d need need条。

#include <cctype>
#include <cstdio>
#include <climits>
#include <algorithm>

template <typename T> inline void read(T& t) {
    int f = 0, c = getchar(); t = 0;
    while (!isdigit(c)) f |= c == '-', c = getchar();
    while (isdigit(c)) t = t * 10 + c - 48, c = getchar();
    if (f) t = -t;
}
template <typename T> inline bool chkMin(T& x, const T& y) { return y < x ? (x = y, true) : false; }
template <typename T> inline bool chkMax(T& x, const T& y) { return x < y ? (x = y, true) : false; }
#ifdef WIN32
#define LLIO "%I64d"
#else
#define LLIO "%lld"
#endif	// WIN32 long long
#define rep(I, A, B) for (int I = (A); I <= (B); ++I)
#define rrep(I, A, B) for (int I = (A); I >= (B); --I)
#define erep(I, X) for (int I = head[X]; I; I = next[I])

const int maxn = 5e4 + 207, maxm = 1e5 + 207;
struct Edge {
    int x, y, w, c;
};
Edge e[maxm];
int fa[maxn];
int n, m, need, sum;
inline bool operator<(const Edge& lhs, const Edge& rhs) {
    return lhs.w < rhs.w || (lhs.w == rhs.w && lhs.c < rhs.c);
}
int findf(int x) { return x == fa[x] ? x : fa[x] = findf(fa[x]); }
inline bool check(int mid) {
    rep(i, 1, m) if (!e[i].c) e[i].w += mid;
    std::sort(e + 1, e + m + 1);
    rep(i, 1, n) fa[i] = i;
    int cnt = sum = 0;
    rep(i, 1, m) {
        int fx = findf(e[i].x), fy = findf(e[i].y);
        if (fx ^ fy) {
            fa[fx] = fy;
            sum += e[i].w;
            cnt += !e[i].c;
        }
    }
    rep(i, 1, m) if (!e[i].c) e[i].w -= mid;
    return cnt >= need;
}
int main() {
    read(n); read(m); read(need);
    rep(i, 1, m) {
        read(e[i].x); read(e[i].y); read(e[i].w); read(e[i].c);
        ++e[i].x; ++e[i].y;
    }
    int left = -101, right = 101, pos;
    while (left <= right) {
        int mid = (left + right) >> 1;
        if (check(mid)) left = (pos = mid) + 1;
        else right = mid - 1;
    }
    check(pos);
    printf("%d\n", sum - need * pos);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值