PTA家谱处理c++版——山东科技大学

10/19 08:21
阅读数 21

在这里插入图片描述
在这里插入图片描述
输入:

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:答案仅供参考,请勿抄袭

展开阅读全文
c++
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部