传送门:点击打开链接
题意:一颗完全二叉树,表示辈分关系,节点从0开始。随便告诉你两个节点,问v节点是u节点的什么关系。
思路:顶级模拟题!感谢这道题目,我终于搞懂了各种头衔的含义。。
思路大概是先求出u和v到lca的距离,然后就利用这个距离去讨论。
刚开始可以写一部分出来,发现规律后就可以直接按规律来写了。
#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <bitset>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
#define fuck(x) cout << "[" << x << "]"
#define FIN freopen("input.txt", "r", stdin)
#define FOUT freopen("output.txt", "w+", stdout)
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int MX = 40000;
int vis[MX];
int u, v; char s[10];
int h1, h2;
void find_h(int id) {
int t = u;
while(t) {
vis[t] = id;
t /= 2;
}
t = v;
int lca;
while(t) {
if(vis[t] == id) {
lca = t;
break;
}
t /= 2;
}
h1 = h2 = 0;
for(t = u; t != lca; t /= 2) h1++;
for(t = v; t != lca; t /= 2) h2++;
}
string pre[] = {"", "grand", "great-grand", "great-great-grand"};
string num[] = {"", "1st", "2nd", "3rd"};
string last[] = {"", "once", "twice", "thrice"};
string DFS(int h1, int h2) {
if(h1 == 0 && h2 == 0) return "self";
if(h1 == 1 && h2 == 0) {
if(s[0] == 'M') return "father";
else return "mother";
}
if(h1 == 0 && h2 == 1) {
if(s[0] == 'M') return "son";
else return "daughter";
}
if(h1 == 1 && h2 == 1) {
if(s[0] == 'M') return "brother";
else return "sister";
}
if(h1 == 2 && h2 == 1) {
if(s[0] == 'M') return "uncle";
else return "aunt";
}
if(h1 == 1 && h2 == 2) {
if(s[0] == 'M') return "nephew";
else return "niece";
}
int d = abs(h1 - h2), Min = min(h1, h2);
if(Min >= 2) {
if(Min - 1 <= 3 && d <= 3) {
if(d == 0) return num[Min-1] + " cousin";
else return num[Min-1] + " cousin " + last[d] + " removed";
} else return "kin";
} else {
if(d - 1 > 3) return "kin";
else {
if(h1 > h2) return pre[d-1] + DFS(h1 - d + 1, h2);
if(h1 < h2) return pre[d-1] + DFS(h1, h2 - d + 1);
}
}
}
int main() {
int sz = 0; //FIN;
while(~scanf("%d%d%s", &u, &v, s), u >= 0) {
u++; v++;
find_h(++sz);
printf("%s\n", DFS(h1, h2).c_str());
}
return 0;
}