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;
    }
    
  • 相关阅读:
    Spring第一次测试错题解析
    正则回顾
    Spring经典---AOP
    动态代理
    MyBatis第一次测试卷---错题分析
    JS中对数组元素进行增删改移
    限制条件补全代码系列题
    字符串去空格
    数组去重
    数组排序
  • 原文地址:https://www.cnblogs.com/liuzz-20180701/p/11498272.html
Copyright © 2011-2022 走看看