Author: Speedster1010
Required Knowledge : Interactive, Implementation
Time Complexity :
Editorialist : Speedster1010
This problem might sound complex with all the “timelines” and “Infinity Stones,” but it’s actually about exploring a binary tree interactively. Each junction can branch left (L) or right (R), and one hidden junction contains the stone.
At every junction, we can ask TVA whether the stone lies in its left or right branch. TVA responds with:
The next junction (or if it doesn’t exist), and
if the stone is somewhere in that branch, otherwise.
We start at junction and keep following whichever branch says . If both branches return , it means the stone is at the current junction.
The algorithm is simple:
Begin at node .
Ask about the left branch — if , move there.
Otherwise, ask about the right branch — if , move there.
If both return , print the current node as the answer.
This guarantees the correct junction in at most queries, as we only explore each branch once.
#include <iostream>
#include <string>
#include <vector>
#include <utility>
using namespace std;
pair<int, string> ask(int junction, char direction) {
cout << "? " << junction << " " << direction << endl;
int next_junction;
string response;
cin >> next_junction >> response;
return { next_junction, response };
}
void solve() {
int n;
cin >> n;
int node = 1;
while(true) {
int next_junction;
string response;
auto result_left = ask(node, 'L');
next_junction = result_left.first;
response = result_left.second;
if(response == "YES") {
node = next_junction;
continue;
}
auto result_right = ask(node, 'R');
next_junction = result_right.first;
response = result_right.second;
if(response == "YES") {
node = next_junction;
continue;
}
cout << "! " << node << endl;
break;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--) {
solve();
}
return 0;
}