Prim算法

#include "stdafx.h"
#include <iostream>
#include <limits>
#include <iomanip>
using namespace std;
//const int NUM = 3;
//int map[3][3] = { {0, 1, 2},
//                  {1, 0, 3}, 
//                  {2, 3, 0} };
const int NUM = 7;
int map[NUM][NUM] = { {0,  28,  INT_MAX,  INT_MAX,  INT_MAX,  10,  INT_MAX},
                      {28,  0,  16,  INT_MAX,  INT_MAX,  INT_MAX,  14},
					  {0,  16,  0,  12,  INT_MAX,  INT_MAX,  INT_MAX},
					  {INT_MAX,  INT_MAX,  12,  0,  22,  INT_MAX,  18},
					  {INT_MAX,  INT_MAX,  INT_MAX,  22,  0,  25,  24},
					  {10,  INT_MAX,  INT_MAX,  INT_MAX,  25,  0,  INT_MAX},
                      {INT_MAX,  14,  INT_MAX,  18,  24,  INT_MAX,  0} };

int _tmain(int argc, _TCHAR* argv[])
{
	bool visited[NUM] = {false};
	int minDis = (std::numeric_limits<int>::max)();
	int nextVertex;
	int beginVertex;
	int nextVertex_temp;
	int shortest[NUM] = { (std::numeric_limits<int>::max)() };
	int shortest_index[NUM] = {0};
	int vertex[NUM-1][2];

	visited[0] = true;
	for( int i = 1; i < NUM; i++ )
	{
		shortest[i] = map[0][i];
		if( shortest[i] < minDis  )
		{
			nextVertex = i;
			minDis = shortest[i];
		}
	}
	vertex[0][1] = 0;
	vertex[0][2] = nextVertex;
	visited[nextVertex] = true;
	
	for( int i = 1; i < NUM - 1; i++ )
	{
		minDis = std::numeric_limits<int>::max();
		for( int j = 0; j < NUM; j++ )
		{
			if( false == visited[j] )
			{
				if( map[nextVertex][j] < shortest[j] )
				{
					shortest[j] = map[nextVertex][j];
					shortest_index[j] = nextVertex;
				}	
				if( shortest[j] < minDis )
				{
					minDis = shortest[j];
					nextVertex_temp = j;
					beginVertex = shortest_index[j];
				}
			}			
		}
		nextVertex = nextVertex_temp;
		vertex[i][1] = beginVertex;
		vertex[i][2] = nextVertex;
		visited[nextVertex] = true;
	}

	nextVertex = 0;
	for(int k = 0; k < NUM - 1; k++ )
	{
		cout << setw(5) << vertex[k][1] + 1 << setw(5) << vertex[k][2] + 1 << endl;
		//cout << setw(5) << vertex[nextVertex][1] + 1 << setw(5) << vertex[nextVertex][2] + 1 << endl;
		//nextVertex = vertex[nextVertex][2];
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值