Prime算法

#include<stdio.h>
#include<string.h>
#define max 99999

int map[101][101],visit[101],lowcost[101];
int temp,n;

int prime()
{
    int i,j,k,sum=0;
    memset(visit,0,sizeof(visit));
    visit[1] = 1;
    for(i = 1; i <= n; i++)
        lowcost[i] = map[1][i];    
    for(i = 1; i <= n; i++)
    {
        temp = max;
        for(j = 1; j <= n; j++)
        {
            if(!visit[j] && lowcost[j] < temp)
            {
                k=j;
                temp = lowcost[k];
            }
        }
        if(temp == max)
            break;
        sum += temp;
        visit[k]=1;    
        for(j = 1; j <= n; j++)
            if(!visit[j] && lowcost[j] > map[k][j])
                lowcost[j]=map[k][j];
    }
    return sum;
}

int main()
{
    int i,m,a,b,cost,min;
    while(scanf("%d",&n)==1 && n)
    {
        m = n * (n-1) / 2;
        temp = max;
        memset(map,max,sizeof(map));
        for(i = 1; i <= m; i++)
        {
            scanf("%d %d %d",&a,&b,&cost);
            if(cost<temp)
                map[a][b] = map[b][a] = cost;
        }
        min = prime();
        printf("%d\n",min);
    }
    return 0;
}

 

posted @ 2012-08-04 12:36  Robot_Asia  阅读(945)  评论(0编辑  收藏  举报