ZOJ-uild The Electric System(最小生成树)

uild The Electric System

In last winter, there was a big snow storm in South China. The electric system was damaged seriously. Lots of power lines were broken and lots of villages lost contact with the main power grid. The government wants to reconstruct the electric system as soon as possible. So, as a professional programmer, you are asked to write a program to calculate the minimum cost to reconstruct the power lines to make sure there's at least one way between every two villages.

Input

Standard input will contain multiple test cases. The first line of the input is a single integer T (1 <= T <= 50) which is the number of test cases. And it will be followed by T consecutive test cases.

In each test case, the first line contains two positive integers N and E (2 <= N <= 500, N <= E <= N * (N - 1) / 2), representing the number of the villages and the number of the original power lines between villages. There follow E lines, and each of them contains three integers, A, B, K (0 <= A, B < N, 0 <= K < 1000). A and B respectively means the index of the starting village and ending village of the power line. If K is 0, it means this line still works fine after the snow storm. If K is a positive integer, it means this line will cost K to reconstruct. There will be at most one line between any two villages, and there will not be any line from one village to itself.

Output

For each test case in the input, there's only one line that contains the minimum cost to recover the electric system to make sure that there's at least one way between every two villages.

Sample Input

1
3 3
0 1 5
0 2 0
1 2 9

Sample Output

5

题目链接:

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2966

题意描述:

给你n个点m条边,然后是m行表示两两点之间连起来的权值,求这些点的最小生成树。

解题思路:

先把所有的点存起来,然后普里姆算法即可。

程序代码:

#include<stdio.h>
#include<string.h>
const int inf=99999999;
int e[510][510],dis[510];
bool book[510];
int n,m;

int prim();

int main()
{
	int T,i,j,a,b,c;
	
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&n,&m);
		
		for(i=0;i<n;i++)
			for(j=i;j<n;j++)
				if(i==j)
					e[i][j]=0;
				else
					e[i][j]=e[j][i]=inf;
	
		for(i=0;i<m;i++)
		{
			scanf("%d%d%d",&a,&b,&c);
			if(c<e[a][b])
				e[a][b]=e[b][a]=c;
		}
		printf("%d\n",prim());	
	}
	return 0;	
} 
int prim()
{
	int i,k,u,mi,sum=0;
	for(i=0;i<n;i++)
		dis[i]=e[0][i];
	memset(book,0,sizeof(book));
	book[0]=1;
	for(k=0;k<n-1;k++)
	{
		mi=inf;
		for(i=0;i<n;i++)
			if(book[i]==0&&dis[i]<mi)
			{
				mi=dis[i];
				u=i;
			}
		sum+=dis[u];
		book[u]=1;
		for(i=0;i<n;i++)
			if(book[i]==0&&dis[i]>e[u][i])
				dis[i]=e[u][i];
	}
	return sum;
}

猜你喜欢

转载自blog.csdn.net/HeZhiYing_/article/details/84174004
今日推荐