最小生成树 (prim)

void prim(int n)
{
    int i,j,pos,min,sum=0;
    for(i = 1;i <= n;i++)
    {
        dist[i] = map[1][i];
    }
    book[1] = 1;
    for(i = 2;i <= n;i++)
    {
        pos = i;
        min = max;
        for(j = 1;j <= n;j++)
        {
            if(book[j] == 0&&dist[j] < min)
            {
                min = dist[j];
                pos = j;
            }
        }
        sum += dist[pos];
        book[pos] = 1;
        for(j= 1;j <= n;j++)
        {
            if(book[j] == 0&&dist[j] > map[pos][j])
            {
                dist[j] = map[pos][j];
            }
        }
    }
    printf("%d\n",sum);
}
void prim()
{
    int s = 1,p = 0;
    double dis[550];
    int vis[550];
    int sum = 1;
    int x;
    double Min;
    memset(vis,0,sizeof(vis));
    vis[s] = 1;
    for(int i = 1;i<=n;i++) dis[i] = 123456789;
    while(1)
    {
        if(sum == n) return ;
        Min = 123456789;
        for(int i=2;i<=n;i++)
        {
            if(!vis[i]&&dis[i] > dist[s][i])
                dis[i] = dist[s][i];
            if(!vis[i]&&dis[i] < Min)
            {
                Min = dis[i];
                x = i;
            }
        }
        s = x;
        vis[s] = 1;
        ans[p++] = Min;
        sum++;
    }
}

 

 

你可能感兴趣的:(#,模板)