POJ 1251: Jungle Roads (minimum spanning tree)

POJ 1251: Jungle Roads (minimum spanning tree)

Topic Link

This question seems to see it once it together, but because there is no topic is too long to do, in fact, a Figure that this is a minimum spanning tree problem, yesterday made a whim, the result is very silent, has been RE. . . . .

The gechar began to enter a space:

getchar();
scanf("%c",&ch);

POJ not know why that is, but not before, back into this

scanf(" %c",&ch);

A result, very silent ...

Of course, the topic is very simple, direct is a bare minimum spanning tree, Prim algorithm I use
Prim's algorithm embodied see this blog:

Minimum Spanning Tree concepts and constructs (Prim algorithm, Kruskal algorithm)

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#define INF 999999
using namespace std;
int n;
int mp[110][110];
int vis[110];
int cost[110];
int tree[110];
void init(){
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(j==i)
                mp[i][j]=0;
            else
                mp[i][j]=INF;
        }
    }
}
void Prim(){
    memset(vis,0,sizeof(vis));
    memset(cost,0,sizeof(cost));
    memset(tree,0,sizeof(tree));
    for(int i=2;i<=n;i++){
        cost[i]=mp[1][i];
        tree[i]=1;
    }
    tree[1]=-1;
    vis[1]=1;
    cost[1]=0;
    for(int i=1;i<=n;i++){
        int Min=INF+1;
        int pos;
        for(int j=1;j<=n;j++){
            if(vis[j]==0&&cost[j]<Min){
                Min=cost[j];
                pos=j;
            }
        }
        vis[pos]=1;
        for(int j=1;j<=n;j++){
            if(vis[j]==0&&mp[pos][j]<cost[j]){
                cost[j]=mp[pos][j];
                tree[j]=pos;
            }
        }
    }
}
int main(){
    while(~scanf("%d",&n)){
        if(n==0)
            break;
        init();
        char ch;
        int x,y;
        int m;
        int dis;
        for(int k=0;k<n-1;k++){
            scanf(" %c",&ch);
            x=ch-'A'+1;
            scanf("%d",&m);
            for(int i=0;i<m;i++){
                getchar();
                scanf(" %c %d",&ch,&dis);
                y=ch-'A'+1;
                if(mp[x][y]>dis){
                    mp[x][y]=mp[y][x]=dis;
                }
            }
        }
        Prim();
        int sum=0;
        for(int i=1;i<=n;i++){
            sum+=cost[i];
        }
        printf("%d\n",sum);
    }
    return 0;
}

Published 127 original articles · won praise 32 · views 10000 +

Guess you like

Origin blog.csdn.net/boliu147258/article/details/102500146