Codeforces Round #395 (Div. 2) C. Timofey and a tree (树的基础应用)

来源:互联网 发布:hgkp软件 编辑:程序博客网 时间:2024/05/22 11:48



C. Timofey and a tree
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.

Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.

Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.

A subtree of some vertex is a subgraph containing that vertex and all its descendants.

Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.

Input

The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.

Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ nu ≠ v), denoting there is an edge between vertices uand v. It is guaranteed that the given graph is a tree.

The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.

Output

Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.

Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.

Examples
input
41 22 33 41 2 1 1
output
YES2
input
31 22 31 2 3
output
YES2
input
41 22 33 41 2 1 2
output
NO
题意: 
一棵树中各个节点被染上了c[i]颜色; 
让你在一棵树中随便选一个节点作为根节点,然后把整棵树抬起来; 
问你是否存在一个根节点,这个根节点的直系儿子节点的子树里面的所有节点的颜色都一样; 

思路:

要理解树的构造以及特点,每棵树的子树是不相连的,就是几个分块了,所以这个点要想使所有子树都是一种颜色,其实就是这个点所连边包括所有端点不同色的边,因为还有端点不同色的边没有与根节点相连,那么肯定某一颗子树含有这个边,也就是这颗子树并没有同色,因为子树之间没有边相连,所以只能在某一科子树里。所以做法就是记录所有不同色的边的个数,记录每个点连接的不同色的边的个数,如果某个两者相等说明这个点连着所有不同色的边,也就是符合题意了

#include <iostream>#include <cstdio>#include <algorithm>using namespace std;const int maxn = 2e5 + 5;int u[maxn], v[maxn], cnt[maxn], c[maxn], sum = 0;int main(){    int n;    cin >> n;    for(int i = 1; i < n; i++)        cin >> u[i] >> v[i];    for(int i = 1; i <= n; i++)        cin >> c[i];    for(int i = 1; i < n; i++)    {        if(c[u[i]] != c[v[i]])            sum++, cnt[u[i]]++, cnt[v[i]]++;    }    for(int i = 1; i <= n; i++)    {        if(cnt[i] == sum)        {            cout << "YES\n" << i << endl;            return 0;        }    }    cout << "NO" << endl;    return 0;}



0 0
原创粉丝点击