最小生成树算法,Prim,错误了n次,在于每次输入数据的时候,没有初始化数据,牢记教训!
#include<iostream>
using namespace std;
int vertex = 0;
int iMap[110][110];
int lowcost[110];
bool flag[110];
int sum = 0;
int findMin();
int main()
{
//freopen("input.txt","r",stdin);
while(scanf("%d",&vertex) != EOF)
{
sum = 0;
memset((void*)lowcost, 0, sizeof(lowcost));
memset((void*)flag, 0, sizeof(flag));
memset((void*)iMap,0,sizeof(iMap));
for (int i = 0; i < vertex; ++i)
for (int j = 0; j < vertex; ++j)
{
scanf("%d",&iMap[i][j]);
}
flag[0] = true;
for (int i = 1; i < vertex; ++i)
{
lowcost[i] = iMap[0][i];
}
for (int i = 1; i < vertex; ++i)
{
int cur_min = findMin();
flag[cur_min] = true;
sum += lowcost[cur_min];
for (int j = 1; j < vertex; ++j)
{
if (!flag[j] && iMap[cur_min][j] < lowcost[j])
{
lowcost[j] = iMap[cur_min][j];
}
}
}
printf("%d/n",sum);
}
return 0;
}
int findMin()
{
int j = -1;
int tmp_min = 100000000;
for (int i = 1; i < vertex; ++i)
{
if (lowcost[i] < tmp_min && !flag[i])
{
tmp_min = lowcost[i];
j = i;
}
}
return j;
}