Prim算法求解最小生成树 c++代码实现

#include 
#include 

using namespace std;

const int maxn = 100;
const int inf = 0x3f3f3f3f;

int n, m, sum = 0;
int graph[maxn][maxn];
bool visit[maxn];
int closest[maxn];
int lowcost[maxn];

void Prim()
{
	visit[1] = true;
	for(int i = 2; i <= n; i++)
	{
		lowcost[i] = graph[1][i];
		closest[i] = 1;
	}
	for(int i = 1; i <= n - 1; i++)
	{
		int minn = inf, minid = 1;
		for(int j = 2; j <= n; j++)
		{
			if(lowcost[j] < minn && visit[j] == false)
			{
				minn = lowcost[j];
				minid = j;
			}
		}
		sum += minn;
		visit[minid] = true;
		for(int j = 2; j <= n; j++)
		{
			if(graph[minid][j] < lowcost[j] && visit[j] == false)
			{
				lowcost[j] = graph[minid][j];
				closest[j] = minid;
			}
		}
	}
}

int main()
{
	cin >> n >> m;
	fill(graph[0], graph[0] + maxn * maxn, inf); 
	while(m--)
	{
		int a, b, c;
		cin >> a >> b >> c;
		graph[a][b] = graph[b][a] = c;
	}
	Prim();
	cout << sum << endl;
	return 0;
}
/*
测试样例
6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3
12
*/ 

你可能感兴趣的:(数据结构,算法,prim,数据结构)