#103-[最小生成树之prim算法]Agri-Net

版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/82756401

Description

农夫John被选为他所在市镇的市长。而他的竞选承诺之一是将在该地区的所有的农场用互联网连接起来。现在他需要您的帮助。

John的农场已经连上了高速连接的互联网,现在他要将这一连接与其他农场分享。为了减少成本,他希望用最短长度的光纤将他的农场与其他农场连接起来。

给出连接任意两个农场所需要的光纤长度的列表,请您找到将所有农场连接在一起所需要光纤的最短长度。

任何两个农场之间的距离不会超过100,000。

Input

      输入包括若干组测试用例。每组测试用例的第一行给出农场数目N (3<=N<=100)。然后是N´N的邻接矩阵,其每个元素表示一个农场与另一个农场之间的距离。逻辑上,有N行,每行有N个空格间隔的整数。一行接一行地输入,每行不超过80个字符。当然,矩阵的对角线为0,因为一个农场到自己的距离为0。

Output

     对每个测试用例,输出一个整数,表示把所有农场连接在一起所需要光纤的最短长度。

Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

Sample Output

28

稠密图(几乎就是完全图了),prim算法(炒 鸡)适用。

#include <iostream>
#include <cstring>

#define SIZE 110
#define INF 0x3F3F3F3F

using namespace std;

int graph[SIZE][SIZE], lowcost[SIZE];
bool visited[SIZE];

int main(int argc, char** argv)
{
	int n, i, j, res, mincost, index;
	
	while (~scanf("%d", &n))
	{
		memset(visited, false, sizeof (visited));
		res = 0;
		for (i = 1; i <= n; ++i)
		{
			for (j = 1; j <= n; ++j)
			{
				scanf("%d", &graph[i][j]); // prim算法用的是邻接矩阵,这里直接输入.
			}
		}
		visited[1] = true;
		for (i = 2; i <= n; ++i) // prim算法求最小生成树
		{
			lowcost[i] = graph[1][i];
		}
		for (i = 1; i < n; ++i)
		{
			mincost = INF;
			index = -1;
			for (j = 2; j <= n; ++j)
			{
				if ((!visited[j]) && (mincost > lowcost[j]))
				{
					mincost = lowcost[j];
					index = j;
				}
			}
			visited[index] = true;
			res += lowcost[index];
			for (j = 2; j <= n; ++j)
			{
				lowcost[j] = min(lowcost[j], graph[index][j]);
			}
		}
		printf("%d\n", res);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/82756401