|
发表于 2003-9-3 05:26:18
|
显示全部楼层
// 最小生成树
// Kruskal.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream infile("Kruskal.in");
ofstream outfile("Kruskal.out");
struct Node
{
int x;
int y;
int z;
};
const int ub = 15;
const int inf = 1000000;
int n;
int nEdge;
int original[ub][ub];
int e[ub];
Node ee[ub];
int s[ub];
int r[ub];
void initialization();
void readData();
void process();
void output();
void initialization()
{
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
original[j] = inf;
}
for(int j=0;j<nEdge;j++)
{
r[j] = 0;
s[j] = j;
e[j] = j;
}
}
void readData()
{
infile>>n>>nEdge;
initialization();
for(int i=0;i<nEdge;i++)
{
int x,y,z;
infile>>x>>y>>z;
original[x-1][y-1] = z;
original[y-1][x-1] = z;
ee.x = x-1;
ee.y = y-1;
ee.z = z;
}
process();
output();
}
bool cmp(int a,int b)
{
return (ee[e[a]].z <= ee[e].z);
}
bool cmp2(Node a,Node b)
{
return a.z < b.z;
}
void process()
{
// minimum cost spanning tree... Kruskal...
//sort(e,e+nEdge,cmp);
sort(ee,ee+nEdge,cmp2);
// get the lowest-weight edge...
int f_x = ee[0].x;
int f_y = ee[0].y;
// merge...
s[f_x] = s[f_y];
r[0] = ee[0].z;
int curPos = 1;
for(int i=1;i<n-1;i++)
{
while(s[ee[curPos].x] == s[ee[curPos].y])
{
curPos++;
}
int curNo = s[ee[curPos].x];
for(int j=0;j<nEdge;j++)
{
if (s[j] == curNo)
s[j] = s[ee[curPos].y];
}
r = ee[curPos].z;
}
// end of MST...
}
void output()
{
for(int i=0;i<n-1;i++)
{
cout<<r<<' ';
}
cout<<endl;
}
int main(int argc, char* argv[])
{
readData();
return 0;
}
|
|