算法导论第23章第2节
#include<iostream>
#include<cmath>
using namespace std;
struct node{
node(int i,int j,int l):x(i),y(j),len(l){}
int x;
int y;
int len;
};
int N,M;
int u,v,l;
node* length[1000];
int p[1000];
int cnt=0;
int getGroup(int i)
{
if(p[i]!=i)
p[i]=getGroup(i);
return ppos;
}
void Heapify(int pos)
{
int l=pos*2;
int r=pos*2+1;
int min=pos;
if(r<=cnt&&length[r]->len<length[min]->len)
min=r;
if(l<=cnt&&length[l]->len<length[min]->len)
min=l;
if(min!=pos)
{
swap(length[min],length[pos]);
Heapify(min);
}
}
void insert(node* nd)
{
int pos=++cnt;
length[pos]=nd;
int parent=floor(pos/2);
while(parent>0&&length[parent]->len>length[pos]->len)
{
swap(length[parent],length[pos]);
pos=parent;
parent=floor(pos/2);
}
}
node* ExtractMin()
{
swap(length[1],length[cnt]);
Heapify(1);
return length[cnt--];
}
int main()
{
cin>>N>>M;
int ans=0;
for(int i=0;i<N;++i)
p[i]=-1;
for(int i=0;i<M;++i)
{
cin>>u>>v>>l;
node *nd=new node(u,v,l);
insert(nd);
}
while(cnt>0)
{
node* nd=ExtractMin();
int x=nd->x,y=nd->y,len=nd->len;
delete nd;
nd=NULL;
if(p[x]==-1&&p[y]==-1)
{
p[x]=x;
p[y]=x;
ans+=len;
}
else if(p[x]!=-1&&p[y]!=-1)
{
if(getGroup(x)!=getGroup(y))
{
p[getGroup(y)]=getGroup(x);
ans+=len;
}
}
else
{
int px=p[x]!=-1?x:y;
int py=px==x?y:x;
p[py]=getGroup(px);
ans+=len;
}
}
cout<<ans<<endl;
return 0;
}