跳到正文

题解

题解:CF2117G Omg Graph

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
获赞
1
题目
CF2117G

版本

  1. v1当前

思路

考虑从小到大加入边,通过并查集来维护集合和最小最大值。 加入一条边后就统计一次答案。 如果合并后 11 和 nn 联通,设 miimi_i 是 ii 所在的集合中最小的一条边,maima_i 是 ii 所在的集合中最大的一条边 ,此时将 ansans 设为 min⁡(ans,mi1+ma1)\min(ans,mi_1+ma_1) 。

证明

假设现在有一个边的集合 SS 表示选择的边。 如果最长边不在我们最后选择的路径中,则删掉最长边对答案没有影响,所以我们假设最长边在 SS 中。 既然最长边在我们最后选择的路径中,则将所有比这条边小的边加入集合一定不会让答案更大。 所以剩下的所有 SS 就都是从小到大加入的边。

code

码风有点差

C++
#include<bits/stdc++.h>
using namespace std;
struct st{
	int x,y,z;
	friend bool operator <(st x,st y){
		return x.z<y.z;
	}
}sz[200009];
int f[200009],ma[200009],mi[200009];
int gf(int x){
	if(f[x]!=x)f[x]=gf(f[x]);
	return f[x];
}
int main(){
	ios::sync_with_stdio(0);
	int t;
	cin>>t;
	while(t--){
		int a,b;
		long long ans=2e10;
		cin>>a>>b;
		for(int i=1;i<=a;i++)f[i]=i,ma[i]=-1,mi[i]=1e9+7;
		for(int i=1,x,y,z;i<=b;i++)cin>>x>>y>>z,sz[i]={x,y,z};
		sort(sz+1,sz+b+1);
		for(int i=1;i<=b;i++){
			int x=sz[i].x,y=sz[i].y,z=sz[i].z;
			int fx=gf(x),fy=gf(y);
			if(fx==fy)continue;
			f[fx]=fy,ma[fy]=max({ma[fy],ma[fx],z}),mi[fy]=min({mi[fy],mi[fx],z});
			if(gf(1)==gf(a)){
				ans=min(ans,0ll+ma[gf(1)]+mi[gf(1)]);
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}
原文