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
| const int maxn=2222222; int n,m; pair<int,pii> e[maxn]; int fa[maxn],size[maxn]; void init(int n) { rep(i,1,n) {fa[i]=i;size[i]=1;} } int getfa(int x) { while (fa[x]!=x) x=fa[x]; return x; } int unite(int x,int y) { int fx=getfa(x),fy=getfa(y); if (fx==fy) return 0; if (size[fx]>size[fy]) swap(fx,fy); size[fy]+=size[fx]; fa[fx]=fy; return fx; } void undo(int x) { if (x==0) return; size[fa[x]]-=size[x]; fa[x]=x; } void solve(int l,int r,int L,int R) { if (l==r) { if (size[getfa(1)]==n) {cout<<l<<endl;exit(0);} return; } int mid=(l+r)>>1;
int pos; stack<int> s; for (pos=R;pos>=L&&e[pos].first>mid;pos--) s.push(unite(e[pos].second.first,e[pos].second.second)); solve(l,mid,L,pos); while (!s.empty()) {undo(s.top());s.pop();}
for (pos=L;pos<=R&&e[pos].first<=mid;pos++) s.push(unite(e[pos].second.first,e[pos].second.second)); solve(mid+1,r,pos,R); while (!s.empty()) {undo(s.top());s.pop();} } int main() { read(n,m); init(n); rep(i,1,m) read(e[i].second.first,e[i].second.second,e[i].first); sort(e+1,e+m+1); solve(0,e[m].first+1,1,m); return 0; }
|