题解 | #找出直系亲属#
找出直系亲属
https://www.nowcoder.com/practice/2c958d09d29f46798696f15ae7c9703b
利用并查集加各种判断,整了一个多小时 #include<iostream> using namespace std; #define N 30 int father[N]; int num; //初始化并查集 void Init() { for (int i = 1; i <= N; i++) { father[i] = i; } } void Findrelation(int x,int y) { if (father[y] != x) { Findrelation(x,father[y]); num++; } return; } void Union(int x, int y) { if (x != y) { father[y] = x; } } //非路径压缩版本 int Find(int x,int y) { int a = x, b = y; while (father[x] != x) { x = father[x]; if (x == y) return 1; } while (father[b] != b) { b = father[b]; if (a == b) return 2; } return 3; // 1表示x为y的祖先 ,2表示y为x祖先,3表示没有关系 } int main() { //用1到26表示A到Z int n, m; while (cin >> n >> m) { Init(); for (int i = 0; i < n; i++) { char a, b, c; cin >> a >> b >> c; Union(a - 'A' + 1, b - 'A' + 1); Union(a - 'A' + 1, c - 'A' + 1); } for (int i = 0; i < m; i++) { char a, b; cin >> a >> b; num = 0; if (Find(a-'A'+1,b-'A'+1) == 3) { cout << '-' << endl; continue; } if (Find(a - 'A' + 1, b - 'A' + 1) == 1) { Findrelation(b - 'A' + 1, a - 'A' + 1); if (num == 0) cout << "parent" << endl; else if (num > 0) { while ((num--) > 1) { cout << "great-"; } cout << "grandparent" << endl; } } else { Findrelation(a - 'A' + 1, b - 'A' + 1); if (num == 0) cout << "child" << endl; else if (num > 0) { while ((num--) > 1) { cout << "great-"; } cout << "grandchild" << endl; } } } } }