zoukankan      html  css  js  c++  java
  • 点的距离

    题目描述

    思路

    lca 模板题

    代码

    #include <cstdio>
    #include <algorithm>
    using namespace std;
    
    const int MAX = 1e5 + 5;
    int n, m;
    int head[MAX], ver[MAX << 1], nxt[MAX << 1], ht;
    int dep[MAX], fa[MAX][22];
    void add(int x, int y) {
    	nxt[++ht] = head[x], head[x] = ht, ver[ht] = y;
    }
    inline int read() {
    	int s = 0;
    	char ch = getchar();
    	while (ch < '0' || ch > '9') ch = getchar();
    	while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
    	return s;
    }
    void dfs(int x, int u) {
    	fa[x][0] = u;
    	dep[x] = dep[u] + 1;
    	for (int i = 1; i <= 20; ++i) fa[x][i] = fa[fa[x][i - 1]][i - 1];
    	for (int i = head[x], j; i; i = nxt[i]) {
    		j = ver[i];
    		if (j == u) continue;
    		dfs(j, x);
    	}
    }
    int lca(int x, int y) {
    	if (dep[x] < dep[y]) swap(x, y);
    	for (int i = 20; i >= 0; --i) {
    		if (dep[fa[x][i]] >= dep[y]) x = fa[x][i];
    		if (x == y) return x;
    	}
    	for (int i = 20; i >= 0; --i) {
    		if (fa[x][i] != fa[y][i]) {
    			x = fa[x][i];
    			y = fa[y][i];
    		}
    	}
    	return fa[x][0];
    }
    int dist(int a, int b) {
    	return dep[a] + dep[b] - (dep[lca(a, b)] << 1);
    }
    int main() {
    	n = read();
    	for (int i = 1, a, b; i < n; ++i) {
    		a = read(), b = read();
    		add(a, b), add(b, a);
    	}
    	dfs(1, 0);
    	m = read();
    	for (int i = 1, a, b; i <= m; ++i) {
    		a = read(), b = read();
    		printf("%d
    ", dist(a, b));
    	}
    	return 0;
    }
    
  • 相关阅读:
    2017年期末获奖名单
    2018-01-17作业
    3.2.4 条件表达式
    3.2.3if语句的嵌套2
    if嵌套语句--作业题
    软工第四次作业
    软工第五次作业-结对
    软工第三次作业
    软工第二次作业——数独
    软工实践2017年第一次作业
  • 原文地址:https://www.cnblogs.com/liuzz-20180701/p/11498272.html
Copyright © 2011-2022 走看看