您的位置:首页 > 其它

hdu 1879(并查集+克鲁斯卡尔)

2017-11-20 21:22 323 查看
//并查集 克鲁斯卡尔
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxv=100+5;
const int maxe=5000+5;
struct Edge{
int from,to,weight;
};
bool operator<(const Edge &E1,const Edge &E2)
{
return E1.weight<E2.weight;
}
Edge edges[maxe];
int parent[maxv];
int find(int x)
{
return x==parent[x]?x:parent[x]=find(parent[x]);
}
int kruskal(int pos)
{
sort(edges,edges+pos);
int sum=0;
for(int i=0;i<pos;i++)
{
int cost=edges[i].weight;
int p1=find(edges[i].from);
int p2=find(edges[i].to);
if(p1==p2) continue;
parent[p1]=p2;
sum+=cost;
}
return sum;
}
int main()
{
int n;
while(scanf("%d",&n)==1&&n)
{
for(int i=1;i<=n;i++)
{
parent[i]=i;                //并查集初始化
}
int v1,v2,cost,flag;
int pos=n*(n-1)/2;
for(int i=0;i<pos;i++)
{
scanf("%d%d%d%d",&v1,&v2,&cost,&flag);
if(flag) {
parent[v1]=v2;          //合并
}
edges[i].from=v1;
edges[i].to=v2;
edges[i].weight=cost;
}
cout<<kruskal(pos)<<"\n";
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息