这道题目是很简单的最小生成树的典型例题 。通过这个题目学习Prim算法。
#include <iostream>
using namespace std;
int map[102][102], visited[102], lowercost[102], m, n;
#define MAX 0x7fffffff
void init()
{
int i, j, a, b, c;
for(i=0; i<n; i++)
for(j=0; j<n; j++)
map[i][j] =MAX;
for(i=0; i<m; i++)
{
cin>>a>>b>>c;
map[a][b] = map[b][a]=c;
}
memset(visited,0,sizeof(visited));
memset(lowercost,0,sizeof(lowercost));
}
int Prim(int v)
{
int i, j, k, min=0, tmp_min;
visited[v] = 1;
for(i=1; i<=n; i++)
lowercost[i] = map[v][i];
for(i=2; i<=n; i++)
{
tmp_min = MAX;
for(j=1; j<=n; j++)
if(tmp_min>lowercost[j]&&visited[j]==0)
{
v = j;
tmp_min = lowercost[j];
}
visited[v] = 1;
min+=tmp_min;
for(j=1; j<=n; j++)
if(lowercost[j]>map[v][j]&&visited[j]==0)
lowercost[j] = map[v][j];
}
return min;
}
void main()
{
int i, j;
while(cin>>n&&n)
{
m = (n*(n-1))/2;
init();
int min = Prim(1);
cout<<min<<endl;
}
}