跳到正文

个人记录

Road Reform 题解

sixwl约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年2月6日
篇幅
约 2 分钟

版本

  1. v1当前

题目描述:伯兰国要维修公路,由于调整限速工程浩大,交通部希望尽可能减少调整次数,改革目标是最终保留的(n−1)条道路中,最高限速值恰好为k

思路:我们先正常跑一遍最小生成树,并存一下最高限速,如果这条边大于k了,也就是可以保留,答案就上他们的差值,最后如果最高限速小于k,也就是不满足要求,输出边权和k的最小差值,否则,输出答案

代码:

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long

int f[1000010];
int n,m,k,ans,ma;
struct db{
    int x,y,w;
}a[1000010];
bool cmp(db a,db b){
    return a.w<b.w;
}
int gf(int x){
	if(x==f[x]){
		return x;
	}
	f[x]=gf(f[x]);
	return f[x];
}
void merge(int x,int y,int w){
    x=gf(x),y=gf(y);
    if(x!=y){
        f[y]=x;
        ma=max(ma,w);
        if(w>k){
      		ans+=w-k;
		}
    }
}
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int q;
	cin>>q;
	while(q--){
		cin>>n>>m>>k;
		ma=0,ans=0;
		for(int i=1; i<=n; i++){
			f[i]=i;
		}
		int mi=1e18;
		for(int i=1; i<=m; i++){
			cin>>a[i].x>>a[i].y>>a[i].w;
			mi=min(mi,abs(k-a[i].w));
		}
		sort(a+1,a+m+1,cmp);
		for(int i=1; i<=m; i++){
			merge(a[i].x,a[i].y,a[i].w);
		}
		if(ma<k){
			cout<<mi<<"\n";
		}else{
			cout<<ans<<"\n";
		}
	}
	return 0;
}
原文