还是畅通工程

题目参见:http://acm.hdu.edu.cn/showproblem.php?pid=1233

Prim实现

#include<iostream>
using namespace std;

const int Maxv=101;

int map[Maxv][Maxv];
int vset[Maxv];//顶点访问记录
int lowcost[Maxv];

int main()
{
	int sum;
	int n,i,j,cost;
	while(scanf("%d",&n) && n)
	{
		int m=n*(n-1)/2;
		while(m--)
		{
			scanf("%d %d %d",&i,&j,&cost);
			//printf("%d\n",i);
			map[i][j]=cost;
		}
		for(i=1;i<=n;i++)
		{
			vset[i]=0; 
			lowcost[i]=map[1][i]; //初始化lowcost
		}
		vset[1]=1;
		int k ,min;
		sum=0;
		for(i=1;i<n;i++)
		{
			min=1001;
			for(j=1;j<=n;j++)
			{
		
				if(!vset[j]&&lowcost[j]<min&&lowcost[j]>0)
				{
					min=lowcost[j];
					k=j;
				}
			}
			vset[k]=1;
			sum+=min;
			for(j=1;j<=n;j++)
			{
				if(!vset[j]&&lowcost[j]>map[k][j]&&map[k][j]>0)
				{
					lowcost[j]=map[k][j];
				}
			}
		
		}
		printf( "%d\n" , sum );
	}

	return 0;
}
 
Kruscal实现
#include <stdio.h>
#include <queue>
using namespace std;

#define Maxv 100+5

typedef struct
{
	int v1,v2,len;
}Node;

bool operator > ( Node a , Node b )
{
	if( a.len > b.len )  return true;
	return false;
}

int fa[Maxv];

int Getfa( int i )
{
	if( fa[i] == i )  return i;
	fa[i] = Getfa(fa[i]);
	return fa[i];
} 

int main()
{
	int n,sum;
	priority_queue< Node,vector<Node>,greater<Node> > Q;  //定义优先队列

	int i,j,len;
	Node e;
	while( scanf( "%d" , &n ) && n )
	{
		int m = n*(n-1)/2;
		while( !Q.empty() )  Q.pop();
		while( m-- )
		{
			scanf( "%d%d%d" , &i , &j , &len );
			e.v1 = i , e.v2 = j , e.len = len;
			Q.push(e);   //压入边信息
		}
		for( i = 1 ; i <= n ; i++ )  fa[i] = i;  //初始化父亲数组
		
		sum = 0;
		while( Q.size() != 0 )   
		{
			Node e;
			e = Q.top();  //取出最小边
			Q.pop();
			if( Getfa(e.v1) != Getfa(e.v2) )  //查,若不相连,则并
			{
				sum += e.len;
				fa[Getfa(e.v2)] = Getfa(e.v1);
			}
		}
		printf( "%d\n" , sum );
	}
	return 0;
}

 
原文地址:https://www.cnblogs.com/flyoung2008/p/2137595.html