题解 | #Jungle Roads#

Jungle Roads

https://www.nowcoder.com/practice/75c19b92d6b942f08989b335afbc73c3

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
using namespace std;
const int maxn=30;
int father[maxn];
int height[maxn];
bool isCpt(char x){
    if(x>='A' && x<='Z') return true;
    else return false;
}
struct edge{
    int from;
    int to;
    int length;
    edge(char x,char y,int c){
        from=x-'A';
        to=y-'A';
        length=c;
    }
    bool operator< (edge b) const{
        return length>b.length;
    }
};
priority_queue<edge> q;
void init(){
    for(int i=0;i<maxn;i++){
        father[i]=i;
        height[i]=0;
    }
    while(!q.empty()) q.pop();
}
int findf(int x){
    if(x!=father[x]) father[x]=findf(father[x]);
    return father[x];
}
void Union(int x,int y){
    x=findf(x);
    y=findf(y);
    if(x!=y){
        if(height[x]>height[y]) father[y]=x;
        else if(height[x]<height[y]) father[x]=y;
        else{
            father[y]=x;
            height[x]++;
        }
    }
}
int numberin(string x,int& i){
    int r=0;
    while(x[i]!=' '&& i<x.length()){
        r=r*10+x[i]-'0';
        i++;
    }
    return r;
}

int main() {
    int n;
    while(cin>>n && n!=0){
        init();
        getchar();
        while(n>1){
            queue<char> tc;
            queue<int> ti;
            string x;
            getline(cin, x);
            char from=x[0];
            for(int i=1;i<x.length();i++){
                if(x[i]==' ') continue;
                else if(isCpt(x[i])) {
                    tc.push(x[i]);
                }
                else ti.push(numberin(x,i));
            }
            ti.pop();
            while(!tc.empty()){
                q.push(edge(from,tc.front(),ti.front()));
                tc.pop();
                ti.pop();
            }
            n--;
        }
        int cost=0;
        while(!q.empty()){
            edge e=q.top();
            q.pop();
            if(findf(e.from)==findf(e.to)) continue;
            else{
                Union(e.from,e.to);
                cost+=e.length;
            }
        }
        cout<<cost<<endl;

    }
}

全部评论

相关推荐

若怜君欢:驾驶证去掉吧,PPT啥的也去掉,本硕课程去掉,导师和研究方向去掉;加入本硕排名(好才写);技能栏加入你会的那些控制算法和滤波算法,这个比你会啥啥啥软件更有用;获奖写上去,奖学金啊,有没有专利啊之类的 电机和硬件这一块,属于传统制造业,制造业实习并不多。多投一些攒攒经验,有实习最好,没有也不需要焦虑(制造业实习其实除了转正,没多大用处) 最后,划重点,等秋招开始后,把你所有社交软件都发一份简历上去,并经常更新,找人内推你!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务