CodeForces - 686D Kay and Snowflake(求一棵树的每颗子树的重心)

分析:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1000052;
vector <int> u[maxn];
int n, m, ans[maxn], s[maxn], fa[maxn];
void dfs(int x, int fas) {
	s[x] = 1;
	fa[x] = fas;
	int max_son = -1;
	for (int i = 0; i < u[x].size(); i++) {
		if (u[x][i] == fas) continue;
		dfs(u[x][i], x);
		s[x] += s[u[x][i]];
		if (max_son == -1 || s[u[x][i]] > s[max_son]) {
			max_son = u[x][i];
		}
	}
	if (max_son == -1) {
		ans[x] = x;
	}
	else {
		max_son = ans[max_son];
		while (2 * s[max_son] < s[x] ) {
			max_son = fa[max_son];
		}
		ans[x] = max_son;
	}
}
int main()
{
	ios::sync_with_stdio(false);
	cin >> n >> m;
	for (int i = 2; i <= n; i++) {
		int temp;
		cin >> temp;
		u[temp].push_back(i);
		u[i].push_back(temp);
	}
	dfs(1,-1);
	while (m--) {
		int pos;
		cin >> pos;
		cout << ans[pos] << endl;
	}
}
发布了227 篇原创文章 · 获赞 142 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_36306833/article/details/102943794