Prim

8 篇文章 0 订阅

输入:

N(顶点)  M(边)

u v w(权值)

输出:

建图过程、最小生成树的权值

Sample Input:

7 9
1 2 28
1 6 10
2 3 16
2 7 14
3 4 12
4 5 22
4 7 18
5 6 25
5 7 24

Sample Output:

1 6 10
6 5 25
5 4 22
4 3 12
3 2 16
2 7 14
weight of MST is 99

————————————————————集训8.8的分割线————————————————————

思路:Prim模板

代码如下:

/*
ID: j.sure.1
PROG:
LANG: C++
*/
/****************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <iostream>
#define INF 2e9
using namespace std;
/****************************************/
const int N = 105;
int n, m, sum;
int mat[N][N], dis[N], near[N];

int prim(int st)
{
	int sum = 0;
	for(int i = 1; i <= n; i++) {
		dis[i] = mat[st][i];
		near[i] = st;
	}
	near[st] = -1;
	for(int i = 1; i <= n; i++) {
		int k = -1, mini = INF;
		for(int j = 1; j <= n; j++) if(near[j] != -1) {
			if(dis[j] < mini) {
				mini = dis[j];
				k = j;
			}
		}
        if(k == -1) return 0;
        near[k] = -1;
        sum	+= mini;
        for(int j = 1; j <= n; j++) if(near[j] != -1) {
            if(dis[j] > mat[k][j]) {
                near[j] = k;
                dis[j] = mat[k][j];
            }
        }
	}
	printf("weight of MST is %d\n", sum);
    return sum;
}

int main()
{
#ifdef J_Sure
	freopen("test.in", "r", stdin);
//	freopen(".out", "w", stdout);
#endif
	scanf("%d%d", &n, &m);
	for(int i = 0; i < m; i++) {
		int a, b;
		scanf("%d%d", &a, &b);
		scanf("%d", &mat[a][b]);
		mat[b][a] = mat[a][b];
	}

	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= n; j++) {
			if(i == j)
				mat[i][j] = 0;
			else if(mat[i][j] == 0)
				mat[i][j] = INF;
		}
	}
	prim(1);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值