//最小生成树之krustal算法
#include <iostream>
#include <stdio.h>
#include <queue>
using namespace std;
#define MAX_LINE 7
char tree[MAX_LINE][MAX_LINE]
={
{-1, 7, -1, 5, -1, -1, -1},
{7, -1, 8, 9, 7, -1, -1},
{-1, 8, -1, -1, 5, -1, -1},
{5, 9, -1, -1, 15, 6, -1},
{-1, 7, 5, 15, -1, 8, 9},
{-1,-1, -1, 6, 8,-1, 11},
{-1,-1, -1, -1, 9,11, -1}
};
typedef struct line
{
char row;
char col;
char value;
friend bool operator< (line n1, line n2)
{
return n1.value > n2.value;
}
} Line;
Line lines[MAX_LINE*MAX_LINE];
char father[MAX_LINE];//store father id
priority_queue<Line> qLines;
char linesIndex = 0;
void krustal();
void init(){
char i,j;
Line tmpLine;
for( i = 0;i<MAX_LINE;i++)
{
//Init father
father[i] = i;
for(j = i;j<MAX_LINE;j++)
{
if(tree[i][j] == -1)
continue;
tmpLine.row = i;
tmpLine.col = j;
tmpLine.value = tree[i][j];
qLines.push(tmpLine);
}
}
}
char findFather(char son){
if(father[son] == son)
return son;
return father[son] = findFather(father[son]);
}
int main(){
init();
cout<<"krustal算法最小生成树"<<endl;
krustal();
getchar();
return 0;
}
void krustal(){
Line tmpLine;
char row,col,value;
char fatherRow,fatherCol;
char i,sum = 0;
while(linesIndex<MAX_LINE-1)
{
tmpLine = qLines.top();
qLines.pop();
row = tmpLine.row;
col = tmpLine.col;
value = tmpLine.value;
fatherRow = findFather(row);
fatherCol = findFather(col);
if(fatherRow == fatherCol)//构成环
continue;
//加入到lines
lines[linesIndex++] = tmpLine;
//更新集合信息
char tmpCol = col;
char tmptmp;
while (tmpCol!=father[tmpCol])
{
tmptmp = father[tmpCol];
father[tmpCol] = fatherRow;
tmpCol = tmptmp;
}
father[tmpCol] = fatherRow;
}
//打印结果
for(i = 0;i<linesIndex;i++){
printf("<%d,%d>\n",lines[i].row,lines[i].col);
sum+=lines[i].value;
}
printf("total path is %d\n",sum);
}