题解
【基础】寻找祖先
1 条题解
-
0
#include <iostream> #include <cstring> using namespace std; const int MAX_PEOPLE = 10000; // 最大人数(根据题目规模设定) struct Person { char name[20]; // 人名 char father[20]; // 父亲的名字(空字符串表示无父亲) } people[MAX_PEOPLE]; int count = 0; // 已存储的人数 // 查找名字在数组中的索引,没找到返回-1 int findIndex(const char* name) { for (int i = 0; i < count; i++) { if (strcmp(people[i].name, name) == 0) { return i; } } return -1; } // 递归查找最早祖先 const char* findAncestor(const char* name) { int idx = findIndex(name); if (idx == -1 || strcmp(people[idx].father, "") == 0) { return name; // 没找到父亲,自己就是祖先 } return findAncestor(people[idx].father); // 查找父亲的祖先 } int main() { char line[50]; char currentFather[20] = ""; // 当前处理的父亲名字 while (cin >> line) { if (line[0] == '$') { break; // 结束标志 } if (line[0] == '#') { // 提取父亲名字(去掉开头的'#') strcpy(currentFather, line + 1); // 检查父亲是否已在数组中,不在则添加 if (findIndex(currentFather) == -1) { strcpy(people[count].name, currentFather); strcpy(people[count].father, ""); // 父亲初始无父 count++; } } else if (line[0] == '+') { // 提取儿子名字(去掉开头的'+') char son[20]; strcpy(son, line + 1); // 检查儿子是否已在数组中,不在则添加 int sonIdx = findIndex(son); if (sonIdx == -1) { sonIdx = count; strcpy(people[count].name, son); count++; } // 记录儿子的父亲 strcpy(people[sonIdx].father, currentFather); } else if (line[0] == '?') { // 提取查询的名字(去掉开头的'?') char queryName[20]; strcpy(queryName, line + 1); // 查找并输出最早祖先 const char* ancestor = findAncestor(queryName); cout << queryName << " " << ancestor << endl; } } return 0; }
- 1