PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000070. LCA với gốc thay đổi (Dynamic-Root LCA)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

LCA với gốc thay đổi (Dynamic-Root LCA)

Dynamic-Root LCA

Source: VNOJ

Version: Phuoc Hung OJ Extended

Problem Statement

An undirected tree has a current root, initially vertex 11. Two commands are supported: ! r sets the current root to r‘;‘?uv‘queriestheLCAofr`; `? u v` queries the LCA of uand and v$ under the current root. Root changes persist until replaced by another ! command. No edge ever changes.

Input

First line is nn, followed by n−1n-1 edges u vu\ v and number of commands qq. Each of the next qq lines is ! r or ? u v.

Output

For each ? command print one line containing the requested LCA vertex.

Subtasks

General constraints: 1≤n≤1051\le n\le 10^5; 1≤q≤1051\le q\le 10^5; 1≤r,u,v≤n1\le r,u,v\le n; đồ thị là cây.

  • Subtask 1 (20 points): 1≤n≤401\le n\le 40; 1≤q≤501\le q\le 50.

  • Subtask 2 (30 points): 1≤n≤10001\le n\le 1000; 1≤q≤10001\le q\le 1000.

  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; 1≤q≤1000001\le q\le 100000.

Examples

Input

9
1 2
1 3
2 4
2 5
3 6
3 7
6 8
6 9
5
? 4 5
? 5 6
? 8 7
! 6
? 8 7

Output

2
1
3
6

Explanation

Before rerooting, LCA⁡(8,7)=3\operatorname{LCA}(8,7)=3. After ! 6, the root-to-88 and root-to-77 paths share vertex 66 as their deepest common ancestor.