#C911. Health Status Queries on a Tree
Health Status Queries on a Tree
Health Status Queries on a Tree
You are given a tree with n nodes numbered from 1 to n, and the tree is rooted at node 1. Each node has an initial health state represented by either 0 (unhealthy) or 1 (healthy). You need to process a series of queries on this tree. There are two types of queries:
- Type 1: Given a node u, toggle its health state. That is, if the health state of node u is 0, change it to 1; if it is 1, change it to 0.
- Type 2: Given a node u, compute the number of healthy nodes in the subtree of u. The subtree of a node u consists of node u and all its descendants in the tree.
Formally, let \(n\) be the number of nodes and let the tree be described by its \(n-1\) edges. You are also given an array \(H = [h_1, h_2, \dots, h_n]\) representing the initial health states where \(h_i \in \{0,1\}\). Then, you have \(q\) queries. Each query is represented as a pair \((t, u)\), where:
- If \(t = 1\), then toggle the state of node \(u\).
- If \(t = 2\), then output the number of nodes \(v\) in the subtree of \(u\) such that \(h_v = 1\).
Your task is to process all queries in the order they are given and output the results of each query of type 2.
Note: You must read input from stdin
and write your answer to stdout
.
inputFormat
The input is given in the following format:
<n> <q> <u1> <v1> <u2> <v2> ... (n-1 lines for edges) <h1> <h2> ... <hn> <t1> <u1> <t2> <u2> ... (q lines for queries)
Here:
- n is the number of nodes in the tree.
- q is the number of queries.
- Each of the next n-1 lines contains two integers representing an edge connecting two nodes.
- The next line contains n integers where the i-th integer represents the initial health state of node i (0 or 1).
- Each of the following q lines describes a query with two integers: t (the query type, either 1 or 2) and u (the node on which the query is performed).
outputFormat
For each query of type 2, output a single integer on a new line — the number of healthy nodes in the subtree of the given node.
## sample5 5
1 2
1 3
3 4
3 5
1 1 0 0 1
2 3
1 5
2 3
2 1
1 4
1
0
2
</p>