1670. One Beacon Each

A sensor field has n stations numbered 0..n-1 joined by n - 1 cables listed in edges, forming a tree. Station i is a beacon when marks[i] = 1 and an ordinary station when marks[i] = 0.

You may cut any subset of the cables, including none or all of them. After the cuts the network falls apart into connected groups. A subset of cuts is good when every resulting group contains exactly one beacon. Count the good subsets and return the count modulo 1000000007 (two subsets are different when they cut different cables). If the field has no beacon the count is 0.

A bottom-up pass works: for each station keep the number of ways in which its still-open group currently holds 0 beacons or 1 beacon, and allow cutting a child's cable only when the child's group holds exactly one beacon. Aim for O(n) time and avoid deep recursion.

Example 1

Input:
n = 5edges = [[0,1],[1,2],[2,3],[3,4]]marks = [1,0,0,0,1]
Output:
4
Explanation:

Two beacons at the ends of a 5-node path: exactly one of the four edges must be deleted, so there are 4 valid sets.

Example 2

Input:
n = 4, edges = [[0,1],[0,2],[0,3]], marks = [1,1,1,0]
Output:
1
Explanation:

Cutting the edges to stations 1 and 2 isolates each as a one-beacon group and leaves {0, 3} with one beacon; every other choice leaves a group with 0 or 2 beacons.

Example 3

Input:
n = 3, edges = [[0,1],[1,2]], marks = [0,0,0]
Output:
0
Explanation:

There is no beacon at all, so no component can contain exactly one and the answer is 0.

Constraints

1 ≤ n ≤ 105
marks[i] is 0 or 1
edges has n - 1 pairs [u, v] describing a tree on nodes 0..n-1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…