SalesforceOA #6
Collect Opportunity Data in a Tree
Estimated HardJudge-ready
Topics (AI-labelled)Topo Sort
You may start from any tree node; visiting a node collects all data within at most 2 edges of it. Find the minimum number of edge traversals needed to collect all data and return to the starting node. The source example with n=11 has only 9 edges and an isolated node 5, so it is not a valid tree; this site replaces it with a valid example.
Input
The first line contains n, the second line contains n data flags, each 0/1, followed by n−1 lines of edges u v. 2≤n≤100000, 0≤u,v<n, and the input is guaranteed to be a valid undirected tree.
Output
Output the minimum number of edge traversals; output 0 when there is no data or no movement is needed.
Example 1
Input:
6
1 0 0 0 0 1
0 1
1 2
2 3
3 4
4 5
Output:
2
Example 2
Input:
4
1 1 1 1
0 1
0 2
0 3
Output:
0
Example 3
Input:
2
0 0
0 1
Output:
0
Example notes
For a chain of length 6 with data at both ends, traversing the core edge twice suffices, so the answer is 2; a star tree and a tree with no data both give 0.
Editorial
Loading solution…