CF2117G 题解
题意
给定一个带权无向连通图,定义一条长度为 路径的费用如下:
- 设路径经过边的权值为 。
- 路径的费用定义为 ,也就是最大的边权加上最小的边权。
请求出所有从结点 到结点 的路径中最小的费用。注意路径未必是简单路径。
思路
对于输入的点,可以按 从小到大排序,用最小生成树的方法往图中加边,并用并查集维护是否连通和最小值。如果在某一时刻结点 的父亲等于结点 ,也就是说这两个点位于同一连通块,则答案合法、记录答案,图的最大值则为当前点的 。
易错点
在维护是否连通时,如果第一次确定结点 和结点 在同一连通块时就结束,就会导致答案统计不全,所以要把所有边都遍历完才能结束。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10, INF = 2e9 + 5;
int vis[N];
struct Dsu{
int n, fa[N];
void init(int n){
this->n = n;
for(int i = 1; i <= n; i++){
fa[i] = i, vis[i] = INF;
}
}
int find(int x){
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
bool connected(int x, int y){
return find(x) == find(y);
}
}t;
struct P{
int u, v, w;
};
bool cmp(const P &a, const P &b){
return a.w < b.w;
}
int n, m;
void solve(){
cin >> n >> m;
t.init(n);
vector<P> rec;
for(int i = 1, u, v, w; i <= m; i++){
cin >> u >> v >> w;
rec.push_back({u, v, w});
}
sort(rec.begin(), rec.end(), cmp);
int ans = INF;
for(auto e : rec){
auto [u, v, w] = e;
int fu = t.find(u), fv = t.find(v);
vis[fv] = min({vis[fv], vis[fu], w});
t.fa[fu] = fv;
if(t.find(1) == t.find(n)){
ans = min(ans, vis[t.find(1)] + w);
}
}
cout << ans << "\n";
}
int main(){
int T;
cin >> T;
while(T--){
solve();
}
return 0;
}