#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
namespace wzl{
int n,m;
const int MAXM = (2e5 + 1)*2;
const int MAXN = 5e3 +1;
int fa[MAXN]={};
vector<int>fr,wt,to,nxt,head;
struct node{
int ent;
int num;
}a[MAXM]={};
int cnt=-1;
int ans = 0;
int stats = 0;
inline void add(int x,int y,int z){
fr.push_back(x);
to.push_back(y);
wt.push_back(z);
a[++cnt].ent = z;
a[cnt].num = cnt;
nxt.push_back(head[x]);
head[x] = wt.size() - 1;
return;
}
bool cmp(node x,node y){
return x.ent < y.ent;
}
int getfa(int x){
if(fa[x] != x){
x = getfa(fa[x]);
}else{
return x;
}
}
void merge(int a1,int b1){
fa[getfa(a1)] = getfa(b1);
}
void kruckal(){
stats = 0;
sort(a+1,a+1+m,cmp);
for(int i = 1; i <= n; ++i) fa[i] = i;
for(int i = 1; i <= n; ++i){
int x = a[i].num;
int u = fr[x],v = to[x], w = wt[x];
if(getfa(u) != getfa(v)){
ans += w;
merge(u,v);
++stats;
// cout<<"gc:"a<<u<<"->"<<v<<endl;
}
if(stats == n-1){
break;
}
}
}
void main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin>>n>>m;
head.resize(n+1,-1);
for(int i = 1; i <= m; ++i){
int x,y,z;
cin>>x>>y>>z;
add(x,y,z);
}
kruckal();
if(stats < n-1){
cout<<"orz"<<endl;
}else{
cout<<ans;
}
return;
}
}
int main(){
wzl::main();
return 0;
}
下载样例 :
谢谢了