1. 程式人生 > >【Vijos】lxhgww的奇思妙想

【Vijos】lxhgww的奇思妙想

d3d getc ostream iostream urn cst == query graph

【Vijos】lxhgww的奇思妙想

題面

Vijos

題解

戳這裏

(在求$k$級祖先那裏)

代碼

#include <iostream> 
#include <cstdio> 
#include <cstdlib> 
#include <cstring> 
#include <cmath> 
#include <algorithm>
#include <vector> 
using namespace std; 
inline int gi() { 
    register int data = 0, w = 1; 
    register char ch = 0; 
    while (!isdigit(ch) && ch != ‘-‘) ch = getchar(); 
    if (ch == ‘-‘) w = -1, ch = getchar(); 
    while (isdigit(ch)) data = 10 * data + ch - ‘0‘, ch = getchar(); 
    return w * data; 
}
const int MAX_N = 3e5 + 5; 
struct Graph { int to, next; } e[MAX_N << 1]; int fir[MAX_N], e_cnt; 
void clearGraph() { memset(fir, -1, sizeof(fir)); e_cnt = 0; }
void Add_Edge(int u, int v) { e[e_cnt] = (Graph){v, fir[u]}; fir[u] = e_cnt++; }
int son[MAX_N], dep[MAX_N], md[MAX_N], len[MAX_N], top[MAX_N], f[MAX_N][20]; 
int N, hbit[MAX_N]; 
void dfs1(int x, int fa) {
	md[x] = dep[x] = dep[fa] + 1, f[x][0] = fa; 
	for (int i = 0; i < 19; i++)
		if (f[x][i]) f[x][i + 1] = f[f[x][i]][i]; 
	    else break;
	for (int i = fir[x]; ~i; i = e[i].next) { 
		int v = e[i].to; if (v == fa) continue; 
		dfs1(v, x); 
		if (md[v] > md[son[x]]) son[x] = v, md[x] = md[v]; 
	} 
} 
void dfs2(int x, int tp) { 
	top[x] = tp, len[x] = md[x] - dep[top[x]] + 1; 
	if (son[x]) dfs2(son[x], tp); 
	for (int i = fir[x]; ~i; i = e[i].next)
		if (e[i].to != f[x][0] && e[i].to != son[x])
			dfs2(e[i].to, e[i].to); 
}
vector<int> U[MAX_N], D[MAX_N];
int query(int x, int k) {
	if (k > dep[x]) return 0; if (!k) return x; 
	x = f[x][hbit[k]]; k ^= 1 << hbit[k]; 
	if (!k) return x; 
	if (dep[x] - dep[top[x]] == k) return top[x]; 
	if (dep[x] - dep[top[x]] > k) return D[top[x]][dep[x] - dep[top[x]] - k - 1]; 
	return U[top[x]][k - dep[x] + dep[top[x]] - 1]; 
} 
int main () {
	clearGraph(); 
	N = gi();
	for (int i = 1; i < N; i++) {
		int u = gi(), v = gi(); 
		Add_Edge(u, v), Add_Edge(v, u); 
	} 
	dfs1(1, 0), dfs2(1, 1); 
	for (int i = 1; i <= N; i++)
		if (i == top[i]) { 
			int l = 0, x = i; 
			while (l < len[i] && x) x = f[x][0], ++l, U[i].push_back(x); 
			l = 0, x = i; 
			while (l < len[i]) x = son[x], ++l, D[i].push_back(x); 
		} 
	int res = 1;
	for (int i = 1; i <= N; i++) {
		if ((i >> res) & 1) ++res; 
		hbit[i] = res - 1; 
	} 
	int M = gi(), ans = 0;
	while (M--) {
		int x = gi() ^ ans, k = gi() ^ ans; 
		printf("%d\n", ans = query(x, k)); 
	} 
	return 0; 
} 

【Vijos】lxhgww的奇思妙想