Hdu-1102 Constructing Roads

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1102


代码如下:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
#define MAX 0x3f3f3f3f
int num, mnum;

int map[110][110], visit[110], lowcost[110];

int prime(int cur)
{
	int minn, k, sum = 0;
	visit[cur] = 1; //第一个点归入最小生成树集合,作为起点
	for(int i = 1; i <= num; ++i)
		lowcost[i] = map[cur][i]; //lowcost[]保存所有到cur点的距离
	for(int i = 2; i <= num; ++i)
	{
		minn = MAX;
		for(int j = 1; j <= num; ++j)
			if(lowcost[j] < minn && !visit[j])
			{
				minn = lowcost[j]; //找出到cur点最短的边
				k = j;//记录边权值最小的顶点
			}
		sum += minn; //权值求和
		visit[k] = 1; //加入最小生成树集合
		for(int j = 1; j <= num; ++j)
		{
			if(lowcost[j] > map[k][j] && !visit[j])
				lowcost[j] = map[k][j]; //找出与最小生成树集合距离最近的边
		}
	}
	return sum; //返回权值
}

int main()
{
	int a, b;
	while(scanf("%d", &num) != EOF)
	{
		memset(visit, 0, sizeof(visit));
		memset(map, 0, sizeof(map));
		for(int i = 1; i <= num; ++i)
			for(int j = 1; j <= num; ++j)
				scanf("%d", &map[i][j]);
		scanf("%d", &mnum);
		for(int i = 1; i <= mnum; ++i)
		{
			scanf("%d%d", &a, &b);
			map[a][b] = map[b][a] = 0; //已修路,则距离重置为0即可
		}
		printf("%d\n", prime(1));
	}
	return 0;
}


你可能感兴趣的:(Hdu-1102 Constructing Roads)