#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;
}
Prim算法
最新推荐文章于 2024-09-04 16:21:12 发布