传送门:www.lydsy.com:808/JudgeOnline/problem.php?id=1977
抄gty题解终于A了= =、
Code:
#include<cstdio> //#include<ctime> #include<climits> #include<iostream> #include<algorithm> #include<vector> #include<queue> using namespace std; const int maxn=1e5+10; const int maxm=3e5+10; struct edge{int u,v,w;edge(int _u=0,int _v=0,int _w=0){u=_u,v=_v,w=_w;} bool operator < (const edge &a)const {return w<a.w;};}; vector<edge>G,Ge[maxn]; int vis[maxm]; int n,m; int faa[maxn],a[maxn]; int find(int x){ if(faa[x]!=x) return faa[x]=find(faa[x]); return x; } long long ans=0; int p[maxm][18],maxx[maxm][18],maxi[maxm][18],dep[maxn]; void updata(int &a,int &b,int x1,int y1,int x2,int y2){ if(x1>x2){ a=x1;b=max(y1,x2); }else if(x1<x2){ a=x2;b=max(x1,y2); }else{ a=x1;b=max(y1,y2); } } void initlca(){ queue<int>q;q.push(1); while(!q.empty()){ int u=q.front();q.pop(); for(int i=0;i<Ge[u].size();i++){ int v=Ge[u][i].v,w=Ge[u][i].w; if(v!=1&&!dep[v]){ dep[v]=dep[u]+1; p[v][0]=u; maxx[v][0]=w; maxi[v][0]=0; q.push(v); } } } for(int k=1;k<18;k++) for(int i=1;i<=n;i++){ p[i][k]=p[p[i][k-1]][k-1]; updata(maxx[i][k],maxi[i][k], maxx[i][k-1],maxi[i][k-1], maxx[p[i][k-1]][k-1],maxi[p[i][k-1]][k-1]); } } pair<int,int> Query(int x, int y) { int Maxx = -1; int Maxi = -1; if (dep[x] < dep[y]) swap(x,y); for (int i = 17; i >= 0; i--) if (dep[p[x][i]] >= dep[y]){ updata(Maxx, Maxi, Maxx, Maxi, maxx[x][i], maxi[x][i]); x = p[x][i]; } if (x == y) return pair<int,int>(Maxx,Maxi); for (int i = 17; i >= 0; i--) if (p[x][i] != p[y][i]) { updata(Maxx, Maxi, Maxx, Maxi, maxx[x][i], maxi[x][i]); updata(Maxx, Maxi, Maxx, Maxi, maxx[y][i], maxi[y][i]); x = p[x][i]; y = p[y][i]; } updata(Maxx, Maxi, Maxx, Maxi, maxx[x][0], maxi[x][0]); updata(Maxx, Maxi, Maxx, Maxi, maxx[y][0], maxi[y][0]); return pair<int,int>(Maxx,Maxi); } int main(){ // double st=clock(); // freopen("1.txt","r",stdin); scanf("%d%d",&n,&m); for(int i=1;i<=n;i++)faa[i]=i; for(int i=1;i<=m;i++){ int u,v,w;scanf("%d%d%d",&u,&v,&w); G.push_back(edge(u,v,w)); }sort(G.begin(),G.end()); for(int i=0;i<m;i++){ int u=G[i].u,v=G[i].v,w=G[i].w; int fau=find(u),fav=find(v); if(fau!=fav){ faa[fau]=fav; vis[i]=1;ans+=w; Ge[u].push_back(edge(u,v,w)); Ge[v].push_back(edge(v,u,w)); } }initlca(); long long res,Ans=1LL<<61; for(int i=0;i<m;i++){ res=ans; if(vis[i])continue; int u=G[i].u,v=G[i].v,w=G[i].w; res+=w; pair<int,int> pi=Query(u,v); if(pi.first==w)res-=pi.second;else res-=pi.first; Ans=min(Ans,res); } cout<<Ans<<endl; // cerr<<(clock()-st)/CLOCKS_PER_SEC<<endl; return 0; }