#include <queue>
#include <set>
using namespace std;
#define N 10
int iW[N][N] = {0};
int iNum = 0;
#define MAX_WEIGHT 9999 // 正无穷大
queue<int> q; // 考察过的点的队列
set<int> s; // 没有考察过的点的集合
set<int>::iterator itSet = s.begin();
void Input() // 从文件中读
{
ifstream is("E:\\temp\\Daylogs\\201010\\01\\1.txt");
is >> iNum;
for (int i = 0; i < iNum; ++i)
{
for (int j = 0; j < iNum; ++j)
{
is >> iW[i][j];
if (iW[i][j] == 0)
{
iW[i][j] = (i==j)?0:MAX_WEIGHT;
}
}
}
}
void Output() // 打印出当前的iW矩阵,及Q队列
{
for (int i = 0; i < iNum; ++i)
{
for (int j = 0; j < iNum; ++j)
{
if (iW[i][j] == MAX_WEIGHT)
printf("%d\t", 0);
else
printf("%d\t", iW[i][j]);
}
printf("\n");
}
queue<int> qTmp(q);
while (!qTmp.empty())
{
int i = qTmp.front();
printf("%d, %d\n", i, iW[0][i]);
qTmp.pop();
}
}
int FindMinDist(int iStart) // 找与iStart点距离最近的点
{
int iMin = MAX_WEIGHT;
int iID = -1;
for (itSet = s.begin(); itSet != s.end(); ++itSet)
{
int i = *itSet;
if (iMin > iW[iStart][i])
{
iMin = iW[iStart][i];
iID = i;
}
}
return iID;
}
void UpdateWeight(int _iNext) // 更新权重
{
for (itSet = s.begin(); itSet != s.end(); ++itSet)
{
int i = *itSet;
int iNewDist = iW[0][_iNext] + iW[_iNext][i];
if (iNewDist < iW[0][i])
iW[0][i] = iNewDist;
}
}
void Proc()
{
q.push(0);
for (int i = 1; i < iNum; ++i)
s.insert(i);
while (true)
{
int iNext = FindMinDist(0);
if (iNext < 0)
return;
q.push(iNext);
s.erase(iNext);
UpdateWeight(iNext);
}
}
void CodeWrapper()
{
Input();
Output();
Proc();
printf("\n\nAfter Process ....\n");
Output();
}