OpenJudge:丛林中的路(kruskal最小生成树)

题目描述

丛林中的路

解题思路

  • 邻接表输入
  • 经典最小生成树,MST模板题,和Hdu 1863.畅通工程 Kruskal模板一样
  • 注意在初始化代表元素的时候,是字符数组,需要int转char
  • 常用ASCII对应 A-65 a-97 0-48

代码

#include <iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
#define max 80
struct edge{
    char x,y;
    int w;
}paths[max];
char fa[max];
int cmp(edge a,edge b){
    return a.w<b.w;
}
void init(int n){//注意这里初始化的是char数组
    for(int i=0;i<n;i++){
        char a = 65+i;
        fa[a] = a;
    }
}
char find(char x){
    if(fa[x]==x)
        return x;
    else
        return fa[x]=find(fa[x]);
}
void _union(char x,char y){
    char xf = find(x);
    char yf = find(y);
    if(xf!=yf){
        fa[yf] = xf;
    }
}
int main() {
    int n;
    char a,b;
    int after,w;
    while(1){
        cin>>n;
        if(n==0) break;
        int m=0,ans = 0,count=0;
        for(int i=0;i<n-1;i++){
            cin>>a>>after;
            for(int j=0;j<after;j++){
                cin>>b>>w;
                paths[m].x = a;
                paths[m].y = b;
                paths[m++].w = w;
            }   
        }
        init(n);
        sort(paths,paths+m,cmp);
        for(int i=0;i<m;i++){
            char x=paths[i].x;
            char y=paths[i].y;
            if(find(x)!=find(y)){
                _union(x,y);
                count++;
                ans+=paths[i].w;
            }
        }
        if(count==n-1){
            cout<<ans<<endl;
        }else{
            cout<<"-1"<<count<<endl;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/armstrong_rose/article/details/80317107