poj 1861 Network

#include <iostream>            //kruskal
using namespace std;
const int max_ve=1005,max_ed=15005;
int n,m,i,flag[max_ed]; //n,m分别记录顶点数和边数
struct node
{
int par;
}vertex[max_ve];
struct Edge
{
int u,v,weigh;
}edge[max_ed];
int cmp(const void* a,const void* b)
{
return (*(Edge*)a).weigh-(*(Edge*)b).weigh;
}
int find_p(int j)
{
if(vertex[j].par!=j)
{
vertex[j].par
=find_p(vertex[j].par);
}
return vertex[j].par;
}
bool union_set(int s,int t)
{
int os=find_p(s),ot=find_p(t);
if(os==ot)
return false;
vertex[ot].par
=os;
return true;
}
int main()
{
/*freopen("F:\\in.txt","r",stdin);*/
int ct,ms;
scanf(
"%d%d",&n,&m);
for(i=1;i<=n;++i) //顶点从1到n
{
vertex[i].par
=i;
}
for(i=0;i<m;++i)
{
scanf(
"%d%d%d",&edge[i].u,&edge[i].v,&edge[i].weigh);
}
qsort(edge,m,
sizeof(edge[0]),cmp);
ms
=0;ct=0;
for(i=0;i<m&&ct<n-1;++i) //当ct==n-1说明有n-1条边,即所有的顶点都已连接上,终止算法
{
if(union_set(edge[i].u,edge[i].v))
{
++ct; //边数+1
ms=max(ms,edge[i].weigh);
flag[i]
=1;
}
}
printf(
"%d\n%d\n",ms,ct);
for(i=0;i<m;++i)
if(flag[i])
printf(
"%d %d\n",edge[i].u,edge[i].v);
return 0;
}

  

posted on 2011-07-22 16:30  sysu_mjc  阅读(128)  评论(0编辑  收藏  举报

导航