HDU 1102 并查集
Constructinig Roads
计算最少还需要多少距离才能将所有节点连接起来
输入节点数N 任意两点间的距离构成的矩阵 ;已经连接起来的点
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<algorithm>
using namespace std;
#define MAX 10005
#define M 102
typedef struct
{
int i,j,k;
}Node;
Node set[MAX];
int father[M],num;
int cmp(Node a,Node b)
{
return a.k<b.k;
}
int find(int x)
{
if(x!=father[x]) father[x]=find(father[x]);
return father[x];
}
void UnionSet(int x,int y)
{
x=find(x);
y=find(y);
if(x!=y)
{
father[x]=y;
num--;
}
}
int main()
{
int n,p,q;
while(scanf("%d",&n)!=EOF){
num=n-1;
for(int m=1;m<=n;m++)
{
father[m]=m;
}
for(int m=1;m<=n;m++)
{
for(int t=1;t<=n;t++)
{
set[(m-1)*n+t].i=m;
set[(m-1)*n+t].j=t;
scanf("%d",&(set[(m-1)*n+t].k));
}
}
sort(set,set+n*n+1,cmp );
scanf("%d",&n);
while(n--)
{
scanf("%d%d",&p,&q);
UnionSet(p,q);
}
int m=1,total=0;
while(m++)
{
if(num==0) break;
if(find(set[m].i)!=find(set[m].j))
{
UnionSet(set[m].i,set[m].j);
total+=set[m].k;
}
}
printf("%d\n",total);
}
return 0;
}
浙公网安备 33010602011771号