P3884 [JLOI2009]二叉树问题(LCA)

传送门

一道很简单的树形题目,求一下LCA然后模拟就好了。

#include <bits/stdc++.h>
using namespace std;

const int N = 1e3 + 10;

int head[N], tot, n;
int dep[N], fa[N][22];
struct Edge{
	int v, next;
}edge[N];
vector<vector<int> > vec(200);
void add(int u, int v){
	edge[tot].v = v;
	edge[tot].next = head[u];
	head[u] = tot ++;
}

void dfs(int now, int pre){
	dep[now] = dep[pre] + 1;
	fa[now][0] = pre;
	for(int i = head[now]; i != -1; i = edge[i].next){
		int v = edge[i].v;
		if(v != pre)
			dfs(v, now);
	}
}

int getlca(int u, int v){
	if(dep[u] < dep[v])
		swap(u, v);
	while(dep[u] > dep[v])
		u = fa[u][(int)log2(dep[u] - dep[v])];
	if(u == v)
		return u;
	for(int i = 20; i >= 0; i --)
		if(fa[u][i] != fa[v][i])
			u = fa[u][i], v = fa[v][i];
	return fa[u][0];
}

int main(){
	cin >> n;
	memset(head, -1, sizeof head);
	for(int i = 1; i <= n - 1; i ++){
		int a, b;
		cin >> a >> b;
		add(a, b);
		add(b, a);
	}
	dfs(1, 0);
	for(int j = 1; j <= 20; j ++)
		for(int i = 1; i <= n; i ++)
			fa[i][j] = fa[fa[i][j - 1]][j - 1];
	
	int u, v;
	cin >> u >> v;
	int maxwid = 0, maxh = 0;
	for(int i = 1; i <= n; i ++)
		maxh = max(maxh, dep[i]);

	for(int i = 1; i <= 100; i ++){
		int cnt = 0;
		for(int j = 1; j <= n; j ++){
			if(dep[j] == i)
				cnt ++;
		}
		maxwid = max(maxwid, cnt);
	}

	int lca = getlca(u, v);
	int dis = (dep[u] - dep[lca]) * 2 + dep[v] - dep[lca];
	cout << maxh << endl << maxwid << endl << dis << endl;
	return 0;
}
上一篇:cf1541D Tree Array


下一篇:洛谷 P2633 Count on a tree 主席树