//poj1258 prime算法+距离表
#include <iostream>
#include <algorithm>
#define inf 100005
using namespace std;
int dist[105];
int mark[105];
int weight[105][105];
int sum;
int prime(int n)
{
dist[0] = 0;
mark[0] = true;
for(int i = 1; i < n; i++)
dist[i] = weight[0][i];
for(int i = 1; i < n; i++)
{
int min1 = inf;
int minIndex = -1;
for(int j = 1; j < n; j++)
{
if(!mark[j] && dist[j] < min1)
{
min1 = dist[j];
minIndex = j;
}
}
sum += min1;
dist[minIndex] = 0;
mark[minIndex] = true;
for(int j = 1; j < n; j++)
dist[j] = (weight[minIndex][j] < dist[j])?weight[minIndex][j]:dist[j];
}
return sum;
}
int main()
{
int n;
cin>>n;
while(n && !cin.eof())
{
memset(dist, 0, sizeof(dist));
memset(mark, 0, sizeof(mark));
memset(weight, 0, sizeof(weight));
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
int w;
cin>>w;
weight[i][j] = w;
}
}
sum = 0;
cout<<prime(n)<<endl;
cin>>n;
}
return 0;
}
poj1258 prime算法+距离表 还是47MS,搞不懂,过了就好。
最新推荐文章于 2019-11-30 18:01:53 发布