现在的位置: 首页 > 综合 > 正文

HDOJ 1233:还是畅通工程 普里姆算法求最小生成树

2018年05月25日 ⁄ 综合 ⁄ 共 937字 ⁄ 字号 评论关闭

    浙大的考验上机题比较单纯,完全就是考最小生成树算法的。最初想用克鲁斯卡尔算法练练手,没想到这个图是个完全图,克丽丝卡尔算法不适用,于是干脆再写一次普里姆算法得了。

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

    我的AC代码:

#include <iostream>
#include <stdio.h>
#include <numeric>
using namespace std;

const int Max = 110;
int g[Max][Max];
int vers;

struct MST
{
	int dist;
	bool belong;
}Mst[Max];

int add(int a, MST &b)
{
	return a + b.dist; 
}

void Prim()
{
	Mst[1].belong = true;

	for(int i=2; i<=vers; ++i)
	{
		Mst[i].dist = g[1][i];
		Mst[i].belong = false;
	}

	for(int i=2; i<=vers; i++)
	{
		int pos = 1;
		while(Mst[pos].belong) ++pos;
		for(int j=pos+1; j<=vers; ++j)
			if(!Mst[j].belong && Mst[j].dist < Mst[pos].dist) 
				pos = j;

		Mst[pos].belong = true;

		for(int j=1; j<=vers; ++j)
			if(!Mst[j].belong && g[pos][j] < Mst[j].dist) 
				Mst[j].dist = g[pos][j];
	}
}

int main()
{
	int head, tail, cost;
	int sum;

	while(scanf("%d", &vers) && vers)
	{
		for(int i=0; i<vers*(vers - 1)/2; ++i)
		{
			scanf("%d%d%d", &head, &tail, &cost);
			g[head][tail] = g[tail][head] = cost;
		}

		Prim();
		sum = accumulate(Mst+1, Mst+vers+1, 0, add);

		printf("%d\n", sum);
	}
	system("pause");
	return 0;
}


   

抱歉!评论已关闭.