题目传送门
比较有趣的思维题。
题目要求最小生成树可能包含第一条边 (u,v) 时,第一条边的最大长度。
考虑 Kruskal 算法的实现流程是不断添加最小的边,那么最小生成树中包含第一条边的充要条件就是第一条边的长度 ≤ 最小生成树中最长边的长度。
但是考虑如果连边的时候把 (u,v) 连通了,那第一条边就没有意义了。所以当 (u,v) 联通时,第一条边应该更新成当前生成树中的最长边。
所以实现就是抛开第一条边,对剩下的边跑 Kruskal,当 (u,v) 联通时输出此时生成树中最长边的长度。
额外地,如果抛开第一条边后无法构成生成树,那么第一条边长度为最大值 109。
时间复杂度 O(mlogm)。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| #include<bits/stdc++.h> #define ll long long #define back return #define ri register int using namespace std; ll read() { ll x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9') { if(ch=='-') f=-1; ch=getchar(); } while(ch>='0'&&ch<='9') { x=x*10+ch-'0'; ch=getchar(); } back x*f; } ll n,m,cnt,maxx=-1,fa[100005]; struct node { ll x,y,w; }a[1000005]; ll find(ll x) { if(fa[x]==x) back x; back fa[x]=find(fa[x]); } bool cmp(node a,node b) { back a.w<b.w; } int main() { n=read(),m=read(); for(ri i=1;i<=n;i++) fa[i]=i; for(ri i=1;i<=m;i++) a[i].x=read(),a[i].y=read(),a[i].w=read(); sort(a+2,a+m+1,cmp); for(ri i=2;i<=m;i++) { if(find(a[i].x)==find(a[i].y)) continue; else { fa[find(a[i].x)]=find(a[i].y); cnt++; maxx=max(maxx,a[i].w); if(find(a[1].x)==find(a[1].y)) { cout<<maxx<<"\n"; back 0; }
} } if(cnt<n-1) cout<<1000000000<<"\n"; back 0; }
|