Codeforces Round #359 (Div. 1) B. Kay and Snowflake dfs
B. Kay and Snowflake
题目连接:
http://www.codeforces.com/contest/685/problem/B
Description
After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.
Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.
After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.
Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.
Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).
Input
The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively.
The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree.
Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.
Output
For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.
Sample Input
7 4
1 1 3 3 5 3
1
2
3
5
Sample Output
3
2
3
6
Hint
给你一棵树,Q次询问,每次询问这个点的中心是啥
题解:
离线做
重心是啥?就是砍掉这个点之后,剩下的树的大小都小于原树大小的1/2
那么我把这个点的所有子树都看一下,把最接近1/2的那个子树剁掉就好了,剩下的肯定满足……
这个启发式合并一下,nlognlogn很容易实现
但是其实,直接dfs一波就好了,递归处理,那个儿子肯定是在他的重儿子那儿,然后不停往上爬就好饿了
复杂度均摊一下,其实没有多大。
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e5+7;
vector<int>E[maxn];
int n,q,sz[maxn],ans[maxn],f[maxn];
void dfs(int x){
ans[x]=x;
sz[x]=1;
for(int i=0;i<E[x].size();i++){
int v=E[x][i];
dfs(v);
sz[x]+=sz[v];
}
for(int i=0;i<E[x].size();i++){
if(sz[E[x][i]]*2>sz[x])
ans[x]=ans[E[x][i]];
}
while((sz[x]-sz[ans[x]])*2>sz[x])
ans[x]=f[ans[x]];
}
int main(){
scanf("%d%d",&n,&q);
for(int i=2;i<=n;i++){
scanf("%d",&f[i]);
E[f[i]].push_back(i);
}
dfs(1);
for(int i=1;i<=q;i++){
int x;scanf("%d",&x);
printf("%d\n",ans[x]);
}
}