该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
kruskal&并查集w
```cpp
#include
#include
#include
#include
using namespace std;
int n,m;
int fa[5001];
int sum,now,f1,f2;
inline int read(){
char c;int sum=0;int f=1;
c=getchar();
while(c'9'){
if(c=='-') f=-1;
c=getchar();
}
while(c>='0'&&c<='9') {
sum=sum*10+c-48;
c=getchar();
}
return sum*f;
}
struct zzy{
int l,r,w;
};
zzy ed[200001]; //空间开少了
inline int find(int a){
// if(fa[a]==a) return a;
while(a!=fa[a]) a=fa[a]=fa[fa[a]]; //:) 优化③
return a;
}
inline bool cmp(zzy a,zzy b){
return a.w
}
inline void unite(int a,int b){
fa[a]=fa[b];
return ;
}
inline void kruskal(){
sort(ed+1,ed+1+m,cmp);
// printf("here %d %d\n",ed[1].w,ed[m].w);
for(register int i=1;i<=m;i++){ //循环结构②
f1=find(ed[i].l);
f2=find(ed[i].r);
if(f1==f2) continue;
fa[f1]=f2; //并查集①
sum+=ed[i].w;
//printf("now %d\n",now);
if(++now==n-1) break ;//边最多可以有N-1条;
}
return;
}
int main(){
n=read();
m=read();
// printf("%d %d\n",n,m);
for(register int i=1;i<=m;i++){
ed[i].l=read();ed[i].r=read();
ed[i].w=read();
}
for(register int i=1;i<=n;i++)
fa[i]=i;
//purefy
kruskal();
printf("%d\n",sum);
return 0;
}
```