Description
In 2016, Sister Jia Yuan had just learned about trees and was very happy. Now he wants to solve this problem: Given a root tree (root is 1), there are two operations:
- Mark operation: Mark a node (at the beginning, only Node 1 is marked, and other nodes are not marked, and a node can be marked multiple times .)
- Query operation: Ask a node about a marked ancestor (this node is also its own ancestor)
Can you help him?
Input
Enter two positive integers n and Q in the first line to indicate the number of nodes and the number of operations, respectively.
Next, the N-1 line, each line of two positive integers U, V (1 ≤ u, v ≤ n) indicates that u to V has a directed edge
The next Q row, such as "opernum" when "C" indicates that this is a tag operation, and "Q" indicates that this is a query operation for each query operation.
Output
Returns a positive integer to indicate the result.
A suffocating question, Luogu's Brute Force\ (\)?
But on the bzoj, t's flying emm
The question is tree section.
But Brute Force\ (\)Dropped. So the write positive solution is dragged backward to emmm.
Minor optimization: If no modification operation is performed, directly output\ (1 \).
Code
# Include <cstdio> # include <iostream> # include <algorithm> # define R registerusing namespace STD; const int Gz = 100008; inline void in (Int & X) {int F = 1; X = 0; char S = getchar (); While (! Isdigit (s) {If (S = '-') F =-1; S = getchar () ;}while (isdigit (s )) {x = x * 10 + S-'0'; S = getchar ();} x * = f;} int N, Q; int f [GZ], TG [GZ]; char OPT [5]; inline int work (r int X) {If (TG [x]) return X; while (F [x]) {X = F [X]; If (TG [x]) return x ;}} bool flg; int main () {In (N), in (Q ); for (r int I = 1, x, y; I <n; I ++) in (x), in (Y), f [y] = X; TG [1] = true; For (r int I = 1, x; I <= Q; I ++) {scanf ("% s", opt + 1 ); if (OPT [1] = 'q') {In (x); If (! Flg) puts ("1"); else printf ("% d \ n", work (x);} else {In (x), flg = true; TG [x] = true ;}}}
Brute force [p4092] [heoi2016/tjoi2016] tree