点击打开链接 hdu 1102
//并查集 克鲁斯卡尔
#include <iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxe=10000+5;
const int maxv=100+5;
struct Edge{
int from,to,weight;
};
Edge edges[maxe];
int v;
int parent[maxv];
bool operator<(const Edge&E1,const Edge&E2)
{
return E1.weight<E2.weight;
}
int find(int x)
{
return x==parent[x]?x:parent[x]=find(parent[x]);
}
void unite(int x,int y)
{
int p1=find(x);
int p2=find(y);
if(p1==p2) return;
parent[p1]=p2;
}
int main()
{
while(scanf("%d",&v)==1)
{
int ans=0;
for(int i=1;i<=v;i++)
{
parent[i]=i;
for(int j=1;j<=v;j++)
{
int cost;
scanf("%d",&cost);
edges[ans].from=i;
edges[ans].to=j;
edges[ans].weight=cost;
ans++;
}
}
int q;
scanf("%d",&q);
for(int i=0;i<q;i++)
{
int v1,v2;
scanf("%d%d",&v1,&v2);
unite(v1,v2);
}
sort(edges,edges+ans);
int sum=0;
for(int i=0;i<ans;i++)
{
int p1=find(edges[i].from);
int p2=find(edges[i].to);
if(p1==p2) continue;
parent[p1]=p2;
sum+=edges[i].weight;
}
cout<<sum<<endl;
}
return 0;
}
hdu 1102
最新推荐文章于 2018-05-06 22:36:59 发布