师姐毕设论文中,重点利用最小生成树实现立体匹配,最小生成树本身为常用的算法,故抽出时间以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