You are given an undirected tree of $n$ 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 $n$ ($2 \le n \le 3 \cdot 10^5$) — the number of vertices in the tree.

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2$) — the colors of the vertices. $a_i = 1$ means that vertex $i$ is colored red, $a_i = 2$ means that vertex $i$ is colored blue and $a_i = 0$ means that vertex $i$ is uncolored.

The $i$-th of the next $n - 1$ lines contains two integers $v_i$ and $u_i$ ($1 \le v_i, u_i \le n$, $v_i \ne u_i$) — 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
5
2 0 0 1 2
1 2
2 3
2 4
2 5

Output
1

Input
5
1 0 0 0 2
1 2
2 3
3 4
4 5

Output
4

Input
3
1 1 2
2 3
1 3

Output
0



-----Note-----

Here is the tree from the first example: [Image] 

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: [Image] 

Every edge is nice in it.

Here is the tree from the third example: [Image] 

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.

Difficulty: MEDIUM_HARD
Tags: Tree algorithms

Graph traversal

Starter code:

Solutions:
from sys import stdin, stdout
from collections import *
from math import gcd, floor, ceil
st = lambda : list(stdin.readline().strip())
li = lambda : list(map(int, stdin.readline().split()))
mp = lambda : map(int, stdin.readline().split())
inp = lambda : int(stdin.readline())
pr = lambda n: stdout.write(str(n) + '\n')
mod = 1000000007
INF = float('inf')
ans = 0
n = inp()
l = [0] + li()
edge = [li() for i in range(n - 1)]
d = {i: [] for i in range(n + 1)}
for i in edge:
	(a, b) = i
	d[a].append(b)
	d[b].append(a)
(red, blue) = (0, 0)
for i in l:
	red += i == 1
	blue += i == 2
stack = [1]
v = [0 for i in range(n + 1)]
RED = [1 if i == 1 else 0 for i in l]
BLUE = [1 if i == 2 else 0 for i in l]
par = [-1 for i in range(n + 1)]
v[1] = 1
while stack:
	a = stack[-1]
	f = 0
	for i in d[a]:
		if not v[i]:
			v[i] = 1
			stack.append(i)
			f = 1
			par[i] = a
	if f == 0:
		z = stack.pop()
		if stack:
			RED[par[z]] += RED[z]
			BLUE[par[z]] += BLUE[z]
for i in range(1, n + 1):
	if par[i] != -1:
		if RED[i] == red and BLUE[i] == 0 or (RED[i] == 0 and BLUE[i] == blue):
			ans += 1
pr(ans)


from collections import deque
import sys
input = sys.stdin.readline

class Graph(object):

	def __init__(self, n, d):
		self.n = n
		self.graph = [[] for i in range(n)]
		self.parent = [-1 for i in range(n)]
		self.directed = d

	def addEdge(self, x, y):
		self.graph[x].append(y)
		if not self.directed:
			self.graph[y].append(x)

	def bfs(self, root):
		self.parent = [-1 for i in range(self.n)]
		queue = [root]
		queue = deque(queue)
		vis = [0] * self.n
		while len(queue) != 0:
			element = queue.popleft()
			vis[element] = 1
			for i in self.graph[element]:
				if vis[i] == 0:
					queue.append(i)
					self.parent[i] = element

	def dfs(self, root, ans):
		stack = [root]
		vis = [0] * self.n
		stack2 = []
		while len(stack) != 0:
			element = stack.pop()
			if vis[element]:
				continue
			vis[element] = 1
			stack2.append(element)
			for i in self.graph[element]:
				if vis[i] == 0:
					self.parent[i] = element
					stack.append(i)
		while len(stack2) != 0:
			element = stack2.pop()
			m = [0, 0]
			for i in self.graph[element]:
				if i != self.parent[element]:
					m[0] += ans[i][0]
					m[1] += ans[i][1]
			if arr[element] == 1:
				m[0] += 1
			elif arr[element] == 2:
				m[1] += 1
			ans[element] = m
		return ans

	def shortestpath(self, source, dest):
		self.bfs(source)
		path = [dest]
		while self.parent[path[-1]] != -1:
			path.append(parent[path[-1]])
		return path[::-1]

	def ifcycle(self):
		self.bfs(0)
		queue = [0]
		vis = [0] * n
		queue = deque(queue)
		while len(queue) != 0:
			element = queue.popleft()
			vis[element] = 1
			for i in graph[element]:
				if vis[i] == 1 and i != parent[element]:
					return True
				if vis[i] == 0:
					queue.append(i)
					vis[i] = 1
		return False

	def reroot(self, root, ans):
		stack = [root]
		count = 0
		vis = [0] * self.n
		while len(stack) != 0:
			e = stack[-1]
			if vis[e]:
				stack.pop()
				if self.parent[e] != -1:
					ans[self.parent[e]][0] += ans[e][0]
					ans[self.parent[e]][1] += ans[e][1]
					if self.parent[self.parent[e]] != -1:
						ans[self.parent[e]][0] -= ans[self.parent[self.parent[e]]][0]
						ans[self.parent[e]][1] -= ans[self.parent[self.parent[e]]][1]
				continue
			vis[e] = 1
			for i in self.graph[e]:
				if not vis[i]:
					stack.append(i)
			if self.parent[e] == -1:
				continue
			ans[self.parent[e]][0] -= ans[e][0]
			ans[self.parent[e]][1] -= ans[e][1]
			if self.parent[self.parent[e]] != -1:
				ans[self.parent[e]][0] += ans[self.parent[self.parent[e]]][0]
				ans[self.parent[e]][1] += ans[self.parent[self.parent[e]]][1]
			if 0 in ans[e] and 0 in ans[self.parent[e]]:
				count += 1
		return count
n = int(input())
g = Graph(n, False)
arr = list(map(int, input().split()))
for i in range(n - 1):
	(x, y) = map(int, input().split())
	g.addEdge(x - 1, y - 1)
ans = [[0, 0] for i in range(n)]
a = g.dfs(0, ans)
print(g.reroot(0, a))


import sys
input = sys.stdin.readline
n = int(input())
a = [int(t) for t in input().split(' ')]
mx = [[] for _ in range(n)]
for i in range(n - 1):
	(v1, v2) = map(int, input().split())
	mx[v1 - 1].append(v2 - 1)
	mx[v2 - 1].append(v1 - 1)
count = [[0, 0] for _ in range(n)]
total = [a.count(1), a.count(2)]
answer = 0
OBSERVE = 0
CHECK = 1
stack = [(OBSERVE, 0, -1)]
while len(stack):
	(state, vertex, parent) = stack.pop()
	if state == OBSERVE:
		stack.append((CHECK, vertex, parent))
		for child in mx[vertex]:
			if child != parent:
				stack.append((OBSERVE, child, vertex))
	else:
		for child in mx[vertex]:
			if child != parent:
				if count[child][0] == total[0] and count[child][1] == 0 or (count[child][1] == total[1] and count[child][0] == 0):
					answer += 1
				count[vertex][0] += count[child][0]
				count[vertex][1] += count[child][1]
		if a[vertex] != 0:
			count[vertex][a[vertex] - 1] += 1
print(answer)


import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.setrecursionlimit(2 * 10 ** 5)

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

@bootstrap
def dfs(u):
	vis[u] = 1
	global ans
	r1 = 0
	b1 = 0
	for j in adj[u]:
		if not vis[j]:
			r = (yield dfs(j))
			red = r[0]
			blue = r[1]
			if red == tr and blue == 0 or (red == 0 and blue == tb):
				ans += 1
			r1 += red
			b1 += blue
	if col[u - 1] == 1:
		r1 += 1
	elif col[u - 1] == 2:
		b1 += 1
	yield [r1, b1]
n = int(input())
col = list(map(int, input().split()))
adj = [[] for i in range(n + 1)]
for j in range(n - 1):
	(u, v) = map(int, input().split())
	adj[u].append(v)
	adj[v].append(u)
tr = 0
tb = 0
for j in col:
	if j == 1:
		tr += 1
	elif j == 2:
		tb += 1
vis = [0] * (n + 1)
ans = 0
dfs(1)
print(ans)


import sys
from collections import defaultdict
n = int(input())
arr = [int(__) for __ in input().split()]
sactive = set()
sactive.add(0)
nums = [0] * n
d1 = defaultdict(set)
d2 = defaultdict(set)
d = defaultdict(set)
lines = sys.stdin.readlines()
for i in range(n - 1):
	sactive.add(i + 1)
	(s, f) = [int(__) for __ in lines[i].strip().split()]
	s -= 1
	f -= 1
	d[s].add(f)
	d[f].add(s)
	nums[f] += 1
	nums[s] += 1
leaves = set()
for i in range(n):
	if nums[i] == 1:
		leaves.add(i)
while len(leaves):
	x = leaves.pop()
	if arr[x] == 0:
		sactive.remove(x)
		nums[x] -= 1
		targ = d[x].pop()
		nums[targ] -= 1
		d[targ].remove(x)
		if nums[targ] == 1:
			leaves.add(targ)
sactive1 = sactive.copy()
for targ in d:
	d1[targ] = d[targ].copy()
nums1 = nums[:]
nums2 = nums[:]
for i in range(n):
	if nums1[i] == 1:
		leaves.add(i)
while len(leaves):
	x = leaves.pop()
	if arr[x] != 1:
		sactive1.remove(x)
		nums1[x] -= 1
		targ = d1[x].pop()
		nums1[targ] -= 1
		d1[targ].remove(x)
		if nums1[targ] == 1:
			leaves.add(targ)
sactive2 = sactive.copy()
for targ in d:
	d2[targ] = d[targ].copy()
for i in range(n):
	if nums2[i] == 1:
		leaves.add(i)
while len(leaves):
	x = leaves.pop()
	if arr[x] != 2:
		sactive2.remove(x)
		nums2[x] -= 1
		targ = d2[x].pop()
		nums2[targ] -= 1
		d2[targ].remove(x)
		if nums2[targ] == 1:
			leaves.add(targ)
if len(sactive1 & sactive2) > 0:
	print(0)
else:
	print(len(sactive) - len(sactive1) - len(sactive2) + 1)


import os
import sys
from io import BytesIO, IOBase
from collections import defaultdict, deque, Counter, OrderedDict
import threading

def main():
	n = int(input())
	a = [0] + [*map(int, input().split())]
	adj = [[] for _ in range(n + 1)]
	for i in range(n - 1):
		(x, y) = map(int, input().split())
		adj[x].append(y)
		adj[y].append(x)
	num = [[0, 0] for _ in range(n + 1)]
	q = deque([1])
	visit = [0] * (n + 1)
	visit[1] = 1
	for i in range(n - 1):
		x = q[i]
		for nx in adj[x]:
			if visit[nx]:
				continue
			q.append(nx)
			visit[nx] = 1
	while q:
		x = q.pop()
		if a[x] == 1:
			num[x][0] += 1
		if a[x] == 2:
			num[x][1] += 1
		for nx in adj[x]:
			num[x][0] += num[nx][0]
			num[x][1] += num[nx][1]
	ans = 0
	for i in range(2, n + 1):
		if num[i][0] == num[1][0] and num[i][1] == 0:
			ans += 1
		if num[i][0] == 0 and num[i][1] == num[1][1]:
			ans += 1
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import os, sys
from io import IOBase, BytesIO
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'
from collections import deque
n = int(input())
a = list(map(int, input().split()))
tr = [[] for i in range(n)]
for i in range(n - 1):
	(u, v) = map(int, input().split())
	tr[u - 1].append(v - 1)
	tr[v - 1].append(u - 1)
r = {}
b = {}
s = [0]
s = deque()
s.append(0)
p = {0: -1}
m = []
while s:
	x = s.popleft()
	if a[x] == 1:
		r[x] = 1
		b[x] = 0
	elif a[x] == 2:
		r[x] = 0
		b[x] = 1
	else:
		r[x] = 0
		b[x] = 0
	for j in tr[x]:
		if j == p[x]:
			continue
		s.append(j)
		p[j] = x
	m.append(x)
for i in range(n - 1, 0, -1):
	r[p[m[i]]] += r[m[i]]
	b[p[m[i]]] += b[m[i]]
red = a.count(1)
blue = a.count(2)
ans = 0
for i in range(1, n):
	if r[i] == red and b[i] == 0 or (r[i] == 0 and b[i] == blue):
		ans += 1
print(ans)


from collections import deque
import sys
input = sys.stdin.readline

def bfs(s):
	q = deque()
	q.append(s)
	visit = [0] * (n + 1)
	visit[s] = 1
	parent = [-1] * (n + 1)
	p = []
	while q:
		i = q.popleft()
		p.append(i)
		for j in G[i]:
			if not visit[j]:
				q.append(j)
				visit[j] = 1
				parent[j] = i
	return (parent, p)
n = int(input())
a = list(map(int, input().split()))
cnt = [0] * 3
for i in a:
	cnt[i] += 1
G = [[] for _ in range(n + 1)]
for _ in range(n - 1):
	(u, v) = map(int, input().split())
	G[u].append(v)
	G[v].append(u)
(parent, p) = bfs(1)
(dpr, dpb) = ([0] * (n + 1), [0] * (n + 1))
ans = 0
for _ in range(n - 1):
	i = p.pop()
	j = parent[i]
	if a[i - 1] == 1:
		dpr[i] += 1
	elif a[i - 1] == 2:
		dpb[i] += 1
	if not dpr[i] and dpb[i] == cnt[2] or (not dpb[i] and dpr[i] == cnt[1]):
		ans += 1
	dpr[j] += dpr[i]
	dpb[j] += dpb[i]
print(ans)


import sys
n = int(input())
a = [int(t) for t in input().split(' ')]
mx = [[] for _ in range(n)]
lines = sys.stdin.readlines()
for i in range(n - 1):
	(v1, v2) = (int(t) - 1 for t in lines[i].split(' '))
	mx[v1].append(v2)
	mx[v2].append(v1)
count = [[0, 0] for _ in range(n)]
total = [a.count(1), a.count(2)]
answer = 0
OBSERVE = 0
CHECK = 1
stack = [(OBSERVE, 0, -1)]
while len(stack):
	(state, v, from_) = stack.pop()
	if state == OBSERVE:
		stack.append((CHECK, v, from_))
		for nv in mx[v]:
			if nv != from_:
				stack.append((OBSERVE, nv, v))
	else:
		for nv in mx[v]:
			if nv != from_:
				if count[nv][0] == total[0] and count[nv][1] == 0 or (count[nv][1] == total[1] and count[nv][0] == 0):
					answer += 1
				count[v][0] += count[nv][0]
				count[v][1] += count[nv][1]
		if a[v] != 0:
			count[v][a[v] - 1] += 1
print(answer)


import sys
import io, os
input = sys.stdin.buffer.readline
n = int(input())
A = list(map(int, input().split()))
g = [[] for _ in range(n)]
for i in range(n - 1):
	(u, v) = map(int, input().split())
	(u, v) = (u - 1, v - 1)
	g[u].append(v)
	g[v].append(u)
(r, b) = (0, 0)
for a in A:
	if a == 1:
		r += 1
	elif a == 2:
		b += 1
s = []
parent = [-1] * n
order = []
s.append(0)
while s:
	v = s.pop()
	order.append(v)
	for u in g[v]:
		if u == parent[v]:
			continue
		parent[u] = v
		s.append(u)
order.reverse()
B = [0] * n
R = [0] * n
for (i, a) in enumerate(A):
	if a == 1:
		R[i] += 1
	elif a == 2:
		B[i] += 1
	else:
		pass
for v in order:
	if parent[v] != -1:
		R[parent[v]] += R[v]
		B[parent[v]] += B[v]
ans = 0
for v in order:
	if parent[v] != -1:
		if R[v] == r and B[v] == 0:
			ans += 1
		elif R[v] == 0 and B[v] == b:
			ans += 1
print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys, threading
sys.setrecursionlimit(600000)
threading.stack_size(10 ** 8)

def dfs(x):
	global v, l, l1, l2, adj, a, b, ans
	v[x] = 1
	if l[x - 1] == 1:
		l1[x] += 1
	elif l[x - 1] == 2:
		l2[x] += 1
	for i in adj[x]:
		if not v[i]:
			dfs(i)
			l1[x] += l1[i]
			l2[x] += l2[i]
	if l1[x] * l2[x] == 0:
		if l1[x]:
			if l1[x] == a:
				ans += 1
		elif l2[x]:
			if l2[x] == b:
				ans += 1

def main():
	global v, l, l1, l2, adj, a, b, ans
	n = int(input())
	l = list(map(int, input().split()))
	v = [0] * (n + 1)
	l1 = [0] * (n + 1)
	l2 = [0] * (n + 1)
	(ans, a, b) = (0, l.count(1), l.count(2))
	adj = [[] for i in range(n + 1)]
	for i in range(n - 1):
		(x, y) = map(int, input().split())
		adj[x].append(y)
		adj[y].append(x)
	dfs(1)
	print(ans)
t = threading.Thread(target=main)
t.start()
t.join()


import os
import sys
from atexit import register
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
sys.__stdout__ = BytesIO()
register(lambda : os.write(1, sys.__stdout__.getvalue()))
res = 0

def main():
	n = int(input())
	a = input().split()
	red_cnt = a.count(b'1')
	blue_cnt = a.count(b'2')
	tree = [[] for _ in range(n)]
	for _ in range(n - 1):
		(v, u) = map(int, input().split())
		tree[v - 1].append(u - 1)
		tree[u - 1].append(v - 1)
	(dp, visited) = ([[0, 0] for _ in range(n)], [False] * n)

	def dfs(node):
		global res
		finished = [False] * n
		stack = [node]
		while stack:
			node = stack[-1]
			node_cnt = dp[node]
			if not visited[node]:
				visited[node] = True
			else:
				stack.pop()
				node_cnt[0] += a[node] == b'1'
				node_cnt[1] += a[node] == b'2'
				finished[node] = True
			for child in tree[node]:
				if not visited[child]:
					stack.append(child)
				elif finished[child]:
					child_cnt = dp[child]
					node_cnt[0] += child_cnt[0]
					node_cnt[1] += child_cnt[1]
					if child_cnt[0] == red_cnt and child_cnt[1] == 0 or (child_cnt[0] == 0 and child_cnt[1] == blue_cnt):
						res += 1
	dfs(0)
	print(res)
main()


import os, sys
from io import BytesIO, IOBase

def main():
	n = int(input())
	a = list(map(int, input().split()))
	red = a.count(1)
	blue = a.count(2)
	path = [[] for _ in range(n + 1)]
	for _ in range(n - 1):
		(u1, v1) = map(int, input().split())
		path[u1].append(v1)
		path[v1].append(u1)
	st = [1]
	parent = [0] * (n + 1)
	parent[1] = 1
	dp = [[0, 0] for _ in range(n + 1)]
	ans = 0
	while len(st):
		while len(path[st[-1]]) and parent[path[st[-1]][-1]]:
			path[st[-1]].pop()
		if not len(path[st[-1]]):
			x = st.pop()
			if a[x - 1] == 1:
				dp[x][0] += 1
			elif a[x - 1] == 2:
				dp[x][1] += 1
			if dp[x][0] == red and (not dp[x][1]) or (dp[x][1] == blue and (not dp[x][0])):
				ans += 1
			if len(st):
				dp[st[-1]][0] += dp[x][0]
				dp[st[-1]][1] += dp[x][1]
			continue
		i = path[st[-1]].pop()
		parent[i] = 1
		st.append(i)
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()