http://codeforces.com/contest/1118/problem/F1
F1. Tree Cutting (Easy Version)
time limit per test
2 seconds
You are given an undirected tree of nn vertices.
Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.
You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.
How many nice edges are there in the given tree?
Input
The first line contains a single integer nn (2≤n≤3⋅1e5) — the number of vertices in the tree.
The second line contains nn integers a1,a2,…,an (0≤ai≤2) — the colors of the vertices. ai=1ai=1 means that vertex ii is colored red, ai=2ai=2 means that vertex ii is colored blue and ai=0ai=0 means that vertex ii is uncolored.
The ii-th of the next n−1 lines contains two integers vivi and uiui (1≤vi,ui≤n,vi≠ui) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.
Output
Print a single integer — the number of nice edges in the given tree.
Examples
input
Copy
5 2 0 0 1 2 1 2 2 3 2 4 2 5
output
Copy
1
input
Copy
5 1 0 0 0 2 1 2 2 3 3 4 4 5
output
Copy
4
input
Copy
3 1 1 2 2 3 1 3
output
Copy
0
Note
Here is the tree from the first example:
The only nice edge is edge (2,4). Removing it makes the tree fall apart into components {4}and{1,2,3,5}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices.
Here is the tree from the second example:
Every edge is nice in it.
Here is the tree from the third example:
Edge (1,3) splits the into components {1} and {3,2} the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2,3)splits the into components {1,3} and {2} the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.
题意:
给你n个点的一棵树,每个节点上都有颜色:红色 蓝色 无色
问你删除一条边后 剩下的两个连通块中最多只有一种颜色出现(无色不算颜色)
输出方案数
解法:
dfs 处理出以1为根节点后每个点的子树中有多少红点,多少蓝点
然后枚举边删除,记住是看u-v中下面的那个点自己子树中有没有两种颜色
再看种颜色减掉他自己的那颗子树有没有两种颜色出现
#include
using namespace std;
const int maxn=3e5+10;
vector G[maxn];
int fa[maxn],col[maxn],blue[maxn],red[maxn],from[maxn],to[maxn];
void dfs(int x,int y)
{
fa[x]=y;
if(col[x]==1) red[x]=1;
if(col[x]==2) blue[x]=1;
for(auto v:G[x])
{
if(v!=y)
{
dfs(v,x);
red[x] += red[v];
blue[x] += blue[v];
}
}
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&col[i]);
for(int i=1;i