http://acm.pku.edu.cn/JudgeOnline/problem?id=1251
题意求连接每一个村庄的路程的总和最短,用Prime算法求最小生成树。
#include <cstdio>
#include <iostream>
using namespace std;
int number;
int length[26][26];
bool intree[26];
int dis[26];
void Read()
{
char a,c;
int i,j,b,d;
memset(length,999999,sizeof(length));
for(i = 0;i < number-1;i ++)
{
cin>>a;
scanf("%d",&b);//起始位置
for(j = 0;j < b;j ++)
{
cin>>c;
scanf("%d",&d);//终点位置
length[a-'A'][c-'A'] = length[c-'A'][a-'A'] = d;//读书路程数据
}
}
memset(intree,false,sizeof(intree));
memset(dis,999999,sizeof(dis));
intree[0] = true;
for(i = 0;i < number;i ++)
dis[i] = length[0][i];
}
void Prim()
{
int i,j,loc,min,total = 0;
for(i = 0;i < number-1;i ++)
{
min = 999999;
for(j = 0;j < number;j ++)
{
if(intree[j] == false && dis[j] < min)
{
min = dis[j];
loc = j;
}
}
total = total + min;//求路程总和
intree[loc] = true;
for(j = 0;j < number;j ++)
{
if(intree[j] == false)
{
if(length[loc][j] < dis[j])
dis[j] = length[loc][j];
}
}
}
printf("%d/n",total);
}
int main()
{
while(scanf("%d",&number),number)
{
Read();
Prim();
}
return 0 ;
}
/*
9 A 2 B 12 I 25 B 3 C 10 H 40 I 8 C 2 D 18 G 55 D 1 E 44 E 2 F 60 G 38 F 0 G 1 H 35 H 1 I 35 3 A 2 B 10 C 40 B 1 C 20 0
216 30
*/