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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
| #include <bits/stdc++.h> using namespace std; typedef long long ll; const int N=1e5+5,M=3e5+5,inf=2e9; struct Edge{ int u,v,w; bool vis; bool operator<(const Edge& other) const { return w < other.w; } }; struct Edge1{ int v,w; }; int fa[N]; int find(int x) { if(fa[x]==x) return x; return fa[x]=find(fa[x]); } vector<Edge1> adj[N]; int up[N][20],dep[N],w1[N][20],w2[N][20]; Edge edg[M]; ll sum=0; int n,m; void kru() { int cnt=0; sort(edg,edg+m); for(int i=1;i<=n;++i) fa[i]=i; for(int i=0;i<m;++i) { auto& [u,v,w,vis]=edg[i]; int ru=find(u),rv=find(v); if(ru!=rv) { fa[ru]=rv; cnt++; sum+=w; vis=1; adj[v].push_back({u,w}); adj[u].push_back({v,w}); if(cnt==n-1) break; } else vis=0; } } void dfs(int u,int p,int ww) { dep[u]=dep[p]+1; up[u][0]=p; w1[u][0]=ww,w2[u][0]=-inf; for(int i=1;i<=19;++i) { up[u][i]=up[up[u][i-1]][i-1]; w1[u][i]=max(w1[u][i-1],w1[up[u][i-1]][i-1]); w2[u][i]=max(w2[u][i-1],w2[up[u][i-1]][i-1]); if(w1[u][i-1]!=w1[up[u][i-1]][i-1]) { w2[u][i]=max(w2[u][i],min(w1[u][i-1],w1[up[u][i-1]][i-1])); } } for(auto [vv,ww]:adj[u]) { if(vv==p) continue; dfs(vv,u,ww); } } int lca(int u,int v,int w) { int res=-inf; if(dep[v]>dep[u]) swap(u,v); for(int i=19;i>=0;--i) { if(dep[up[u][i]]>=dep[v]) { if(w1[u][i]<w) res=max(res,w1[u][i]); else res=max(res,w2[u][i]); u=up[u][i]; } } if(u==v) { return res; } for(int i=19;i>=0;--i) { if(up[u][i]!=up[v][i]) { if(w1[u][i]<w) res=max(res,w1[u][i]); else res=max(res,w2[u][i]); if(w1[v][i]<w) res=max(res,w1[v][i]); else res=max(res,w2[v][i]); u=up[u][i]; v=up[v][i]; } } if(w1[u][0]<w) res=max(res,w1[u][0]); else res=max(res,w2[u][0]); if(w1[v][0]<w) res=max(res,w1[v][0]); else res=max(res,w2[v][0]); return res; } void solve() { cin>>n>>m; for(int i=0;i<m;++i) { int x,y,z; cin>>x>>y>>z; edg[i]={x,y,z}; } kru(); dfs(1,0,-inf); ll ans=1e18; for(int i=0;i<m;++i) { auto [u,v,w,vis]=edg[i]; if(!vis&&u!=v) { int val=lca(u,v,w); if(val>-inf) { ans=min(ans,sum-val+w); } } } cout<<ans<<'\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T=1; while(T--) { solve(); } return 0; }
|