SSL Week 2 Fri. JZOJ simulation game Group B T1 interrogation grandchild

Subject to the effect:

There is known a rooted tree of n nodes. There are m interrogation. Each interrogation x and y are numbers given pair of nodes, asking grandchild relationship between x and y.

Problem-solving ideas:

D F S DFS sequence O r   L C A or\ LCA
D F S DFS sequence, the first record of the node access time s t [ x ] st[x] , complete access time e d [ x ] ed[x]
if Y Y in x x within the sub-tree, then there must be s t [ x ] &lt; s t [ Y ]   &amp; &   e d [ Y ] < e d [ x ] st[x]&lt;st[y]\ \&amp;\&amp;\ ed[y]&lt;ed[x]

A c c e p t e d   c O d e : Accepted\ code:

#include<cstdio>

using namespace std;

struct Line {
	int from, to, next;
}e[80010];

int n, m, cnt, root;
int st[40010], ed[40010], last[40010];

inline void add(int x, int y) {
	e[++cnt] = (Line){x, y, last[x]}; last[x] = cnt;
}

void dfs(int now, int fa) {
	++cnt;
	st[now] = cnt;
	for (int i = last[now]; i; i = e[i].next)
		if (e[i].to != fa)
			dfs(e[i].to, now);
	ed[now] = cnt;
}

int main() {
	scanf("%d", &n);
	for (int x = 0, y = 0, i = 1; i <= n; ++i) {
		scanf("%d %d", &x, &y);
		if (y == -1) root = x;
		else add(x, y), add(y, x);
	}
	cnt = 0;
	dfs(root, -1);
	scanf("%d", &m);
	for (int x = 0, y = 0, i = 1; i <= m; ++i) {
		scanf("%d %d", &x, &y);
		if (st[x] < st[y] && ed[y] <= ed[x]) puts("1"); else
		if (st[y] < st[x] && ed[x] <= ed[y]) puts("2"); else
		puts("0");	
	}
}

Guess you like

Origin blog.csdn.net/qq_39798042/article/details/88718734