原题:1329
题意:给出一棵n个节点的树,问m对节点的从属关系
解法:因为n较大,若对于每一个子问题都进行一次搜索并定会超时。其实只要进行一次dfs,记录每一个节点出现的初始时间和结束时间,这样就可以保证每一个节点出现的时间必定比其下方的节点出现时间早,结束时间晚。~~(这种方法亦可以求最近公共祖先)
代码实现我应用的是模拟指针…
#include <iostream>
using namespace std;
int a[100000], next[100000], n, last[50000] = {0}, tot = 0, sum = 0;
int f[50100][3] = {0};
void insert(int x, int y) {
a[tot] = y;
next[tot] = last[x];
last[x] = tot;
tot++;
}
void dfs(int t) {
sum++;
if (f[t][1] == 0) f[t][1] = sum;
f[t][2] = sum;
int k = last[t];
while (k != 0) {
if (f[a[k]][1] != 0) {
k = next[k];
continue;
}
dfs(a[k]);
sum++;
f[t][2] = sum;
k = next[k];
}
}
int main() {
cin >> n;
int s;
for (int i = 1; i <= n; i++) {
int x, y;
cin >> x >> y;
if (x == -1) s = y;
else if (y == -1) s = x;
else {
insert(x, y);
insert(y, x);
}
}
dfs(s);
int m;
cin >> m;
for (int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
if (f[x][1] < f[y][1] && f[x][2] > f[y][2]) cout << 1 << endl;
else if (f[y][1] < f[x][1] && f[y][2] > f[x][2]) cout << 2 << endl;
else cout << 0 << endl;
}
}