0
点赞
收藏
分享

微信扫一扫

PTA 7-2 家谱处理——模拟

_阿瑶 2022-08-17 阅读 75


人类学研究对于家族很感兴趣,于是研究人员搜集了一些家族的家谱进行研究。实验中,使用计算机处理家谱。为了实现这个目的,研究人员将家谱转换为文本文件。下面为家谱文本文件的实例:

John
Robert
Frank
Andrew
Nancy
David

​John​​这个家族最早的祖先,他有两个子女​​Robert​​和​​Nancy​​,​​Robert​​有两个子女​​Frank​​和​​Andrew​​,​​Nancy​​只有一个子女​​David​​。

在实验中,研究人员还收集了家庭文件,并提取了家谱中有关两个人关系的陈述语句。下面为家谱中关系的陈述语句实例:

John is the parent of Robert
Robert is a sibling of Nancy
David is a descendant of Robert

研究人员需要判断每个陈述语句是真还是假,请编写程序帮助研究人员判断。

输入格式:

输入首先给出2个正整数N2)和M),其中N为家谱中名字的数量,M为家谱中陈述语句的数量,输入的每行不超过70个字符。

名字的字符串由不超过10个英文字母组成。在家谱中的第一行给出的名字前没有缩进空格。家谱中的其他名字至少缩进2个空格,即他们是家谱中最早祖先(第一行给出的名字)的后代,且如果家谱中一个名字前缩进k个空格,则下一行中名字至多缩进k+2个空格。

​X​​和​​Y​​为家谱中的不同名字:

X is a child of Y
X is the parent of Y
X is a sibling of Y
X is a descendant of Y
X is an ancestor of Y

输出格式:

​True​​,如果陈述为真,或​​False​​,如果陈述为假。

思路:各种瞎搞

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
using namespace std;
const int maxn = 1000;

char str[maxn];
string s, op;
int n, m, zerocnt[maxn], head[maxn], par[maxn];
vector<int> son[maxn];
map<string, int> key;

bool dfs1(int x, int y) {
if (x == y) return true;
for (unsigned int i = 0; i < son[x].size(); i++) {
if (dfs1(son[x][i], y)) return true;
}
return false;
}

bool dfs2(int x, int y) {
if (x == 0) return false;
if (x == y) return true;
if (dfs2(par[x], y)) return true;
return false;
}

void solve(int x) {
gets(str);
int i = 0;
string s;
for (; str[i] == ' '; i++) zerocnt[x]++;
for (; str[i]; i++) s.push_back(str[i]);
key[s] = x;
head[zerocnt[x]] = x;
}

int main() {
scanf("%d %d", &n, &m); getchar();
memset(zerocnt, 0, sizeof(zerocnt));
memset(head, 0, sizeof(head));
memset(par, 0, sizeof(par));
for (int i = 1; i <= n; i++) son[i].clear();
solve(1);
for (int i = 2; i <= n; i++) {
solve(i);
int u = head[zerocnt[i] - 2], v = i;
par[v] = u; son[u].push_back(v);
}
for (int i = 1; i <= m; i++) {
cin >> s; int u = key[s];
cin >> s >> s >> op >> s;
cin >> s; int v = key[s];
bool ok;
if (op[0] == 'c') {
ok = false;
for (unsigned int j = 0; j < son[v].size(); j++) if (son[v][j] == u) { ok = true; break; }
}
else if (op[0] == 'p') {
ok = (par[v] == u);
}
else if (op[0] == 'd') {
ok = dfs1(v, u);
}
else if (op[0] == 'a') {
ok = dfs2(v, u);
}
else {
if (par[u] == par[v] && zerocnt[u] == zerocnt[v]) ok = true;
else ok = false;
}
if (ok) printf("True\n");
else printf("False\n");
}
return 0;
}



举报

相关推荐

0 条评论