CF708C:Centroids(树形dp & 重心构造判断)

C. Centroids
time limit per test
4 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

Tree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed .

You are given a tree of size n and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.

Input

The first line of the input contains an integer n (2 ≤ n ≤ 400 000) — the number of vertices in the tree. Each of the next n - 1 lines contains a pair of vertex indices ui and vi (1 ≤ ui, vi ≤ n) — endpoints of the corresponding edge.

Output

Print n integers. The i-th of them should be equal to 1 if the i-th vertex can be made centroid by replacing no more than one edge, and should be equal to 0 otherwise.

Examples
input
3
1 2
2 3
output
1 1 1 
input
5
1 2
1 3
1 4
1 5
output
1 0 0 0 0 
Note

In the first sample each vertex can be made a centroid. For example, in order to turn vertex 1 to centroid one have to replace the edge (2, 3) with the edge (1, 3).


题意:一棵树,判断每个节点是否能够通过操作:(删去一条边变成两棵树,然后将其中一棵并到另一棵的任意节点上) 变成树的重心。

思路:如果一个点的某个儿子或者祖先节点数大于n/2,那么就要执行操作,找到该枝能移除的最大的子树X(<=n/2),该枝节点总数-X<=n/2就是可以,否则不可以。向上向下维护一个节点能删去的最大子树。

//reference:YxuanwKeith
# include 
# define pb push_back
using namespace std;
const int maxn = 4e5+30;
vectorv[maxn];
int n, sons[maxn], mx_son[maxn], down[maxn], up[maxn];
void dfs(int cur, int pre)
{
    sons[cur] = 1;
    for(auto to : v[cur])
    {
        if(to == pre) continue;
        dfs(to, cur);
        sons[cur] += sons[to];
        down[cur] = max(down[cur], (sons[to]>n/2)?down[to]:sons[to]);
        mx_son[cur] = max(mx_son[cur], sons[to]);
    }
}

void dfs2(int cur, int pre)
{
    multisets;
    for(auto to : v[cur])
    {
        if(to == pre) continue;
        s.insert((sons[to]>n/2)?down[to]:sons[to]);
    }
    for(auto to : v[cur])
    {
        if(to == pre) continue;
        if(n-sons[to] <= n/2) up[to] = max(up[to], n-sons[to]);
        else
        {
            up[to] = max(up[to], up[cur]);
            s.erase(s.find((sons[to]>n/2)?down[to]:sons[to]));
            if(!s.empty()) up[to] = max(up[to], *s.rbegin());
            s.insert((sons[to]>n/2)?down[to]:sons[to]);
        }
        dfs2(to, cur);
    }
}
int main()
{
    scanf("%d",&n);
    for(int i=1; i n/2) ans = mx_son[i]-down[i] <= n/2;
        if(n - sons[i] > n/2) ans = n-sons[i]-up[i] <= n/2;
        printf("%d ",ans);
    }
    return 0;
}




你可能感兴趣的:(树形dp)