题面
https://www.luogu.org/problem/AT2134
题解
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define LL long long #define ri register int #define N 200500 struct edge{ int u,v,l; bool operator < (const edge &rhs) const { return l<rhs.l; } } e[N<<1]; int f[N],v[N]; int n,m; LL ans; int findroot(int x){ if (f[x]==x) return x; return f[x]=findroot(f[x]); } using namespace std; int main(){ scanf("%d %d",&n,&m); for (ri i=0;i<n;i++) v[i]=2000000000; for (ri i=1;i<=m;i++) { scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].l); v[e[i].u]=min(e[i].l+1,v[e[i].u]); v[e[i].v]=min(e[i].l+2,v[e[i].v]); } for (ri i=0;i<n;i++) f[i]=i; for (ri i=0;i<2*n;i++) v[(i+1)%n]=min(v[(i+1)%n],v[i%n]+2); int cc=m; for (ri i=0;i<n-1;i++) e[++cc]=(edge){i,i+1,v[i]}; e[++cc]=(edge){n-1,0,v[n-1]}; sort(e+1,e+cc+1); for (ri i=1;i<=cc;i++) { int r1=findroot(e[i].u),r2=findroot(e[i].v); if (r1==r2) continue; f[r1]=r2; ans+=e[i].l; } cout<<ans<<endl; }