Resolve
We first consider adding an edge (x, y, z) will become what ya son:
(There are not many side drew ...)
Then we separate out this map:
We can see that the contribution for the minimum spanning tree,
It is equivalent to the following of this figure (as the same connectivity):
And the same token, the foremost figure also can become:
Therefore, we only need to connect three sides \ ((X, Y, Z), (X, X +. 1,. 1 + Z), (Y, + Y. 1, Z + 2) \) ,
Finally, then \ (x, y \) to update \ (x + 1, y + 1, x + 2, y + 2 ... \) on the line.
code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define ll long long
#define fre(x) freopen(x".in","r",stdin),freopen(x".out","w",stdout)
using namespace std;
inline int read(){
int sum=0,f=1;char ch=getchar();
while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0' && ch<='9'){sum=sum*10+ch-'0';ch=getchar();}
return f*sum;
}
const int N=200001;
struct edge{int x,y;ll w;}a[N<<1];
int n,m,tot,fa[N];ll f[N],ans;
inline void add(int x,int y,ll z){
a[++tot]=(edge){x,y,z};
}
inline int find(int x){return x==fa[x]? x:fa[x]=find(fa[x]);}
inline bool cmp(edge a,edge b){return a.w<b.w;}
int main(){
n=read();m=read();
for(int i=1;i<=n;i++) fa[i]=i;
memset(f,0x3f,sizeof(f));
while(m--){
int x=read()+1,y=read()+1;ll z=read();
add(x,y,z);f[x]=min(f[x],z+1);f[y]=min(f[y],z+2);
}
for(int i=1;i<=(n<<1);i++) f[i%n+1]=min(f[i%n+1],f[(i-1)%n+1]+2);
for(int i=1;i<=n;i++) add(i,i%n+1,f[i]);
sort(a+1,a+tot+1,cmp);
for(int i=1;i<=tot;i++){
int aa=find(a[i].x),b=find(a[i].y);
if(aa!=b) ans+=a[i].w,fa[aa]=b;
}
printf("%lld\n",ans);
return 0;
}