最小生成树Prim算法实现


师姐毕设论文中,重点利用最小生成树实现立体匹配,最小生成树本身为常用的算法,故抽出时间以C++将其实现。

//============================================================================
// Name        : MST.cpp
// Author      : Julie
// Version     : 0.0.1
// Copyright   : Julie@2014.10.19
// Description : To Generate the MST withPrim algorithm
//============================================================================

#include <iostream>
#include <memory.h>
#include <algorithm>
using namespace std;

#define N 7
#define M 7
#define inf 10000

typedef struct node
{
    int matrix[N][M];      //邻接矩阵
    int n;                 //顶点数
    int e;                 //边数
}MGraph1;

void MST(MGraph1 Mtest){
	bool  known[N];
	memset(known, 0, sizeof(known));

	int dist[N];
	for (int i = 1; i<=Mtest.n; i++)
		dist[i] = inf;

	int  pv[N];
	memset(pv, 0, sizeof(pv));

	known[0]=true;
	dist[0]=inf;
	pv[0]=0;
	int n_now=0;

	for (int j = 1; j<Mtest.n; j++)
	{
		int number, dist_tmp;
		number= n_now;
		dist_tmp=inf;
		for (int i = 1; i<Mtest.n; i++){
			if (!known[i]){
				//更新dist值:未归类的点+与当前点有临接+小于原来dist值
				if (Mtest.matrix[i][n_now]>0 && dist[i]>Mtest.matrix[i][n_now])
				{
					dist[i] = Mtest.matrix[i][n_now];
					pv[i]=n_now;
				}
				//找到最小dist的值与坐标
				if (dist_tmp>dist[i]){
					dist_tmp=dist[i];
					number= i;
				}
			}
		}
		cout<<number<<" "<<pv[number]<<":"<<dist_tmp<<endl;
		n_now=number;
		known[n_now]=true;
	}
}

int main(){
	MGraph1 MGraph;
	MGraph.n = 7;
	MGraph.e = 12;
	int n1,n2,e;

	for (int i = 0; i < MGraph.n; i++)
	{
		for (int j = 0; j < MGraph.n; j++)
			MGraph.matrix[i][j] = -inf;
	}

	for (int i = 0; i < MGraph.e; i++){
		cin>>n1>>n2;
		cin>>MGraph.matrix[n1][n2];
		MGraph.matrix[n2][n1] = MGraph.matrix[n1][n2];
	}
	MST(MGraph);

	return 0;
}


附上一组测试数据及结果:

test:

0 1 2
0 2 4
0 3 1
1 3 3
1 4 10
3 4 7
2 3 2
2 5 5
3 5 8
5 6 1
3 6 4
4 6 6


result:

3 0:1
1 0:2
2 3:2
6 3:4
5 6:1
4 6:6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值