3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0
3 5Huge input, scanf is recommended.HintHint
多做几个,熟悉熟悉!!
AC代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#define INF 0x7f7f7f7f
using namespace std;
int map[105][105], vis[105], dis[105];
int n;
void prim()
{
for(int i=1; i<=n; i++)
dis[i] = map[1][i];
vis[1] = 1; dis[1] = 0;
int sum = 0, pos;
for(int i=1; i<n; i++)
{
int tmp = INF;
for(int j=1; j<=n; j++)
{
if(!vis[j] && dis[j] < tmp)
{
tmp = dis[j];
pos = j;
}
}
sum += tmp;
vis[pos] = 1;
for(int j=1; j<=n; j++)
if(!vis[j] && map[pos][j] < dis[j])
dis[j] = map[pos][j];
}
printf("%d\n", sum);
}
int main()
{
while(scanf("%d", &n) == 1 && n)
{
memset(vis, 0, sizeof(vis));
memset(map, 0x7f, sizeof(map));
memset(dis, 0x7f, sizeof(dis));
int m = n*(n-1)/2, x, y, z;
for(int i = 1; i<=m; i++)
{
scanf("%d %d %d", &x, &y, &z);
map[x][y] = map[y][x] = z;
}
prim();
}
return 0;
}
原文地址:http://blog.csdn.net/u014355480/article/details/42268945