连通问题 1863(通用版) (2011-3-6 09:41)

//算法相当好用,碰到题目转换一下就可以套用了,非常速度!

//基于此题早上两道AC率30%的题目就用了30分钟,相当happy~

#include<stdio.h>
#define inf 0x7FFFFFFF
#define M 101
int
 map[M][M];
int
 link[M];
int  
kz[M];
int
 main()
{

    int
 sum,count,n,m,i,j,a,b,c,min;
    while
(
scanf("%d%d",&m,&n)!=EOF && m){
        for
(
i=0;i<M;i++){
            for
(
j=0;j<M;j++){
                map[i][j]=inf;
            }

            kz[i]=1;
        }

        for
(
i=1;i<=m;i++){
            scanf("%d%d%d",&a,&b,&c);
            map[a][b]=map[b][a]=c;
            if
(
i==1){
                link[0]=a;
                kz[a]=0;
            }
        }

        count=1;
        sum=0;
        a=1;
        while
(
count<n && a<=m){
            min=inf;
            for
(
i=0;i<count;i++){
                    for
(
j=1;j<=n;j++){
                        if
(
kz[j] && map[link[i]][j]<min){
                            link[count]=j;    
                            min=map[link[i]][j];
                        }
                        }    
             }

             if
(
 min!=inf){
                  sum+=min;
                   kz[link[count]]=0;
                 count++;
             }

             a++;
            }

        if
(
count==n){
            printf("%d\n",sum);
        }
else{

            printf("?\n");
        }
        
    }

return
 0;
}

你可能感兴趣的:(c,算法)