3 3 1 2 1 1 3 2 2 3 4 1 3 2 3 2 0 100
3 ?
这几道与畅通工程有关的题目都很像
代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
#define INF 1 << 30
int map[1001][1001] ;
int dis[1001] ;
int used[1001] ;
void Prim(int M)
{
int i = 0 ,j = 0 ;
int c = 0 ;
int sum = 0 ;//用来记录最后所需要的花费
dis[1] = 0 ;
for( i = 1 ; i <= M ; i++)
{
int min = INF ;
for( j = 1 ; j <= M ; j++)
{
if(!used[j] && dis[j] < min)
{
min = dis[j] ;
c = j ;
}
}
used[c] = 1 ;
for(j = 1 ; j <= M ; j++)
{
if(!used[j] && dis[j] > map[c][j])
dis[j] = map[c][j] ;
}
}
for(i = 1 ; i <= M ; i++)
{
if(dis[i] == INF)
{
sum = INF ;
break ;
}
sum += dis[i] ;
}
if(sum != INF)
printf("%d\n",sum);
else
printf("?\n");
}
int main()
{
int N = 0 , M = 0;
while(~scanf("%d%d", &N , &M ))
{
if(N == 0)
break ;
int a = 0 , b = 0 , c = 0 ;
int i = 0 , j = 0 ;
for(i = 1 ; i <= M ; i++)
{
for(j = 1 ; j <= M ; j++)
map[i][j] = INF ;
dis[i] = INF ;
used[i] = 0 ;
}
for( i = 0 ; i < N ; i++)
{
scanf("%d%d%d" , &a , &b , &c );
//判断是否会有重边
if(map[a][b] > c)
map[a][b] = map[b][a] = c ;
}
Prim( M ) ;
}
return 0 ;
}
原文地址:http://blog.csdn.net/bluedream1219/article/details/37989611