1. 程式人生 > >ZOJ-uild The Electric System(最小生成樹)

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;
}