2021杭电多校第三场 1010 Road Discount 选出k个黑边的最小生成树

题意

给你一个图,每条道路有原价格和折扣价格,在选 k k k条折扣价格的道路时将 n n n个点联通的最小花费 k ∈ [ 0 ∼ n − 1 ] k\in[0\sim n-1] k[0n1]

分析

将折扣边看作黑边,原边看成白边,问题转换为每次选 k k k条黑边的最小生成树的最小值。

考虑将黑边的权值 + c +c +c c c c越大,黑边权值越大,选的黑边越少(满足玄学二分性质)。

wqs二分

总共用到的边数仅需 2 ∗ ( n − 1 ) 2*(n-1) 2(n1),即黑边和白边分别跑最小生成树所需的边。

对于上述 c c c可以预处理,从-1000跑到1000,每次记录当前选了多少条折扣边,以及花费的价格,可以采用从小到大合并的方式(从 s t d std std学的)。

代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int ,int> pii;
#define endl '\n'
ll gcd(ll a, ll b){
    return b == 0 ? a : gcd(b, a % b);
}
void input(){
    freopen("1010.in", "r", stdin);
    freopen("out.txt", "w", stdout);
}
const int N = 1e6+10, M = N * 2, inf = 1e8;
int t, n, m, cnt;
int f[N];
pii p[N];
struct Node{
    int u, v, w;
    bool operator < (const Node & n) const{
        return w < n.w;
    } 
}a[N], b[N], e[N];
int find(int x){
    return f[x] == x ? f[x] : f[x] = find(f[x]);
}
void mst(Node *a){
    for(int i = 1; i <= n; i++) f[i] = i;
    sort(a + 1, a + m + 1);
    int cnt1 = 0;
    for(int i = 1; i <= m; i++){
        int u = find(a[i].u), v = find(a[i].v), w = a[i].w;
        if(u == v) continue;
        a[++cnt1] = {u, v, w};
        f[u] = v;
    }
}
pii cal(int mid){
    for(int i = 1; i <= n; i++) f[i] = i;
    for(int i = 1; i <= n; i++) b[i].w += mid;
    int A = 1, B = 1, sum = 0, cnt = 0;
    while(A < n && B < n){
        if(a[A].w <= b[B].w){
            int u = find(a[A].u), v = find(a[A].v), w = a[A].w;
            if(u != v) f[u] = v, sum += w;
            A ++;
        }else{
            int u = find(b[B].u), v = find(b[B].v), w = b[B].w;
            if(u != v) f[u] = v, sum += w, cnt++;
            B ++;
        }
    }
    while(A < n){
        int u = find(a[A].u), v = find(a[A].v), w = a[A].w;
        if(u != v) f[u] = v, sum += w;
        A ++;
    }
    while(B < n){
        int u = find(b[B].u), v = find(b[B].v), w = b[B].w;
        if(u != v) f[u] = v, sum += w, cnt++;
        B ++;
    }
    for(int i = 1; i <= n; i++) b[i].w -= mid;
    return {cnt, sum};
}
int main(){
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cin>>t;
    while(t--){
        cin>>n>>m;
        for(int i = 1; i <= m; i++) {
            cin>>a[i].u>>a[i].v>>a[i].w>>b[i].w;
            b[i].u = a[i].u, b[i].v = a[i].v;
        }
        mst(a);
        mst(b);
        for(int i = -1010; i <= 1010; i++) p[i+1010] = cal(i);
        for(int k = 0; k < n; k++) // 此处可以用二分写,复杂度够跑个暴力。。。
            for(int j = -1010; j <= 1010; j++)
                if(p[j + 1010].first <= k){
                    cout<<p[j+1010].second - k * j<<endl;
                    break;
                }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值