PTA家譜處理c++版——山東科技大學

2020-10-18 15:00:30

在這裡插入圖片描述
在這裡插入圖片描述
輸入:

6 5
John
  Robert
    Frank
    Andrew
  Nancy
    David
Robert is a child of John
Robert is an ancestor of Andrew
Robert is a sibling of Nancy
Nancy is the parent of Frank
John is a descendant of Andrew

輸出:

True
True
True
False
False
//創作不易
//第一次寫,無註釋。
//運用了一點並查集的思想
#include<bits/stdc++.h>
using namespace std;
struct People
{
    string name;
    int write;
    int parent;
} people[105];
map<string,int>mp;
int n,m;
void init()
{
    cin>>n>>m;
    string ss,s;
    int len,x=0;
    cin>>people[0].name;
    people[0].parent=-1;
    people[0].write=0;
    getchar();
    for(int i=1; i<n; i++)
    {
        x=0;
        getline(cin,ss);
        len=ss.length();
        for(int j=0; j<len; j++)
        {
            if(ss[j]!=' ')
                break;
            x++;
        }
        people[i].name=ss.substr(x,len-x);
        people[i].write=x;
        mp[people[i].name]=i;
        for(int j=i-1; j>=0; j--)
        {
            if(people[i].write==people[j].write)
            {
                people[i].parent=people[j].parent;
                break;
            }
            if(people[i].write==people[j].write+2)
            {
                people[i].parent=j;
                break;
            }
        }
    }
}
bool find(int a,int b)
{
    if(people[a].parent==b)
        return true;
    return a==0?false:find(people[a].parent,b);
}
bool judge(string s1,string relation,string s2)
{
    switch (relation[0])
    {
    case 'c':
    {
        if(people[mp[s1]].parent==mp[s2])
            return true;
        break;
    }
    case 'p':
    {
        if(people[mp[s2]].parent==mp[s1])
            return true;
        break;
    }
    case 's':
    {
        if(people[mp[s1]].parent==people[mp[s2]].parent)
            return true;
        break;
    }
    case 'a':
    {
        if(find(mp[s2],mp[s1]))
            return true;
        break;
    }
    case 'd':
    {
        if(find(mp[s1],mp[s2]))
            return true;
        break;
    }
    }
    return false;
}
void solve()
{
    int x=0;
    string s,s1,s2,r;
    for(int i=0; i<m; i++)
    {
        x=0;
        getline(cin,s);
        stringstream ss;
        ss<<s;
        while(ss>>s)
        {
            x++;
            if(x==1)
                s1=s;
            if(x==6)
                s2=s;
            if(x==4)
                r=s;
        }
        if(judge(s1,r,s2))
            cout<<"True"<<endl;
        else
            cout<<"False"<<endl;
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    init();
    solve();
    return 0;
}


每天進步一點點,十天進步十點點,加油!
更多PTA作業程式碼都在我的部落格中

ps:答案僅供參考,請勿抄襲