2445. Number of Nodes With Value One π
Description
There is an undirected connected tree with n
nodes labeled from 1
to n
and n - 1
edges. You are given the integer n
. The parent node of a node with a label v
is the node with the label floor (v / 2)
. The root of the tree is the node with the label 1
.
- For example, if
n = 7
, then the node with the label3
has the node with the labelfloor(3 / 2) = 1
as its parent, and the node with the label7
has the node with the labelfloor(7 / 2) = 3
as its parent.
You are also given an integer array queries
. Initially, every node has a value 0
on it. For each query queries[i]
, you should flip all values in the subtree of the node with the label queries[i]
.
Return the total number of nodes with the value 1
after processing all the queries.
Note that:
- Flipping the value of a node means that the node with the value
0
becomes1
and vice versa. floor(x)
is equivalent to roundingx
down to the nearest integer.
Example 1:
Input: n = 5 , queries = [1,2,5] Output: 3 Explanation: The diagram above shows the tree structure and its status after performing the queries. The blue node represents the value 0, and the red node represents the value 1. After processing the queries, there are three red nodes (nodes with value 1): 1, 3, and 5.
Example 2:
Input: n = 3, queries = [2,3,3] Output: 1 Explanation: The diagram above shows the tree structure and its status after performing the queries. The blue node represents the value 0, and the red node represents the value 1. After processing the queries, there are one red node (node with value 1): 2.
Constraints:
1 <= n <= 105
1 <= queries.length <= 105
1 <= queries[i] <= n
Solutions
Solution 1: Simulation
According to the problem description, we can simulate the process of each query, that is, reverse the values of the query node and its subtree nodes. Finally, count the number of nodes with a value of 1.
There is an optimization point here. If a node and its corresponding subtree have been queried an even number of times, the node value will not change. Therefore, we can record the number of queries for each node, and only reverse the nodes and their subtrees that have been queried an odd number of times.
The time complexity is $O(n \times \log n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|