题解:CF2117G Omg Graph

· · 题解

思路

考虑从小到大加入边,通过并查集来维护集合和最小最大值。
加入一条边后就统计一次答案。
如果合并后 1 和 n 联通,设 mi_i 是 i 所在的集合中最小的一条边,ma_i 是 i 所在的集合中最大的一条边 ,此时将 ans 设为 \min(ans,mi_1+ma_1) 。

证明

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

code

码风有点差。

#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;
}