POJ1258 Agri-Net(简单的prim最小生成树)
一题Prim最小生成树,没有任何陷阱。
#include <iostream>
using namespace std;
const int MAX_SIZE = 102;
long farm[MAX_SIZE][MAX_SIZE];//the farm connection
long closeEdge[MAX_SIZE];//辅助数组
int n;//the number of farms
void createFarm()
{
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
cin>>farm[i][j];
}
long prim()
{
long min,sum = 0;//sum stand for the total length
int i,j,k;
createFarm();
for(i = 0; i < n; i++)
closeEdge[i] = farm[0][i];//初始化辅助数组
for(i = 1; i < n; i++)
{
j = 0;
while(!closeEdge[j])j++;//寻找第一个未归入的点
min = closeEdge[j];k = j;
//开始寻找下一节点
for(j++; j < n; j++)
if(closeEdge[j] && min > closeEdge[j])
{
min = closeEdge[j];
k = j;
}
sum += closeEdge[k];
closeEdge[k] = 0;
for(j = 0; j < n; j++)//新顶点入集并重新选择最小边
if(farm[k][j] && farm[k][j] < closeEdge[j])
closeEdge[j] = farm[k][j];
}
return sum;
}
int main()
{
while(cin>>n)
cout<<prim()<<endl;
return 0;
}
using namespace std;
const int MAX_SIZE = 102;
long farm[MAX_SIZE][MAX_SIZE];//the farm connection
long closeEdge[MAX_SIZE];//辅助数组
int n;//the number of farms
void createFarm()
{
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
cin>>farm[i][j];
}
long prim()
{
long min,sum = 0;//sum stand for the total length
int i,j,k;
createFarm();
for(i = 0; i < n; i++)
closeEdge[i] = farm[0][i];//初始化辅助数组
for(i = 1; i < n; i++)
{
j = 0;
while(!closeEdge[j])j++;//寻找第一个未归入的点
min = closeEdge[j];k = j;
//开始寻找下一节点
for(j++; j < n; j++)
if(closeEdge[j] && min > closeEdge[j])
{
min = closeEdge[j];
k = j;
}
sum += closeEdge[k];
closeEdge[k] = 0;
for(j = 0; j < n; j++)//新顶点入集并重新选择最小边
if(farm[k][j] && farm[k][j] < closeEdge[j])
closeEdge[j] = farm[k][j];
}
return sum;
}
int main()
{
while(cin>>n)
cout<<prim()<<endl;
return 0;
}