标签:
1 4 6 1 2 10 2 3 10 3 1 10 1 4 1 2 4 1 3 4 1 1 3 5 6
4
kruskal算法
#include<stdio.h>
#include<algorithm>
using namespace std;
int set[510],hua[510];
struct record
{
int beg;
int end;
int mo;
}s[130000];
int find(int fa)
{
int ch=fa;
int t;
while(fa!=set[fa])
fa=set[fa];
while(ch!=fa)
{
t=set[ch];
set[ch]=fa;
ch=t;
}
return fa;
}
void mix(int x,int y)
{
int fx,fy;
fx=find(x);
fy=find(y);
if(fx!=fy)
set[fx]=fy;
}
bool cmp(int a,int b)
{
return a<b;
}
bool cmp1(record c,record d)
{
return c.mo<d.mo;
}
int main()
{
int n,m,j,i,sum,lou,e;
scanf("%d",&n);
while(n--)
{
scanf("%d%d",&lou,&e);
for(i=0;i<e;i++)
{
scanf("%d%d%d",&s[i].beg,&s[i].end,&s[i].mo);
}
sort(s,s+e,cmp1);
for(i=0;i<=lou;i++)
{
set[i]=i;
}
for(i=0;i<lou;i++)
scanf("%d",&hua[i]);
sort(hua,hua+lou,cmp);
sum=hua[0];
for(i=0;i<e;i++)
{
if(find(s[i].beg)!=find(s[i].end))
{
mix(s[i].beg,s[i].end);
sum+=s[i].mo;
}
}
printf("%d\n",sum);
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/tonghao/p/4468651.html