zoukankan      html  css  js  c++  java
  • 祖孙询问

    题目描述

    思路

    读入的节点+1,代表树上的节点,这样0节点可以成为根节点的父节点,方便dfs

    代码

    #include <cstdio>
    
    const int MAX = 4e4 + 5;
    int n, m, root;
    int head[MAX], ver[MAX << 2], nt[MAX << 2], ht;
    int f[MAX][17], dep[MAX];
    void add(int x, int y) {
    	nt[++ht] = head[x], head[x] = ht, ver[ht] = y;
    }
    inline int read() {
    	int s = 0, f = 1;
    	char ch = getchar();
    	while (ch < '0' || ch > '9') {
    		if (ch == '-') f = -1;
    		ch = getchar();
    	}
    	while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
    	return f * s;
    }
    
    void dfs_lca(int x, int y) {
    	dep[x] = dep[y] + 1;
    	f[x][0] = y;
    	for (int i = 1; i < 17; ++i) f[x][i] = f[f[x][i - 1]][i - 1];
    	for (int i = head[x], j; i; i = nt[i]) {
    		j = ver[i];
    		if (j == y) continue;
    		dfs_lca(j, x);
    	}
    }
    
    bool lca(int x, int y) {
    	for (int i = 16; i >= 0; --i) {
    		if (dep[f[x][i]] >= dep[y]) x = f[x][i];
    	}
    	return x == y;
    }
    int main() {
    	n = read();
    	for (int i = 1, a, b; i <= n; ++i) {
    		a = read() + 1, b = read() + 1;
    		if (b == 0) root = a;
    		else add(a, b), add(b, a);
    		// printf("%d %d
    ", a, b);
    	}
    	dfs_lca(root, 0);
    	m = read();
    	for (int i = 1, x, y; i <= m; ++i) {
    		x = read() + 1, y = read() + 1;
    		if (x == root) {
    			putchar('1');
    		} else if (y == root) {
    			putchar('2');
    		} else {
    			if (dep[x] < dep[y]) {
    				if (lca(y, x)) putchar('1');
    				else putchar('0');
    			} else {
    				if (lca(x, y)) putchar('2');
    				else putchar('0');
    			}
    		}
    		puts("");
    	}
    	return 0;
    }
    
  • 相关阅读:
    linux指令备份
    jdk安装
    java-成员变量的属性与成员函数的覆盖
    Codeforces Round #384 (Div. 2) E
    Codeforces Round #384 (Div. 2) ABCD
    Codeforces Round #383 (Div. 2) D 分组背包
    ccpcfinal总结
    HDU 3966 & POJ 3237 & HYSBZ 2243 & HRBUST 2064 树链剖分
    HDU 5965 枚举模拟 + dp(?)
    Educational Codeforces Round 6 E dfs序+线段树
  • 原文地址:https://www.cnblogs.com/liuzz-20180701/p/11509319.html
Copyright © 2011-2022 走看看