zoukankan      html  css  js  c++  java
  • 洛谷——P2814 家谱

    P2814 家谱

    题目背景

    现代的人对于本家族血统越来越感兴趣。

    题目描述

    给出充足的父子关系,请你编写程序找到某个人的最早的祖先。

    输入输出格式

    输入格式:

    输入由多行组成,首先是一系列有关父子关系的描述,其中每一组父子关系中父亲只有一行,儿子可能有若干行,用#name的形式描写一组父子关系中的父亲的名字,用+name的形式描写一组父子关系中的儿子的名字;接下来用?name的形式表示要求该人的最早的祖先;最后用单独的一个$表示文件结束。

    输出格式:

    按照输入文件的要求顺序,求出每一个要找祖先的人的祖先,格式:本人的名字+一个空格+祖先的名字+回车。

    输入输出样例

    输入样例#1: 复制
    #George
    +Rodney
    #Arthur
    +Gareth
    +Walter
    #Gareth
    +Edward
    ?Edward
    ?Walter
    ?Rodney
    ?Arthur
    $
    输出样例#1: 复制
    Edward Arthur
    Walter Arthur
    Rodney George
    Arthur Arthur

    说明

    规定每个人的名字都有且只有6个字符,而且首字母大写,且没有任意两个人的名字相同。最多可能有1000组父子关系,总人数最多可能达到50000人,家谱中的记载不超过30代。

    解题报告:

    并查集的操作+string的操作

    #include<iostream>
    #include<map>
    #include<cstring>
    
    #define N 50010
    using namespace std;
    
    string s;
    map<string,int>M;
    string S[N];
    int tot,f,fa[N];
    int find(int x){
        return fa[x]=fa[x]==x?x:find(fa[x]);
    }
    int main()
    {
        for(int i=1;i<=N;i++) fa[i]=i;
        while(cin>>s){
            if(s.find('#')!=string::npos){
                s.erase(0,1);
                if(!M[s]) M[s]=++tot,S[tot]=s,f=tot;
                else f=M[s];
            }else if(s.find('+')!=string::npos){
                s.erase(0,1);
                if(!M[s]) M[s]=++tot,S[tot]=s,fa[tot]=find(f);
                else fa[M[s]]=find(f);
            }else if(s.find('?')!=string::npos){
                s.erase(0,1);
                cout<<s<<" "<<S[find(M[s])]<<"
    ";
            }else if(s.find('$')!=string::npos) break;
        }
        return 0;
    }
  • 相关阅读:
    21.Merge Two Sorted Lists 、23. Merge k Sorted Lists
    34. Find First and Last Position of Element in Sorted Array
    leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、301. Remove Invalid Parentheses
    31. Next Permutation
    17. Letter Combinations of a Phone Number
    android 常见分辨率(mdpi、hdpi 、xhdpi、xxhdpi )及屏幕适配注意事项
    oc 异常处理
    oc 类型判断
    oc Delegate
    oc 协议
  • 原文地址:https://www.cnblogs.com/song-/p/9545237.html
Copyright © 2011-2022 走看看