We need to solve a problem: There's a tree with n nodes. We have our labeling (1..n) and Li Chen's labeling (unknown permutation). The tree structure is known to us (via our labeling), i.e., we know edges between nodes as per our labels. Also we have our subtree S (a connected set of our labels) and we know Li Chen's subtree T (a connected set of his labels). But we don't know the mapping between labels. We can ask up to 5 queries of types: A x: ask Andrew the mapping of our label x to Li Chen's label (i.e., what is Li Chen's label for that node). B y: ask Andrew the mapping of Li Chen's label y to our label.
We must determine if S ∩ T (as nodes) is non-empty. Since we don't know mapping, we have to use queries to gain information. Ultimately we need to output either -1 or a common node (in our labeling). There is a known Codeforces problem: "Tree Queries" maybe. Actually recall problem: "1023E" maybe? Not sure.
We need to design an algorithm that uses at most 5 queries.
Constraints: n ≤ 1000, t ≤ 100. So we need an efficient deterministic algorithm per test case.
We have: we know our tree and our subtree S (connected). We know Li Chen's subtree T as set of his labels (unknown mapping). The goal: determine if there is a node v such that v ∈ S and f(v) ∈ T, where f is the permutation mapping our label to Li Chen's label. Equivalent: There exists v ∈ S such that f(v) ∈ T. Or we can think: There exists node u in T such that f^{-1}(u) ∈ S.
We can query mapping of specific vertices.
We are limited to 5 queries. This suggests we can find some candidate nodes, perhaps the center of subtree etc.
Observations: Both S and T are connected subtrees (connected subgraphs) in the tree. The entire tree is known. We can compute distances etc. With a few queries we can locate the mapping of a few nodes and infer overlap.
Approach: Since we can query up to 5 nodes, we can find a node in S that is also in T perhaps by binary search like approach, but limited queries.
Idea: Find a candidate node in S that might be common. Perhaps use the concept of "center" of the subtree. But we need to know mapping. Could ask for the mapping of some nodes in S and see if they lie in T. But T is given as set of Li Chen's labels. So if we query A x for some x in S, we get f(x). Then check if f(x) ∈ T (since we know T set). So if we find any x in S such that f(x) is in T, then x is a common node. So we could simply query A x for each x in S? But k1 could be up to n, and we only have 5 queries. So we need smarter selection.
Similarly, we can query B y for y in T to get f^{-1}(y) (our label), then check if that node is in S. So we could query some y in T and see if the result is in S.
Thus, we can try to find a common node by checking a small number of candidates. Which nodes should we query? Perhaps we can find the "centroid" of S or T, or some node guaranteed to be in the intersection if any.
If S and T intersect (as sets of nodes), then their intersection is also a connected subtree? Intersection of two connected subgraphs in a tree may not be connected? Actually in a tree, the intersection of two subtrees (connected subgraphs) is also a subtree (connected) because a tree is a median graph? Let's reason: In a tree, any two connected subsets, their intersection is also connected? Not always. Example: tree like a star, S contains two leaves and the center, T contains two other leaves and the center: intersection is just the center (connected). But if S is a path A-B-C and T is a path C-D-E, intersection is C (single node, connected). Actually any intersection of connected subgraphs in a tree is connected? Consider tree: nodes 1-2-3-4 (line). S = {1,2} (connected), T = {3,4} (connected), intersection empty. If S = {1,2,3} and T = {2,4}? But {2,4} not connected because 2-4 not directly connected? In a tree, a connected subgraph must be induced? Usually subtree is a connected subgraph, meaning the induced subgraph on those vertices is connected. So T = {2,4} would not be connected (unless there is edge 2-4). So T must be connected. So intersection of two connected subgraphs in a tree is always connected? I think yes because tree is a median graph and convex sets have property that intersection of convex sets is convex. But are subtrees convex? Usually a connected subgraph in a tree is not necessarily convex (like a set of nodes that is connected but not necessarily contains all nodes on paths between them). Actually in a tree, a set of nodes is called a subtree if it induces a connected subgraph. That set is not necessarily convex (i.e., containing all vertices on paths). For intersection of two connected induced subgraphs: consider tree: 1-2-3-4-5. S = {1,2,4,5}? Is that connected? 1-2 connected, 4-5 connected, but no connection between 2 and 4 because 3 missing, so not connected. So a connected subgraph must contain all intermediate nodes on any path between two nodes? Actually in an induced subgraph, connectivity means for any two vertices there is a path whose vertices all lie in the set. So if you have vertices 1 and 4, you need vertex 2 and/or 3 to be in set to connect them. So the set must be "convex": if two vertices are in the set, all vertices on the unique path between them must be in the set as well. Actually let's check: In a tree, if a set of vertices induces a connected subgraph, then for any two vertices u, v in the set, the unique path between u and v must be entirely within the set; otherwise, there would be a missing vertex and the induced subgraph would not have an edge connecting across that missing vertex because edges only exist directly between adjacent nodes. The path would require intermediate nodes to be present to connect via them. Without them, there would be no path in the induced subgraph. So yes, any connected induced subgraph of a tree is necessarily "convex": it contains the whole unique path between any two of its vertices. So subtrees are convex sets (i.e., node sets closed under taking paths). Therefore intersection of two convex sets is also convex (since if u and v are both in both sets, the path between them is in each set, hence in intersection). So intersection is also connected. Good.
Thus intersection, if non-empty, is a connected subtree. So we might be able to locate a node in intersection by exploring "central" nodes.
We know S entirely (our labeling) and we know T as set of labels in Li Chen's labeling, but we don't know mapping. However, we can query mapping of some nodes from our side to his, or from his side to ours. The goal is to find any common node with ≤5 queries.
Idea: Pick a candidate node from S that is "central" in S. For example, find the node in S that minimizes the maximum distance to any node in S (i.e., the center(s) of S). In a tree, there is either 1 or 2 such centers; if two, they are adjacent. Similarly, for T, but we don't know mapping of T's nodes to our labels. But we could query the mapping of a node from T to our labeling. Since we know T's labels, we can ask B y for some y in T to get our label corresponding to that Li Chen's label. That gives a node in our tree. If that node lies in S, then we have a common node. So one simple approach: pick any node from T, say the first y1, query B y1. Let v = answer. If v ∈ S, done (output v). Otherwise, we have a node v not in S. Similarly, we could also pick a node from S and query A x to get f(x) and check if it belongs to T.
But we need to guarantee that if there is an intersection, we will find a common node within 5 queries. If we just pick one random node, it might miss. We have 5 queries, so we can try several. But we need a deterministic strategy that works for all cases within 5 queries.
We can think: The intersection is a convex set. If we know one node from S and one node from T (mapped to our side) that are not in intersection, perhaps we can narrow down intersection by querying the LCA or something.
Another known approach from Codeforces problem "1147C"?? Not sure. Actually this problem appears to be from Codeforces Round #??? The problem name might be "Tree Queries" but I recall a problem: "You have two labelings, ask 5 queries to find if subtrees intersect." Possibly the intended solution uses the idea of "centroid" or "tree diameter" and uses queries to map the centers.
We have up to 5 queries. So we can afford to query up to 5 nodes. Perhaps we can find a node in S that is "deep" or use binary search on path.
Given that S is a subtree (connected convex set). If we query some node x in S and get f(x). If f(x) ∈ T, done. If not, then we know that x is not a common node. But we might use that information to limit the region where common nodes could exist. For example, if we take a node in S and map it to his labeling, we get some label. Since his subtree T is connected, we can consider the distances. But we don't know his tree structure under his labeling, but we know the tree structure in our labeling. However we know the permutation mapping between labelings, but we only know the structure via our edges. We can't compute distances in his labeling without knowing mapping. But we can ask B queries to map his nodes to ours, and then compute distances on our tree because the underlying tree is same; only labels differ. So if we map a node from his side to our side, we get its actual node (our label). Then we can compute distances on our tree.
Thus, after we query B y for some y in T, we get a node v (our label). If v is not in S, we now have a node v (not in S) that is the image of some y in T. Since T is a subtree in his labeling, the set of nodes corresponding to T (via mapping) is exactly f^{-1}(T) = { u | f(u) ∈ T }. That set is a subtree in our tree as well, because permutation is just a renaming, and connectivity is preserved under isomorphism: if T is connected in his labeling, then f^{-1}(T) is a connected set in our tree (since edges are same). Actually, careful: The tree structure is same; Li Chen's labeling is just a renaming of vertices. So the set of actual vertices (our labels) that correspond to T is exactly some connected subtree U of our tree. Because if we take the induced subgraph on f^{-1}(T), it's exactly the same as the induced subgraph on T in his labeling, which is connected. So U is a connected subtree (convex) in our tree. Similarly, S is also a connected subtree. Intersection is S ∩ U. So our problem reduces to: Given two connected subtrees S and U in the same tree, with S known exactly and U unknown except we can query certain points: we can ask for the mapping of a specific our node to know if it belongs to U? Actually we can ask A x to get f(x), and then we can check if f(x) ∈ T. That tells us whether x ∈ U (since x ∈ U iff f(x) ∈ T). Also we can ask B y to get f^{-1}(y), which yields a node v that is definitely in U (since y ∈ T). So we can get a node that belongs to U.
Thus we have: known S, unknown U (connected subtree). We can get at most 5 pieces of information: we can test membership of up to 5 of our nodes in U (by A queries), or we can get up to 5 sample nodes from U (by B queries). Our goal: determine if S ∩ U is non-empty, and if yes, output a node in the intersection.
This is similar to: we have two convex sets in a tree, one known, the other unknown but we can sample points from it and test membership. With a few queries, can we find intersection?
Now consider the following: If we can get one node u ∈ U (by querying B for some y in T), then we can compute the nearest node of S to u (in terms of distance in the tree). Since S is convex (connected subtree), the unique shortest path from u to S will end at a node that is the projection of u onto S. That projection node (call p) is the unique node in S that is closest to u, and the path from u to p is unique; moreover, if S and U intersect, then the intersection must lie on the path from u to some node in S? Actually, we can reason: Since both S and U are convex, if they intersect, then the projection of u onto S might be inside the intersection? Not necessarily. Let's analyze.
Let u ∈ U. If S ∩ U ≠ ∅, then there is some common node c. Consider the unique path from u to c. Since c ∈ S and S is convex, the path from u to c may exit U? U is convex, and u, c ∈ U, so the whole path from u to c is in U. Also the part from c to the projection p: Actually, p is the closest node in S to u. That distance d(u, S) = min_{v∈S} dist(u,v). Since c ∈ S ∩ U, we have dist(u,c) ≥ dist(u,p). And if p = c, then p is in intersection. If not, then p is some node in S not in U? Possibly. However, can we guarantee that if S ∩ U ≠ ∅, then the projection p must be in U? Not necessarily. Example: Consider a line: nodes 1-2-3-4. S = {2,3} (connected). U = {1,2} (connected). u = 1 (we pick u=1). Projection of u onto S is node 2 (closest node in S). Indeed, 2 is in U, so p ∈ U ∩ S. That's good. Another example: S = {2,3,4}, U = {1,2,5}? But U must be connected, so can't have 1 and 5 without 2,3,4? Let's try to construct a tree where the projection is not in U but intersection exists. Consider a tree shaped like a 'Y': central node r, with branches a, b, c. S = branch a plus r? Actually, let's define: nodes: r, a, b, c, where edges: r-a, r-b, r-c. S = {r, a} (convex). U = {b, r} (convex). Pick u = b ∈ U. Projection of b onto S: distances: b to r =1, b to a=2, so closest is r, which is in intersection. Good. Another try: S = {a, r} as before. U = {b, c}? But {b, c} is not connected because path between b and c goes through r, which is not in U. So U must be convex, so if U contains b and c, it must also contain r. So U = {b,c,r}. Then S ∩ U = {r}. u = b: projection to S is r (in intersection). u = c: same. So far projection is always in intersection? Is it always true? Let's think: Suppose S and U are convex sets with non-empty intersection. Take any u ∈ U. Let p = the unique node in S that is closest to u (since S is convex, the set of nodes in S that achieve min distance is actually a single node? In a tree, the set of nodes in a convex set S that are at minimum distance from u is a single node? Possibly if multiple nodes at same distance, but S is convex and tree: the distances from u to nodes in S are such that the set of nodes minimizing distance is the projection of u onto S, which is either a unique node or could be two nodes if u is exactly equidistant to two nodes? For convex sets in trees, the metric projection is unique because the tree metric is a median graph and convex sets are gated; the projection (gate) is unique. Indeed, in a tree, each vertex has a unique nearest point in a convex set (since the set is connected and convex). Actually, consider a convex set S that consists of two nodes that are adjacent? That's connected. For u not in S, if u is equidistant to both? Example: line: nodes 1-2-3, S={1,3}? But S={1,3} is not convex because path between 1 and 3 includes 2, which is not in S, so not connected (induced subgraph on {1,3} is disconnected). So convex sets must contain the whole path, so they cannot have gaps. So S is convex, hence for any u, there is a unique node p ∈ S that is closest; this is the first node of S encountered on the unique path from u to any node in S. More formally, there is a unique node p such that the path from u to any node in S passes through p, and p ∈ S. This is the projection (also called the gate). So p is unique.
Now, claim: If S ∩ U ≠ ∅, then for any u ∈ U, the projection p of u onto S lies in U ∩ S. Let's test: Let c be any node in S ∩ U. Consider the unique path from u to c. Since both u and c are in U and U is convex, the entire path from u to c is in U. On this path, as we go from u towards c, we eventually first hit S at some node p (since S is convex, the set of nodes on the path that are in S is a contiguous segment from the first entry point to c). Actually, the intersection of the path with S is a subpath starting at some node p (the first node in S when traveling from u to c) and ending at c. Since the path is in U (because both endpoints are in U and U is convex), all nodes on the path are in U. In particular, the first node p on the path that belongs to S is also in U. Thus p ∈ U ∩ S. Moreover, p is the closest node in S to u because any node in S closer would have to be encountered earlier, but p is the first S node on the shortest path to any node in S. So p is exactly the projection. Therefore p ∈ U ∩ S. This is a crucial property: For any u ∈ U, the projection of u onto S is in the intersection (if intersection is non-empty). Conversely, if intersection is empty, then the projection of u onto S will not be in U (since U ∩ S = ∅). So we can use this: pick any u ∈ U (by querying B y for some y in T). Compute its projection p onto S (using our tree knowledge). Then test whether p ∈ U (by querying A p to get f(p) and check if f(p) ∈ T). If the answer is yes (f(p) ∈ T), then p is common, and we output p. If not, then p ∉ U. But if intersection were non-empty, then p must be in U. So if we find that p ∉ U, we can conclude that intersection is empty. However, we must be careful: The projection p depends on the choice of u. But the property holds for any u ∈ U if intersection is non-empty. So if we pick a u ∈ U, compute p, and test p, then:
- If p ∈ U, then p ∈ S ∩ U, so intersection non-empty and we have a common node.
- If p ∉ U, then intersection must be empty? Could it be that intersection is non-empty but p ∉ U? According to the argument, if intersection is non-empty, then p must be in U. So yes, p ∉ U implies intersection empty. So this yields a deterministic solution: we need to get one u ∈ U (via a B query), compute its projection p onto S, then check membership of p in U via an A query. That uses at most 2 queries. But is this always correct? Let's verify thoroughly.
We assume: S is a connected convex set (subtree) in our tree. U = f^{-1}(T) is also a connected convex set (since T is connected). Intersection S∩U.
Given u ∈ U, let p = argmin_{v ∈ S} dist(u, v). Because S is convex, p is unique and lies on the shortest path from u to any node in S. In particular, for any c ∈ S∩U, the unique path from u to c goes through p. Since u ∈ U and c ∈ U, and U is convex, the entire path is in U. So p ∈ U. Therefore p ∈ S∩U. So indeed p is a common node.
Thus, if we can get any u ∈ U, then p computed will be a common node if intersection exists; if intersection empty, then p might not be in U, but we will test it.
But wait, what if intersection is non-empty but our computed p is not in U? Could the property fail? Let's double-check convexity: In a tree, a set X is convex if for any two nodes a,b ∈ X, all nodes on the unique path between a and b are also in X. S and U are both convex (connected induced subgraph). Intersection of two convex sets is convex but possibly empty. The argument used: take u ∈ U, c ∈ S∩U. Then path from u to c is in U because U convex. Also, since S is convex, the path from p (first node of S encountered from u) to c lies in S. But is it guaranteed that p lies on the path from u to c? Yes, because p is the closest node in S to u, so the path from u to p is a subpath of the path from u to c (since c is also in S). Actually careful: The closest node p might not lie on the u-c path? In a tree, the shortest path from u to c is unique. That path goes from u to c. The distance from u to c = dist(u,p) + dist(p,c) because p is the point where the path from u to S meets S. Since c ∈ S, the path from u to c must intersect S at some point, and the first point of intersection is exactly the point on that path that is in S and closest to u. That is indeed p. So p lies on the u-c path. Since u and c are both in U, and U is convex, the entire path between u and c is in U, so p ∈ U. Good.
Thus the property holds.
Now, one nuance: We need to compute p, the closest node in S to u. Since we know the tree and S, we can compute distances from u to all nodes? n ≤ 1000, we can BFS from u or use LCA precomputation. But we need to compute the projection efficiently. How to compute p? The projection of u onto S is the unique node in S that lies on the shortest path from u to any node in S, and it can be found by: start from u and traverse towards S along the unique path to any node in S. Since S is convex, there is a unique neighbor direction to move to get closer to S. One way: compute the distances from u to all nodes? But we can do better: Because tree is small, we can preprocess LCA for whole tree once per test case, then compute distances and find the node on the path from u to the "center"? But to find p, we can simply take any node in S, say s0 (maybe the first in list). Then the unique path from u to s0: we can compute the LCA, etc. However, the first node on that path that belongs to S is not necessarily the closest; it could be that s0 is far and the path enters S at some node that might not be the first node in S? Actually the closest node p is the first node on the path from u to any node in S. If we take an arbitrary node s0 ∈ S, the unique path from u to s0 will have a first node where it hits S. That node is exactly the projection p, because any node in S that is closer would be encountered earlier on that path; but if there were a closer node not on that path, then the distance to that node would be shorter and the path to that node would diverge. But is the first node of S on the path to s0 always the closest? Consider: S is convex. The set of nodes in S that lie on the path from u to s0 is a contiguous segment (possibly starting at some node p and ending at s0). p is the node on that path closest to u. Could there be another node q ∈ S not on that path that is even closer? Suppose there is q ∈ S with dist(u,q) < dist(u,p). Then the path from u to q would intersect the path from u to s0 at some point (maybe at u itself). But since p is the first node of S on the path to s0, any node q ∈ S not on that path would have its path from u branch off before p. That would imply that there is some node on the path from u to q that is also on the path from u to s0 before p. But that node might not be in S. Could q be closer? Let's think: In a tree, the set of nodes that are closer to u than p is the set of nodes whose distance from u is < dist(u,p). This set is a ball around u. S is convex. The intersection of S with that ball would be empty because p is the closest. So no node q ∈ S can be closer. Therefore p is indeed the unique closest node. So we can find p by taking any s ∈ S, then walking from u towards s until we find the first node in S. That can be done by computing the path and scanning. Since n ≤ 1000, we can just compute the whole path (list of nodes on path from u to s) and find the first node that belongs to S. That will be p. So algorithm:
-
Choose any y in T (say the first given y1). Query B y. Get answer u = f^{-1}(y). That's a node in our labeling, and u ∈ U.
-
Compute p = projection of u onto S: For any s in S (say first x1), get the unique path from u to s. Since the tree is small, we can compute path by BFS/DFS or using parent array. Actually we can precompute parent and depth for root, then get path via climbing LCA. Simpler: do BFS from u to build distances and parent, then find a node in S with minimum distance; but we can also compute directly: Find the node on the path from u to s that belongs to S and is closest to u. To do that, we can iterate over the path nodes in order from u towards s, check membership in S. The first node that is in S (if any) is p. But note: u might already be in S? If u ∈ S, then p = u. But u ∈ U, and if intersection exists, then p=u? Actually if u ∈ S, then u ∈ S∩U, so we are done immediately without further query? Wait: we queried B y and got u. After that, we know u. We can check if u ∈ S (since we know S). If yes, then u is common, we can output it. That uses only 1 query. So we can incorporate: after obtaining u, if u ∈ S, output u and done. If not, we compute p.
-
Then query A p to get f(p). If f(p) ∈ T, then p is common. Output p. If f(p) ∉ T, then intersection empty, output -1.
Thus, total queries: at most 2 (B y and A p). This is within 5.
But is there any scenario where this fails? Let's test edge cases.
Case: intersection empty. Then we pick u ∈ U. Compute p = projection of u onto S. Since intersection empty, p ∉ U. So A p will return f(p) not in T. So we output -1. Correct.
Case: intersection non-empty. Then as argued, p ∈ U∩S. So A p will confirm p is in U (since f(p) ∈ T). So we output p. Correct.
But we must ensure that we compute the correct projection. However, is it always true that the projection of u onto S is in U when intersection non-empty? Our argument used existence of some c ∈ S∩U. But what if u itself is that c? Already handled: if u ∈ S, then intersection non-empty and we output u. So we are in case u ∉ S. Then we have u ∈ U \ S. We have some c ∈ S∩U. Since u and c are both in U and U is convex, the entire path between them is in U. The first node from u towards c that belongs to S is p, and it's on that path, so p ∈ U. Good.
But one subtlety: Could it be that the projection p is not unique? No, it's unique.
Thus, the 2-query solution seems sound.
But wait: Are we allowed to query A p after we have done a B query? Yes.
But there is a catch: What if the tree is such that the projection p is not defined? That would happen if S is empty? But k1 ≥ 1, so S non-empty. So p always exists.
Thus, this algorithm is extremely simple: For each test case, we read n, edges, build adjacency, read k1 and S set, read k2 and T set. Then we decide: pick any y from T, say y = first element of the given list (or maybe any). Query "B y". Read response u. If u is in S, then output "C u". Else compute p = nearest node in S to u. How to compute p efficiently? Since n ≤ 1000, we can BFS from u to compute distances to all nodes, then find among S the node(s) with minimal distance; if multiple, any works? Actually projection is unique, but if there are multiple nodes in S at same minimal distance, is that possible? Consider S convex: could there be two nodes at the same distance from u? Yes, if u is exactly equidistant to two nodes in S. But can that happen if S is convex? Example: u is at equal distance to two distinct nodes in S. Since S is convex, the path between those two nodes lies in S. u's distances to them are equal. In a tree, the set of points equidistant to two nodes is the perpendicular bisector? Possibly the midpoint of the path. But could u be such that it is not on the path? Let's think: Suppose S contains a path of length 2: nodes a - b - c. u is a node connected to b (the middle) but at distance 1 from b. Then distances: dist(u,a)=2, dist(u,b)=1, dist(u,c)=2. So minimal unique b. To have two nodes at equal minimal distance, u must be at the same distance to two nodes, and there must be no node with smaller distance. For convex S, the metric projection is unique because convex sets in trees are "gated": for any u, there is a unique gate p such that for any s ∈ S, dist(u,s) = dist(u,p) + dist(p,s). This gate is unique. Indeed, in a median graph (trees are median), every convex subgraph is gated. The gate is unique. So the set of nodes at minimum distance from u is exactly {p}. So no tie. So we can safely compute p by finding a node in S with minimum distance; if there are ties (maybe due to implementation or if S is not convex? But it is guaranteed convex), but we can still pick any; if there is tie, then both would be gates? Actually if there were two nodes p1, p2 at same minimal distance, then consider the path between p1 and p2. Since S is convex, that path is in S. The midpoint (or some node) would be closer? Let's analyze: In a tree, if p1 and p2 are distinct and both at minimal distance d from u, then consider the unique path between p1 and p2. Let w be the point on that path closest to u (maybe the meeting point of the three paths). Actually, because tree, there is a unique node m where the paths from u to p1 and u to p2 diverge. Suppose path from u to p1: u ... m ... p1, and from u to p2: u ... m ... p2. Then dist(u,p1) = dist(u,m)+dist(m,p1), dist(u,p2)=dist(u,m)+dist(m,p2). If both are equal d, then dist(m,p1)=dist(m,p2). If both >0, then m is not p1 nor p2. Then m is on the path from p1 to p2, and since S is convex, m ∈ S. But dist(u,m) = d - dist(m,p1) < d (since dist(m,p1)>0). So m is closer to u than p1,p2, contradiction. Therefore, there cannot be two distinct nodes in S at minimal distance. So projection is unique.
Thus we can compute p by any method: BFS from u, then pick the node in S with minimum distance; that node is unique. Or find the path to any s ∈ S and find the first node in S along that path; that also yields p.
Now, is there any tricky scenario? The algorithm uses at most 2 queries. However, we must consider if the tree size is 1? n=1, then S and T are both {1} (since labels are 1). But our labeling and Li Chen's labeling: both label 1 might correspond to the same physical node? Actually if n=1, the permutation is trivial: our label 1 maps to his label 1. Then S and T both contain that node. Our algorithm: pick y from T, say y=1, query B 1 -> answer u? But we need to be careful: For n=1, there are no edges. The input: n=1, then no edges. Then k1=1, x1=1. k2=1, y1=1. We query B 1? That would give u = f^{-1}(1). Since permutation maps our label to his label, f is bijection. f^{-1}(1) is the node with his label 1. But his label 1 corresponds to some our label; due to permutation, could be 1? Not necessarily? Since permutation is a bijection from {1..n} to {1..n}, if n=1, the only permutation is [1]. So u=1. Then u∈S, so output C 1. Works. But we used a query. However, we could also output C 1 without any query, because we know both subtrees are {1}? But we don't know mapping? Actually we know that our subtree is {1} (since k1=1, x1=1). We know Li Chen's subtree is {y1} = {1} in his labeling. But we don't know if his node 1 corresponds to our node 1. It could be that his label 1 is our node something else? However, since n=1, the only node is the single physical node. So regardless of labeling, both subtrees must contain that unique node. So indeed they intersect. But we cannot be sure without knowing permutation? Actually, physically there is only one node. So both subtrees, regardless of labels, refer to that node. So they must intersect. So we could output C 1 without queries. But our algorithm using query also works, and it's within limit. However, we need to ensure we don't exceed 5 queries; using 1 or 2 is fine. So we can keep algorithm as is. But we could also add a check: if S set and T set? But we cannot compare directly because they are in different labeling. So we cannot deduce intersection from sizes without mapping. So we still need queries. But in n=1, it's obvious. But we can just let algorithm handle.
One more nuance: In the interaction, we must be careful: after reading the input for a test case, we can ask queries. The input for each test case includes the tree edges (according to our labeling), and the subtrees. Then we perform interaction.
Our algorithm:
- Read n.
- Read edges, build adjacency.
- Read k1, then list x_i; store S as set (maybe boolean array or vector).
- Read k2, then list y_i; store T as set (maybe for membership check).
- Pick y0 = y_1 (or any).
- Print "B y0" and flush.
- Read response u (int).
- If u is in S: print "C u" and flush; done.
- Else:
- Compute p = projection of u onto S.
- Print "A p" and flush.
- Read response v (int).
- If v is in T: print "C p" and flush.
- Else: print "C -1" and flush.
This uses 2 queries at most. But is there any case where we might need more queries? Possibly if the projection p is not in S? p is computed as the closest node in S; it's in S by definition. So fine.
Now, we should also consider a scenario: we pick y0 from T, but maybe T is empty? But k2 ≥ 1, so non-empty.
Thus, the problem seems solved with at most 2 queries. However, the problem statement says we may ask at most 5 questions, so using 2 is fine.
But wait, is there any hidden catch? The problem might be trickier: The subtrees are defined as connected subgraphs, but are they necessarily induced? Typically "subtree" in tree problems means a connected subgraph (which as argued is convex). However, is it guaranteed that the subtree is induced? Usually when we say a subtree defined by a set of vertices, we assume the induced subgraph is connected. The statement: "Your subtree consists of the vertices labeled x1, x2, …, x_{k_1} in your labeling" and "It is guaranteed that these vertices form a subtree." That typically means the induced subgraph on these vertices is connected. So yes, convex.
Thus, the solution is valid.
But why is the limit 5 then? Possibly to allow alternative approaches, or to handle some nuance I missed. Could there be a scenario where our algorithm fails because of the assumption that U is convex? But we argued that U = f^{-1}(T) is convex because T is convex in Li Chen's labeling and the tree structure is same, so the set of physical nodes corresponding to T is exactly the same as the set of nodes in our tree that map to those labels; since permutation is just renaming, the induced subgraph on those nodes is isomorphic to the induced subgraph on T, so it is connected, thus convex. However, is it guaranteed that the induced subgraph on U is connected? Yes, because the mapping is a graph isomorphism between the two labeled trees. The tree edges are defined based on the physical connections; the labeling just changes vertex names. So if T is a connected set in his labeling, then the corresponding set of physical nodes (our labels) is also connected. So U is indeed a subtree.
Thus the property holds.
Now, we need to compute projection efficiently. Since n ≤ 1000, we can simply BFS from u to compute distances to all nodes. Then find node in S with minimal distance; that's p. Alternatively, we can compute LCA after rooting tree. But BFS is simpler and O(n) per test case, which is fine.
Edge Cases: When u is already in S, we output u and done (no need to compute projection). That's best.
Now, confirm with sample tests:
Sample 1:
Input:
1
3
1 2
2 3
1
1
1
2
So n=3, edges: 1-2,2-3. Our subtree: k1=1, x=[1]. Li Chen's subtree: k2=1, y=[2]. (In hack format they gave permutation [2,3,1], but we don't know that). We pick y0=2. Query B 2. Response? In hidden permutation, f(our label) -> his label. Since they gave permutation [2,3,1] meaning our 1 -> his 2, our 2 -> his 3, our 3 -> his 1. So B 2 asks: what is our label of his label 2? That is f^{-1}(2) = 1. So u=1. u is in S (since S={1}), so we output C 1. That matches sample output, though sample also includes an extra A query for demonstration; our algorithm would just do B 2 then output C 1. But we could also do as sample; they did A 1 and B 2 then C 1. Our algorithm would be correct.
Sample 2:
First test case:
Input:
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
So n=6, edges as given. Our subtree S: {1,3,4,5} (connected? Check: 1-4-5 path includes 4, so yes. Actually nodes: 1 connected to 3,4; 4 to 5,6; so {1,3,4,5} is connected? 1-4 is edge, 4-5 is edge, 1-3 is edge, so yes). Li Chen's subtree T: {3,5,2} (in his labeling). We pick y0 = first element 3. Query B 3. According to hidden permutation (for both cases they gave permutation [5,3,2,4,1,6]?? Actually second sample says: "In the second sample, there are two test cases. ... For the first case, the permutation is [5,3,2,4,1,6]". Let's compute: Our labeling to his: our 1->5, 2->3, 3->2, 4->4, 5->1, 6->6. So f(1)=5, f(2)=3, f(3)=2, f(4)=4, f(5)=1, f(6)=6. Then T = {3,5,2} in his labels. That means physical nodes corresponding to these labels: f^{-1}(3)=2, f^{-1}(5)=1, f^{-1}(2)=3. So U = {2,1,3} = {1,2,3}. Indeed U is connected? 1-2? edge? Our tree edges: 1-2 yes, 1-3 yes. So U is connected. Our S = {1,3,4,5}. Intersection S∩U = {1,3}. So there is intersection.
Our algorithm: B 3 -> returns f^{-1}(3) = 2 (since his label 3 maps to our node 2). u=2. u ∈ S? 2 is not in S (S = {1,3,4,5}). So compute projection of u=2 onto S. Compute distances: 2 is adjacent to 1 (edge 1-2). Distances to S nodes: dist(2,1)=1, to 3: path 2-1-3 =2, to 4: 2-1-4 =2, to 5: 2-1-4-5=3. Minimum is 1, with node 1. So p=1. Then query A 1: returns f(1)=5. Is 5 in T? T={3,5,2}. Yes, 5∈T. So output C 1. That matches sample: they output C 1 after B 2? Actually sample output for first test case: "B 2\nC 1". Wait sample output shows:
B 2
C 1
A 1
C -1
Actually the sample output given for second sample is:
Output
B 2
C 1
A 1
C -1
But the input description says: The second sample input:
2
6
... (first case)
3
... (second case)
And the output lines: "B 2" then "C 1" then "A 1" then "C -1". That corresponds to two test cases: first test case they used B 2 (not B 3) and got C 1; second test case they used A 1 and got C -1. So let's see: In first test case, they asked B 2. Why 2? Possibly because they chose some y from T? T = {3,5,2}. They could choose y=2, get u = f^{-1}(2) = 3. u=3 is in S? S = {1,3,4,5} yes, so output C 3? But they output C 1. Actually they output C 1, maybe they chose different. Let's compute: If they ask B 2, then answer: f^{-1}(2)=3 (since our 3 -> his 2). So u=3. u∈S, so they could output C 3. But they output C 1. So they maybe did something else. Or maybe they asked B 2, got answer 3, then perhaps they reasoned that 1 is also common? But they still output C 1. That's fine, any common node works. In our algorithm, if we had chosen y=2, we would get u=3, then output C 3 (or could output 3). But the problem statement sample explanation says: "We first ask 'B 2', and Andrew will tell us 3. In this case, we know 3 is a common vertex, and moreover, any subtree with size 3 that contains node 3 must contain node 1 as well, so we can output either 'C 1' or 'C 3' as our answer." So they output C 1. So they didn't output the direct u, but they reasoned something else. However, our algorithm when u∈S, we output u. That would be C 3. That's also acceptable, because we can output any common vertex. The problem statement: "determine one of your labels for any of the common vertices." So outputting 3 is fine. But sample output shows C 1. That's okay; judges compare any correct common node. So our algorithm might output C 3 instead of 1, but still correct.
Now second test case of sample 2:
Input:
3? Actually the input after first test case continues with another tree? The sample input:
2
6
... (edges as same? Actually they gave two test cases, but both have same tree? Possibly same tree, different subtrees. The input shows:
2
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5
Wait parsing: The first test case: n=6, edges as above, then k1=4, list [1,3,4,5]; then k2=3, list [3,5,2]; then next test case: n=3? Actually the next lines: "3" could be n? But they wrote "3" and then "6"? Let's read the sample input carefully from problem statement:
Input:
2
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5
This is confusing. Actually typical CF problem sample might be: first line t=2. Then for first test case: n=6, then 5 edges, then k1=4, list of 4 numbers, then k2=3, list of 3 numbers. Then second test case: n=6? But they wrote "3" then "6"? Let's parse as per format: After the first test case, we need to read the next test case's n. After finishing first test case, the next input line should be the n for second test case. The sample shows "3" then "6". That would be n=3? But then edges? However, they wrote:
...
3
3 5 2
3
6
1 2
...
Wait, after the first test case's T list: "3 5 2" then the next line is "3". That "3" is actually the k1 for second test case? Because after finishing first test case, we must provide next test case's n. So maybe the input is:
t=2
Test case 1:
n=6
edges: (1 2), (1 3), (1 4), (4 5), (4 6)
k1=4
x: 1 3 4 5
k2=3
y: 3 5 2
Test case 2:
n=3? But then edges would be? Actually after "3 5 2" the next line is "3". That could be the n for test case 2? Then after that we have "6"?? Not matching. Let's re-read the sample input as given in problem statement:
"Input
2
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5"
Actually there might be a formatting issue: The second test case might also have n=6, but the "3" before "6" might be something else. Let's check the official problem (CF 1795E?). I think it's CF Round #1310? Not sure. However, the sample output given is:
Output
B 2
C 1
A 1
C -1
That matches two test cases: first test case they did B 2 and answered C 1; second test case they did A 1 and answered C -1. So the second test case had something that led to A 1 and then -1.
Our algorithm for second test case: we need to read input. Suppose second test case: n=6, edges same, k1=3, x: 1 2 3, k2=3, y: 4 1 6. And maybe there is an extra number 5 at the end? The sample input ends with "5". That might be extraneous? Possibly it's part of hack format? Actually the sample input from CF might be exactly as above. But I'm not going to worry; we trust the algorithm.
Check second test case scenario: According to sample explanation: "In the second case ... You ask Andrew for the label of node 1 in Li Chen's labelling and Andrew says 5. In this case, you know that Li Chen's subtree doesn't contain node 1, so his subtree must be consist of the nodes 4,5,6 (in your labelling), thus the two subtrees have no common nodes." So in second test case: Our subtree S = {1,2,3} (connected). Li Chen's subtree T = {4,1,6}? Actually they said "4 1 6". So T = {4,1,6} in his labeling. Hidden permutation: [5,3,2,4,1,6]? Let's check: f(1)=5, f(2)=3, f(3)=2, f(4)=4, f(5)=1, f(6)=6. So T his labels {4,1,6} correspond to our nodes: f^{-1}(4)=4, f^{-1}(1)=5, f^{-1}(6)=6. So U = {4,5,6}. That is connected (4-5,4-6). S = {1,2,3}. Intersection empty. Our algorithm: pick y0 from T, say first element 4. Query B 4 -> response u = f^{-1}(4)=4. u=4 not in S. Compute projection of 4 onto S. Distances: S nodes: 1,2,3. Tree: 1 connected to 2,3,4. So distances: 4 to 1 =1, to 2 =2 (4-1-2), to 3 =2 (4-1-3). Minimum is 1, p=1. Then query A 1 -> returns f(1)=5. Is 5 in T? T = {4,1,6}. 5 not in T. So we output -1. That matches sample: they used A 1 and got -1, but they output C -1. They used only one query A 1? Actually sample output for second test case is "A 1\nC -1". They didn't do a B query. They directly asked A 1. But in our algorithm we would do B 4 then A 1 (two queries). However, we could also do A 1 first: if we query A 1, get 5, which is not in T, that doesn't directly tell us intersection emptiness because 1 not in U, but we need more info. They reasoned that since they know S = {1,2,3} and T = {4,1,6}, and they got f(1)=5 not in T, they concluded that U does not contain 1. But they still needed to know if any other node could be common. How did they conclude? Possibly they used additional reasoning: Since T is of size 3, and they might know something about the tree structure? Actually from the problem statement: "In this case, you know that the only subtree of size 3 that doesn't contain node 1 is subtree 4,5,6." That's a specific property: The tree is such that any connected subtree of size 3 that does not contain node 1 must be exactly {4,5,6}. But that reasoning relies on knowledge of tree structure. In general, we cannot rely on such specific deductions. So their approach in sample might be tailored to that particular tree. But our algorithm is general and uses at most 2 queries, which is within 5. So it's fine.
Thus, the solution seems straightforward.
But wait: The problem statement mentions: "You can ask Andrew at most 5 questions". So with 2 queries we are safe.
But we must be careful about reading input and printing queries. Also note that after printing "C s", we should flush and then proceed to next test case. The input for next test case will then be provided.
Now, let's confirm correctness more formally:
-
The tree is known. S is known. U = f^{-1}(T) is unknown but known to be a connected subtree.
-
Claim: For any u ∈ U, let p = the unique vertex in S that minimizes dist(u, v) for v ∈ S. If S ∩ U ≠ ∅, then p ∈ U. Proof: Take any c ∈ S ∩ U. The unique path from u to c contains p (since p is the point where the path from u first hits S). Because u, c ∈ U and U is convex, the whole path is in U, so p ∈ U. Thus p ∈ S ∩ U. Conversely, if S ∩ U = ∅, then p ∉ U (since p ∈ S, and S ∩ U = ∅, so p ∉ U). So p ∈ U iff intersection non-empty.
Thus, by obtaining u ∈ U (via B query) and computing p, then testing p ∈ U (via A query), we determine intersection.
What if the B query returns u that is in S? Then u is in intersection, done.
Thus, algorithm is correct.
But is it always possible to compute p accurately? Yes, we have tree structure.
Now, we must ensure that we compute p correctly even if S is not convex? But S is guaranteed convex. So it's fine.
Potential issue: The projection of u onto S is computed based on distances in the tree. However, we need to ensure that p is indeed the unique node in S that is closest to u. That's straightforward.
Now, about implementation details:
-
For each test case, we read n, edges, build adjacency list.
-
Read k1, then read list of x_i; store them in a boolean array inS[1..n] = true for those.
-
Read k2, then read list of y_i; store them in a set (maybe boolean array inT[1..n]? But T is set of Li Chen's labels, which are from 1..n. We'll store them in a boolean array inT_y[1..n] for quick membership check of f(p) in T.
-
Then interaction:
- Choose y0 = y_1 (the first element). Print "B y0" and flush.
- Read integer u.
- If inS[u] then print "C u" flush; continue to next test case.
- Else compute p:
- Option 1: BFS from u to compute distances (or use DFS) to all nodes. Since n ≤ 1000, BFS O(n) fine.
- Find node with minimal dist among those with inS true. That is p. Could be multiple? but as argued unique, so we can take any.
- Print "A p" flush.
- Read integer v.
- If inT_y[v] then print "C p" flush; else print "C -1" flush.
That's it.
But we need to be careful: The query B y returns the label in our labeling for Li Chen's label y. So u is in [1,n]. We must ensure that we handle potential -1 response? The judge responds with -1 only if we exceeded queries or invalid query; otherwise, it's always a valid label. So we read u normally.
Now, what about the case when we query A p and get v, which is the Li Chen's label for our node p. That v is in [1,n]. We check if v ∈ T (the set of y_i). If yes, then p is common.
Edge case: What if we query B y0, and get u that is not in S. Then we compute p and query A p. But what if the intersection is empty, and p we computed is some node; we query A p and get v not in T, and output -1. That's correct.
But could there be a scenario where intersection is empty but p happens to be in U anyway? That would contradict the property we proved (p ∈ U iff intersection non-empty). Let's double-check the converse: If intersection empty, can p be in U? Suppose S and U are disjoint convex sets. Take u ∈ U. Let p be the projection of u onto S. Could p be in U? p is in S by definition, so if p were in U, then p would be in S∩U, contradicting disjoint. So no. So safe.
Thus algorithm is correct.
Now, is there any scenario where the B query we do might be invalid? No, y0 is from T, which is a valid label (1 ≤ y_i ≤ n). So B y0 is valid.
Now, think about query count: at most 2 per test case. But the problem allows up to 5. However, we must be careful: We might need to handle a case where the first chosen y0 gives u that is in S; that uses 1 query. Or if not, uses 2. So never exceed 2.
But there is a subtle case: What if k2 = 0? But constraints say k2 ≥ 1. So T non-empty.
Now, consider possibility of multiple test cases: we must reset data per test case.
Now, I'll think about if there is any pitfall with reading input after outputting answer. The interaction: after we print "C s", we flush, and then the judge will provide the next test case input if any. So we must read the next test case's first line (n) after that. But we need to be careful not to read beyond when t test cases are done. The input is provided all at once? Actually interactive problems with multiple test cases usually provide input as we go, but since we are reading from stdin, the entire input is given from start. However, because we are interacting, we need to read the input for each test case after we finish the previous. But the input for all test cases is initially in the input stream. We can still read it sequentially. So after we output answer for test case i, we then read the next test case's n. That's fine.
Now, regarding BFS: We'll need to compute distances from u to all nodes. Since n ≤ 1000, we can just run BFS from u each time. But we could also precompute LCA and depth to compute distances quickly. But BFS is simpler.
Implementation steps in code (C++):
- For each test case:
-
int n; cin >> n;
-
vector<vector> adj(n+1);
-
for i=1 to n-1: read a,b; add edge.
-
int k1; cin >> k1; vector S_nodes(k1); bool inS[n+1]={false}; for i=0..k1-1: cin >> x; inS[x]=true; S_nodes.push_back? maybe not needed.
-
int k2; cin >> k2; bool inT[n+1]={false}; vector T_nodes(k2); for i=0..k2-1: cin >> y; inT[y]=true; T_nodes.push_back(y); maybe store first y.
-
// choose y0 = T_nodes[0] (since k2>=1)
-
int y0 = T_nodes[0];
-
cout << "B " << y0 << endl; cout.flush();
-
int u; cin >> u; if (u == -1) exit(0); // error
-
if (inS[u]) { cout << "C " << u << endl; cout.flush(); continue; }
-
// BFS from u to compute distances and find p
-
vector dist(n+1, -1); queue q; dist[u]=0; q.push(u);
-
while(!q.empty()) { int v = q.front(); q.pop(); for(int w: adj[v]) if(dist[w]==-1) { dist[w]=dist[v]+1; q.push(w); } }
-
int p = -1, minDist = n+1;
-
for(int v=1; v<=n; ++v) if(inS[v] && dist[v] < minDist) { minDist = dist[v]; p = v; }
-
// p should be found.
-
cout << "A " << p << endl; cout.flush();
-
int v; cin >> v; if(v==-1) exit(0);
-
if(inT[v]) { cout << "C " << p << endl; } else { cout << "C -1" << endl; }
-
cout.flush();
That's the core.
But we should also consider that BFS from u may be unnecessary if we compute projection by walking along path to an arbitrary s. However, BFS is simple.
Now, test on a custom case:
Case: n=2, edge 1-2. S = {1} (k1=1, x=[1]). T = {2} (k2=1, y=[2]). Permutation unknown: suppose f(1)=2, f(2)=1. Then U = {2} (since f^{-1}(2)=1? Wait: T={2} in his labels. f^{-1}(2)=1. So U={1}. Actually intersection S∩U = {1}? S={1}, U={1} -> common. But our algorithm: pick y0=2, query B 2 -> u = f^{-1}(2) = 1. u in S, so output C 1. Works.
If permutation f(1)=1, f(2)=2, then U = {2} (since f^{-1}(2)=2). S={1}, U={2}, disjoint. Our algorithm: B 2 -> u=2. u not in S. BFS from u=2: distances: dist(2)=0, dist(1)=1. S nodes: node1 distance 1. So p=1. Query A 1 -> returns f(1)=1. Is 1 in T? T={2} -> no. So output -1. Correct.
Now, consider a more complex tree where S and U intersect at multiple nodes. Works.
Now, think about potential pitfalls: The projection p is unique. However, if u is in S we already handled. So BFS to find min distance will give that unique p. Good.
Now, think about case where S is not convex? But problem guarantees it is a subtree (connected induced subgraph), which is convex. So safe.
Now, what about the possibility that the tree has n=1000 and we run BFS for each test case maybe multiple times? At most 2 BFS? Actually we only need one BFS per test case (if u not in S). That's fine.
Now, consider reading input: Since t up to 100, total nodes across test cases up to 100*1000 = 100k, BFS each test case O(n) = 1000, so total O(100k) fine.
Now, we must also handle the case where the judge might respond with -1 indicating we did something wrong. In that case, we should exit.
Now, finalize solution.
But we should double-check if any hidden constraints could break the property that U is convex. The tree structure is the same, but the labeling of Li Chen is a permutation. So U = { f^{-1}(y) | y ∈ T }. Since the mapping f is a bijection on vertices, the induced subgraph on U is isomorphic to the induced subgraph on T via f. Since T is connected, U is connected. In a tree, connected induced subgraph is convex as argued. Yes.
Wait: Is it necessarily true that the induced subgraph on T is connected? The problem says "It is guaranteed that these vertices form a subtree." That means the vertices (in Li Chen's labeling) form a connected subgraph. So yes.
Thus U is a subtree.
Now, check the proof that projection of u onto S lies in U when intersection non-empty. This relied on convexity of U. But is U convex? In a tree, a connected induced subgraph is convex? Let's confirm: Suppose we have a connected induced subgraph U in a tree. Take two nodes a,b ∈ U. Since the induced subgraph is connected, there exists a path within U connecting them. In a tree, the unique simple path between a and b is the only simple path; if there is any path in the induced subgraph, it must be that unique path, meaning all intermediate nodes on the unique path are present in U. Therefore, U contains the whole path between any two of its vertices. Thus it is convex. So indeed any connected induced subgraph in a tree is convex.
Thus the property holds.
Therefore the algorithm is correct.
Now, why did the problem allow up to 5 queries? Possibly to let participants use a different approach like querying centers of S and T, or to handle some other nuance. But our solution uses only 2 and is simpler.
But we must be cautious: The sample second test case used A 1 directly (without B). Could there be a scenario where our algorithm fails because the chosen y0 yields u that is exactly the projection p? Actually that's fine. Let's examine: Suppose we pick y0, get u not in S. Then p is computed. If intersection non-empty, p ∈ U. But we will query A p. That's okay.
But could it be that u is chosen such that the projection p is not in U even though intersection non-empty? No, as argued.
One more nuance: The projection p is computed based on distances in the tree. But we assume that the distance metric is the same. Yes.
Thus solution is robust.
Now, we need to implement reading of input and interaction carefully.
Potential pitfalls: The input for each test case includes the tree edges, etc. After we output "C s", we should not have any leftover newline issues. Use endl for flushing.
Now, we should also consider that the B query might return a node that is not reachable? But all nodes are connected.
Edge Cases:
-
n=1: adjacency empty, S contains 1, T contains some y (must be 1). Our B query: B 1 -> u = f^{-1}(1). Since permutation must map the only node to 1, u=1. Then u in S -> output C 1. Works.
-
S or T size 1. Works.
Now, let's test with a custom case where intersection is a single node and u is far away.
Example: line 1-2-3-4-5. S = {3,4,5} (connected). T (in his labeling) corresponds to U = {1,2,3}. So intersection = {3}. Choose y0 from T, say y0 corresponding to node 1 (maybe). Suppose we pick y0 that maps to u=1 (not in S). BFS from u=1: distances to S: dist(3)=2, dist(4)=3, dist(5)=4. Min is 3? Actually 3 is distance 2? Wait: nodes: 1-2-3-4-5. S = {3,4,5}. Distances: to 3 =2, to 4=3, to 5=4. So p=3. Query A 3 -> f(3) should be in T (since 3 ∈ U). So v ∈ T. Output 3. Works.
If we had chosen y0 that maps to u=2, then u=2 not in S, distances: to 3=1, to4=2, to5=3 => p=3. Works.
Now, think about a case where S and U intersect in multiple nodes, but the projection might be one of them.
Thus algorithm is sound.
Now, confirm with another scenario: U and S are disjoint. Choose u in U. BFS gives p in S but not in U. Query A p -> v not in T. Output -1. Works.
Thus answer is straightforward.
But we should also consider if it's possible that after B query we get u, and then we compute p, but what if p equals u? That would mean u is in S? Because p is in S by definition. If u not in S, then u ∉ S, so p ≠ u because p ∈ S and u ∉ S. So p different.
Now, check for any off-by-one errors.
Implementation details:
We'll use vector< vector > g(n+1). Build.
We'll store inS and inT as boolean arrays.
We'll also store Tlist for choosing y0.
Now, BFS: we can use queue. Dist array of size n+1 initialized to -1. BFS from u, compute distances.
Then find p: iterate v from 1 to n, if inS[v] and (p==-1 or dist[v] < minDist) update.
But ensure that dist[v] is computed; all nodes reachable, tree is connected so all have distances.
Now, we output "C -1" if no intersection.
Now, be careful about reading response after queries: The judge will output an integer on a line. So we do int res; cin >> res;
Now, after finishing a test case, we need to flush output before reading next? Actually after we output "C s", we flush, and then the next test case input will be available. We can just read next n.
Now, we must also handle that after last test case, there is no more input; we can exit.
Now, test with sample 1:
Input:
1
3
1 2
2 3
1
1
1
2
We read n=3, edges, k1=1, S={1}, k2=1, T={2}. Choose y0=2. Output "B 2". Flush. The judge (simulated) should answer with u=1 (based on hidden permutation). We read 1. inS[1] true, so output "C 1". That's it. That matches expectation (though sample had extra query, but output is fine).
Now, sample 2 first test case: We already computed, algorithm would output C 3 (if u=3) or if we choose y0=2 we get u=3, then output C 3. But the sample output says C 1. However, both are correct. So judge should accept any common node. So fine.
Now, sample 2 second test case: Our algorithm would output B 4, then A 1, then C -1. That uses two queries, while sample used one query (A 1) and C -1. Both are acceptable as query count ≤5. But the sample output shows "A 1" then "C -1". So our output might be different but still correct.
One more nuance: The problem statement says: "You can ask Andrew at most 5 questions, each of which is in one of the following two forms: A x or B y." Then "When you are ready to answer, print "C s", where s is your label of a vertex that is common to both subtrees, or -1". So as long as we output a correct answer within query limit, it's fine. So our algorithm will be accepted.
Now, we must ensure that we handle the case where the first B query returns u that is -1? That indicates error, we should exit.
Now, there is a potential subtlety: The projection p we compute is the closest node in S to u. But we must be absolutely sure that if there is intersection, p is in U. The proof seems solid. However, is there any scenario where U is not convex? Let's double-check: U is the set of vertices whose Li Chen's label is in T. Since T is a subtree (connected induced subgraph) in Li Chen's labeling, and the mapping f is a permutation of vertices, U is exactly the set of vertices that correspond to T. Since the tree structure is identical, the induced subgraph on U is isomorphic to the induced subgraph on T via f. Because if two vertices a,b are adjacent in the tree, then in Li Chen's labeling they are adjacent as well (since the edges are defined by the underlying tree; the permutation just renames vertices). So adjacency is preserved: For any two vertices, they are adjacent in our labeling iff they are adjacent in Li Chen's labeling (since the underlying graph is same). So the induced subgraph on U is exactly the same as the induced subgraph on T, just relabeled. Thus if T is connected, U is connected. So U is a connected induced subgraph, hence convex. Good.
Now, the property that the projection of u onto S is in U when intersection non-empty holds as long as U is convex. Good.
Now, consider a pathological case: The tree is not a tree? It's a tree.
Thus final solution.
Now, I'm ready to write final answer.
But before finalizing, let's think about any possible alternative that could break due to the fact that the tree edges are given according to our labeling, and we use them to compute distances. That's fine.
Now, we should also consider that the BFS we run from u to compute distances might be affected if we haven't preprocessed the tree? But BFS from u will give correct distances.
Now, we should also be mindful of the fact that we might need to compute p quickly; BFS is O(n). For n=1000, fine.
Now, write code.
But before coding, let's test on more random cases with a script mentally: We'll generate a random tree, random permutation, random S and T subtrees, and simulate our algorithm.
Simulate small n=4:
Tree: edges: 1-2, 2-3, 3-4 (line). Permutation f: random, say [2,4,1,3] meaning: our1->2, our2->4, our3->1, our4->3.
Our S: random connected subtree: suppose S = {2,3} (connected). T: random subtree in his labeling: suppose T = {1,4}? Check connectivity: his labels 1 and 4: what are the corresponding nodes in his tree? His tree edges are same but labeled differently: his node 1 corresponds to our node? f(our3)=1, so his node 1 is our 3. His node 4 corresponds to our 2? f(our2)=4, so his node 4 is our 2. So T = {1,4} corresponds to U = {3,2} = {2,3} which is S. So intersection = S = {2,3}. Our algorithm: pick y0 from T, say 1. B 1 -> u = f^{-1}(1) = 3. u=3 is in S? Yes (S={2,3}), so output C 3. Works.
If T = {2,3} in his labels? Then f^{-1}(2)=1, f^{-1}(3)=4, so U={1,4}. S={2,3}. Intersection empty. Choose y0=2. B 2 -> u=1. u not in S. BFS from 1: distances to S: dist(2)=1? Actually edges: 1-2-3-4. S={2,3}. Distances: to 2 =1, to 3=2. So p=2. Query A 2 -> f(2)=4. Is 4 in T? T={2,3}? 4 not in T. So output -1. Correct.
Now, test a case where S and U intersect but the chosen u yields p that is not the only common node, but that's fine.
Now, test case where u is in S but not in U? That's impossible because u ∈ U by definition (since u = f^{-1}(y) for y ∈ T). So if u ∈ S, then u ∈ S∩U, so intersection non-empty. Good.
Now, test case where u is not in S, but the projection p is exactly a node that is not in U even though intersection exists? Suppose intersection exists. Could it be that the chosen u is such that the path from u to some c ∈ S∩U does not go through p? But p is defined as the closest node in S to u. For any c ∈ S∩U, the path from u to c must go through the unique point where it first hits S. That point is p. So p is on that path. Since u and c are in U, and U is convex, the whole path is in U, so p ∈ U. So yes.
Thus algorithm stands.
Now, implement.
One more nuance: The problem statement says: "The values of x_1, x_2, …, x_{k_1} and y_1, y_2, …, y_{k_2} are known to both of you." So we know the sets. In our algorithm we use T set membership to check if v (from A query) is in T. That's fine.
Now, think about input reading: After we output answer for test case i, the judge will provide the next test case's data. However, what about the case where we output -1? That's fine.
Now, test with sample input to ensure we parse correctly.
Let's manually parse sample 2 as described: It is ambiguous, but our code will parse based on the format. The input as given: first line t=2. Then:
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5
Our parser:
- Read n=6.
- Read 5 edges: (1,2),(1,3),(1,4),(4,5),(4,6)
- Read k1=4, then read 4 numbers: 1 3 4 5.
- Read k2=3, then read 3 numbers: 3 5 2.
- That completes first test case? But there is still "3" after that. Actually after reading the 3 numbers "3 5 2", the next integer is "3". That would be the n for next test case? If so, next test case has n=3. But then after that we have "6", which would be something else. So the sample input might be malformed in the statement; probably the "3" before "6" is actually part of the second test case's data? Let's try to interpret: Perhaps the second test case also has n=6, and the "3" is k1? The sequence: after first test case, we have "3" (maybe it's k1 for second test case?), then "6" is something else. Actually looking: after "3 5 2" (the y list) there is a newline, then "3", then newline, then "6". Possibly the second test case is:
n=3? But then edges: "6" ??? That doesn't fit. Alternatively, maybe the input is:
2
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5
I think the second test case is: n=3? But then edges would be missing. Actually it's more likely that the sample input is correct and the second test case also has n=6, but there is a stray "3". Let's parse as:
After first test case, the next lines are:
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5
Perhaps "3" is the k1 for the second test case? But then after that "6" would be the first edge? That doesn't align because after k1 we expect list of k1 numbers. Let's try:
Second test case:
n=3? But then we would have 2 edges. The next numbers after "3" are "6", "1", "2", ... That seems like n=6 again. So maybe the "3" is actually the n for the second test case? n=3, then edges: the next line "6 1"? No.
Better to search memory: I recall a Codeforces problem "Tree Queries" maybe problem 1292D? Actually I think it's Codeforces Round #1400 problem "Ehab and another another problem"? Not sure.
Let's search my memory: There is a Codeforces problem with name "Li Chen and Tree" or "Tree Queries" with 5 queries limit. I think it's CF Round #1092 E? Let's quickly recall: The problem described is exactly "Tree Queries" from CF Round #1311? I've seen something like this: "You have a tree with two labelings, ask up to 5 queries to find if subtrees intersect". I think the official solution uses exactly this technique: query a vertex from T to get its original label, then ask about the vertex in S that is closest to it. Yes, I remember a Codeforces editorial: "Take any vertex from the second set, ask its label in your tree. If it's inside your set, answer it. Else, find the vertex from your set closest to it and ask about its label in the second tree. If that label is in the second set, then answer that vertex, else answer -1." That's exactly our algorithm. So it's correct.
Thus, the sample input might be as we think, but it's okay.
Now, code.
Implementation in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<vector<int>> g(n+1);
for (int i = 0; i < n-1; ++i) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
int k1;
cin >> k1;
vector<bool> inS(n+1, false);
for (int i = 0; i < k1; ++i) {
int x;
cin >> x;
inS[x] = true;
}
int k2;
cin >> k2;
vector<bool> inT(n+1, false);
vector<int> Tlist(k2);
for (int i = 0; i < k2; ++i) {
int y;
cin >> y;
inT[y] = true;
Tlist[i] = y;
}
// query B for first element in Tlist
int y0 = Tlist[0];
cout << "B " << y0 << endl;
cout.flush();
int u;
cin >> u;
if (u == -1) return 0; // error
if (inS[u]) {
cout << "C " << u << endl;
cout.flush();
continue;
}
// BFS from u to compute distances
vector<int> dist(n+1, -1);
queue<int> q;
dist[u] = 0;
q.push(u);
while (!q.empty()) {
int v = q.front(); q.pop();
for (int w : g[v]) {
if (dist[w] == -1) {
dist[w] = dist[v] + 1;
q.push(w);
}
}
}
// find node in S with minimum distance
int p = -1, minDist = n+1;
for (int v = 1; v <= n; ++v) {
if (inS[v] && dist[v] < minDist) {
minDist = dist[v];
p = v;
}
}
// query A p
cout << "A " << p << endl;
cout.flush();
int v;
cin >> v;
if (v == -1) return 0;
if (inT[v]) {
cout << "C " << p << endl;
} else {
cout << "C -1" << endl;
}
cout.flush();
}
return 0;
}
But there is a small improvement: we don't need to store Tlist vector; we can just store first y while reading. But okay.
Now, confirm that we handle the case when the BFS yields p that may be unreachable? Tree is connected, so all nodes reachable.
Now, test with a custom case where k2 is large and we choose first element; fine.
Now, consider if the first element of Tlist might be a node that is not optimal, but it's okay.
Now, think about potential issue: The projection p might be such that the A query returns a label that is in T, but we output p; but what if p is not actually in intersection? That would mean our reasoning is wrong. But we trust.
Now, let's think about a pathological scenario: The tree is not a tree? It's a tree.
Now, final answer: Provide explanation and code.
But before finalizing, note: Some solutions might use an alternative approach where they query a vertex from S first, but ours is fine.
Now, confirm interaction formatting: Each query printed as "A x" or "B y" with a space, and newline. Answer as "C s". Flush after each.
Edge Cases:
-
What if after B query we get u that is -1? Then we should exit as per problem: "If the judge responds with -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate." So we exit.
-
Similarly for A query.
Now, code seems ready.
Now, think about potential pitfalls: The BFS might be heavy if we run for each test case many times, but it's fine.
Now, note: The tree is given with edges according to our labeling. So our adjacency list is correct.
Now, consider if the tree size n=1000 and we have up to 100 test cases, BFS each O(1000) yields 100k operations, trivial.
Now, confirm that the "inT" array we use is indexed by Li Chen's labels. When we get v from A p, it's a label in Li Chen's labeling. So checking inT[v] is correct.
Now, done.
Now, I'll produce final answer: Explanation of algorithm and code.
But before writing final response, I'll think if there is any scenario where the algorithm might fail because of the assumption that the projection of u onto S is in U when intersection exists. The proof used convexity of U. But is U necessarily convex? Let's double-check the definition: U = f^{-1}(T). T is a subtree in Li Chen's labeling, meaning the vertices in T induce a connected subgraph. In a tree, that means T is a convex set (since any induced connected subgraph contains all vertices on paths between its vertices). Because if two vertices are in T, the unique path between them must be fully in the induced subgraph for it to be connected (otherwise there would be a missing vertex and the induced subgraph would be disconnected). So T is convex. Now, does convexity transfer via a permutation? Since the permutation is a graph automorphism? No, it's just a renaming, not necessarily an automorphism? Wait, the permutation maps our vertex labels to his vertex labels, but the underlying tree structure is the same. However, the permutation is not necessarily an automorphism of the tree; it's a relabeling of the same underlying graph. Actually, consider the tree is the same physical tree. The permutation defines a bijection between our labels and his labels. But the edges are defined based on the physical connections. So if we take two physical vertices a and b that are adjacent, then in our labeling they have numbers a and b, and in his labeling they have numbers f(a) and f(b). So the edge set in his labeling is { (f(a), f(b)) | (a,b) is edge in our tree }. That means his graph is exactly the same graph but with vertices renamed. So the permutation f is a graph isomorphism from our labeled graph to his labeled graph. Therefore, f is an isomorphism, not necessarily an automorphism (since automorphism would map the graph to itself preserving labels, but here labels change). But as an isomorphism, it preserves all graph properties including distances, connectivity, convexity. Therefore, if T is convex in his graph, then U = f^{-1}(T) is convex in our graph because convexity is preserved under graph isomorphism. Indeed, if T is convex in his graph, then for any two nodes x,y in U, f(x), f(y) ∈ T, and the unique path between f(x) and f(y) lies entirely in T. Applying f^{-1}, the unique path between x and y lies entirely in U. So U is convex. So property holds.
Thus, algorithm is correct.
Now, one more nuance: The problem statement says: "Your subtree consists of the vertices labeled x_1, x_2, …, x_{k_1} in your labeling, Li Chen's subtree consists of the vertices labeled y_1, y_2, …, y_{k_2} in his labeling. The values of x_1, x_2, …, x_{k_1} and y_1, y_2, …, y_{k_2} are known to both of you." So we know T set as his labels. So our inT array is correct.
Now, consider if the tree has multiple components? No, it's a tree, connected.
Now, finalize.
I will produce final answer with explanation and code. ```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<vector<int>> g(n + 1);
for (int i = 0; i < n - 1; ++i) {
int a, b;
cin >> a >> b;
g[a].push_back(b);
g[b].push_back(a);
}
int k1;
cin >> k1;
vector<bool> inS(n + 1, false);
for (int i = 0; i < k1; ++i) {
int x;
cin >> x;
inS[x] = true;
}
int k2;
cin >> k2;
vector<bool> inT(n + 1, false);
vector<int> Tlist(k2);
for (int i = 0; i < k2; ++i) {
int y;
cin >> y;
inT[y] = true;
Tlist[i] = y;
}
// 1) get any vertex of U by asking about a vertex from T
int y0 = Tlist[0];
cout << "B " << y0 << endl;
cout.flush();
int u;
cin >> u;
if (u == -1) return 0; // invalid query – terminate
// if u is already in S, it is a common vertex
if (inS[u]) {
cout << "C " << u << endl;
cout.flush();
continue;
}
// 2) BFS from u to compute distances
vector<int> dist(n + 1, -1);
queue<int> q;
dist[u] = 0;
q.push(u);
while (!q.empty()) {
int v = q.front();
q.pop();
for (int w : g[v]) {
if (dist[w] == -1) {
dist[w] = dist[v] + 1;
q.push(w);
}
}
}
// find the vertex of S closest to u (the projection)
int p = -1, minDist = n + 1;
for (int v = 1; v <= n; ++v) {
if (inS[v] && dist[v] < minDist) {
minDist = dist[v];
p = v;
}
}
// 3) ask for the Li Chen label of p
cout << "A " << p << endl;
cout.flush();
int v;
cin >> v;
if (v == -1) return 0;
// if the answer belongs to T, then p is common; otherwise the intersection is empty
if (inT[v]) {
cout << "C " << p << endl;
} else {
cout << "C -1" << endl;
}
cout.flush();
}
return 0;
}