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
| #include<bits/stdc++.h> #define fo(i,a,b) for(int i=a;i<=b;i++) #define fd(i,a,b) for(int i=a;i>=b;i--) using namespace std;
typedef long long LL;
const int maxn=1e5+5, maxm=3e5+5, MX=17;
struct E{ int x,y,w; }; bool cmpE(const E &a,const E &b) {return a.w<b.w;}
int n,m; E e[maxm]; vector<pair<int,int>> eg[maxn],et[maxn];
LL ans; int ga[maxn]; int get(int x) {return (ga[x]==x) ?x :ga[x]=get(ga[x]) ;} void Kruscal() { sort(e+1,e+1+m,cmpE); fo(i,1,n) ga[i]=i; fo(i,1,m) if (get(e[i].x)!=get(e[i].y)) { ans+=e[i].w; ga[get(e[i].x)]=get(e[i].y); et[e[i].x].push_back(make_pair(e[i].y,e[i].w)), et[e[i].y].push_back(make_pair(e[i].x,e[i].w)); } }
int deep[maxn],fa[maxn][MX+2],maxv[maxn][MX+2],dfn[maxn],en[maxn],tot; void dfs_pre(int k,int last,int s) { deep[k]=deep[last]+1; fa[k][0]=last, maxv[k][0]=s; fo(j,1,MX) fa[k][j]=fa[fa[k][j-1]][j-1], maxv[k][j]=max(maxv[k][j-1],maxv[fa[k][j-1]][j-1]); dfn[k]=++tot; for(pair<int,int> son:et[k]) if (son.first!=last) dfs_pre(son.first,k,son.second); en[k]=tot; } int lca(int x,int y) { if (deep[x]<deep[y]) swap(x,y); fd(j,MX,0) if (deep[fa[x][j]]>=deep[y]) x=fa[x][j]; if (x==y) return x; fd(j,MX,0) if (fa[x][j]!=fa[y][j]) x=fa[x][j], y=fa[y][j]; return fa[x][0]; } int dis(int x,int y) { int re=0; fd(j,MX,0) if (deep[fa[x][j]]>=deep[y]) re=max(re,maxv[x][j]), x=fa[x][j]; return re; }
int p0,p[2*maxn],z0,z[2*maxn]; bool cmp(const int &a,const int &b) {return dfn[a]<dfn[b];} void vtree(int x) { LL ans1=0; p0=0; for(pair<int,int> go:eg[x]) { p[++p0]=go.first; ans1+=go.second; } p[++p0]=x; sort(p+1,p+1+p0,cmp); int tmp=p0-1; fo(i,1,tmp) p[++p0]=lca(p[i],p[i+1]); sort(p+1,p+1+p0,cmp); z0=m=0; fo(i,1,p0) if (i==1 || p[i]!=p[i-1]) { while (z0 && en[z[z0]]<dfn[p[i]]) z0--; if (z0) { ans1-=dis(p[i],z[z0]); e[++m]=(E){z[z0],p[i],dis(p[i],z[z0])}; } z[++z0]=p[i]; } fo(i,1,p0) ga[p[i]]=p[i]; for(pair<int,int> go:eg[x]) ga[go.first]=x; sort(e+1,e+1+m,cmpE); fo(i,1,m) if (get(e[i].x)!=get(e[i].y)) { ans1+=e[i].w; ga[get(e[i].x)]=get(e[i].y); } printf("%lld\n",ans1+ans); }
int main() { scanf("%d %d",&n,&m); fo(i,1,m) { scanf("%d %d %d",&e[i].x,&e[i].y,&e[i].w); eg[e[i].x].push_back(make_pair(e[i].y,e[i].w)), eg[e[i].y].push_back(make_pair(e[i].x,e[i].w)); } Kruscal(); dfs_pre(1,0,0); fo(i,1,n) vtree(i); }
|