如题:http://poj.org/problem?id=1258
最小生成树的基础练习
农民要建立互联网络,目的使村庄里所有的农民连上网,并且总费用最小。多组数据,每组数据给出一个n,然后给出n * n大小的无向图的邻接矩阵表示,值表示边权。要求输出最小生成树的权值和
#include<iostream>
using namespace std;
#define MAX 101
#define MAXCOST 0x7fffffff
int graph[MAX][MAX];
int prim(int g[MAX][MAX],int n)
{
int i,j;
int lowcost[MAX];
int visited[MAX];
int minid,sum=0,min;
memset(visited,0,sizeof(visited));
for(i=1;i<=n;i++)
{
lowcost[i]=graph[1][i];
}
visited[1]=1;
for(i=2;i<=n;i++)
{
min=MAXCOST;
minid=0;
for(j=1;j<=n;j++)
{
if(visited[j]==0&&lowcost[j]!=0&&lowcost[j]<min)
{
min=lowcost[j];
minid=j;
}
}
visited[minid]=1;
sum+=min;
for(j=1;j<=n;j++)
if(visited[j]==0&&lowcost[j]>graph[minid][j])
lowcost[j]=graph[minid][j];
}
return sum;
}
int main()
{
int i, j, n;
int cost;
while (scanf("%d", &n) != EOF)
{
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
graph[i][j] = MAXCOST;
}
}
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
scanf("%d", &graph[i][j]);
}
}
cost = prim(graph, n);
printf("%d\n", cost);
}
return 0;
}