您的位置:首页 > 其它

POJ1861 Network [kruskal + 并查集]

2011-08-12 14:50 295 查看
刚开始用prim。。。超时。。。。。。。。。

#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<algorithm>

#define llong long long
#define Min(a,b) (a<b?a:b)
#define Max(a,b) (a>b?a:b)
#define Abs(a) ((a)>0?(a):-(a))
#define Mod(a,b) (((a)-1+(b))%(b)+1)
using namespace std;
int n,m;
const int N=1005,M=15005;
const int inf=99999999;
int father
;
struct Edge
{
int a,b,c;
bool operator < (Edge &bb)
{
return c<bb.c?true:false;
}
}edge[M];
Edge output[M];
int findfa(int now)
{
while(father[now]>0)
{
now=father[now];
}
return now;
}
void Union(int a,int b)
{
if(father[a]>father[b])
{
father[a]+=father[b];
father[b]=a;
}
else
{
father[b]+=father[a];
father[a]=b;
}
}
void mst()
{
memset(father,-1,sizeof(father));
sort(edge,edge+m);
int count=n-1;
int k=0;
for(int i=0;i<m;i++)
{
int a=edge[i].a;
int b=edge[i].b;
int c=edge[i].c;
int fa=findfa(a);
int fb=findfa(b);
if(fa!=fb)
{
output[k]=edge[i];
Union(fa,fb);
k++;
}
}
printf("%d\n%d\n",output[n-2].c,n-1);
for(int i=0;i<n-1;i++)
printf("%d %d\n",output[i].a,output[i].b);
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&edge[i].a,&edge[i].b,&edge[i].c);
}
mst();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: