Jungle Roads
Description
The Head Elder of the tropical island of Lagrishan has a problem. A burst of foreign aid money was spent on extra roads between villages some years ago. But the jungle overtakes roads relentlessly, so the large road network is too expensive to maintain. The Council of Elders must choose to stop maintaining some roads. The map above on the left shows all the roads in use now and the cost in aacms per month to maintain them. Of course there needs to be some way to get between all the villages on maintained roads, even if the route is not as short as before. The Chief Elder would like to tell the Council of Elders what would be the smallest amount they could spend in aacms per month to maintain roads that would connect all the villages. The villages are labeled A through I in the maps above. The map on the right shows the roads that could be maintained most cheaply, for 216 aacms per month. Your task is to write a program that will solve such problems.
Input
Output
Sample Input
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
Sample Output
216 30
题意:给定n个点,给出各点之间的连通情况,和各点之间的距离。求一条路径能够连通所有的点的最小距离
题解:最小生成树prim算法
注意:用%c读入re,%s即ac
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int p[30][30];
int visit[30],cnt[30];
int n,sum;
void prim()
{
int i,temp=n,k;
memset(visit,0,sizeof(visit));
visit[1]=1;
for(i=1;i<=n;i++) cnt[i]=p[1][i];
while(temp--)
{
int inf=10000000;
for(i=1;i<=n;i++)
{
if(visit[i]==0&&cnt[i]<inf)
{
k=i;
inf=cnt[i];
}
}
if(inf==10000000) break;
sum+=inf;
visit[k]=1;
for(i=1;i<=n;i++)
{
if(visit[i]==0&&p[k][i]<cnt[i])
{
cnt[i]=p[k][i];
}
}
}
}
int main()
{
int i,j,px,a;
char mc[2],mm[2];
while(scanf("%d",&n),n)
{
getchar();
memset(cnt,0,sizeof(cnt));
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
p[i][j]=10000000;
}
}
for(j=1;j<n;j++)
{
scanf("%s %d",&mc,&px);
for(i=0;i<px;i++)
{
scanf(" %s %d",&mm,&a);
p[mc[0]-'A'+1][mm[0]-'A'+1]=a;
p[mm[0]-'A'+1][mc[0]-'A'+1]=a;
}
getchar();
}
sum=0;
prim();
printf("%d\n",sum);
}
}