QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#758315 | #9570. Binary Tree | Yuu | RE | 1ms | 3488kb | C++23 | 3.0kb | 2024-11-17 17:42:10 | 2024-11-17 17:42:11 |
Judging History
answer
#include<bits/stdc++.h>
using namespace std;
using i64 = long long;
// The 2024 ICPC Asia Nanjing Regional Contest
int ask(int u, int v){
std::cout<<"? "<<u<<" "<<v<<endl;
int res; std::cin>>res;
return res;
}
void sol(){
int n; std::cin>>n;
const int K = std::__lg(n);
std::vector<std::set<int>>G(n + 1);
std::vector<int>vis(n + 1);
for(int i = 1;i <= n;i++){
int l, r;
std::cin>>l>>r;
if(l) {
G[i].insert(l);
G[l].insert(i);
vis[l] = 1;
}
if(r) {
G[i].insert(r);
G[r].insert(i);
vis[r] = 1;
}
}
int root = 0;
for(int i = 1;i <= n;i++){
if(vis[i] == 0){
root = i;
break;
}
}
std::vector<std::vector<int>>del(n + 1);
auto dfs = [&](auto& self, int u, int pa = 0)->void{
for(auto v : G[u]) {
if(v == pa) continue ;
del[v].push_back(u);
self(self, v, u);
}
};
dfs(dfs, root);
for(int i = 1;i <= n;i++){
for(auto u : del[i]){
G[i].erase(u);
}
}
std::vector<int>vec;
int f = root;
auto DFS = [&](auto&self, int u)->void{
vec.push_back(u);
if(G[u].size() == 2) return ;
if(G[u].size() == 1) self(self, *G[u].begin());
return ;
};
while(G[f].size()){
if(G[f].size() == 2){
int ls = *G[f].begin(), rs = *G[f].rbegin();
int t = ask(ls, rs);
if(t == 1){
std::cout<<"! "<<f<<endl;
return ;
}
f = (t == 0?ls : rs);
}else{
vec.clear();
DFS(DFS, f);
if(vec.size() == 1){
std::cout<<"! "<<vec.back()<<endl;
return ;
}else {
int last = vec.back();
if(G[last].size() == 2){
int ls = *G[last].begin(), rs = *G[last].rbegin();
int t = ask(ls, rs);
if(t != 1){
f = (t == 0?ls : rs);
continue ;
}
}
// s在 vec[]内
int l = 0, r = vec.size() - 1;
while(l + 1 != r){
int t = ask(vec[l], vec[r]);
if(t == 1){
std::cout<<"! "<<vec[(l + r) / 2]<<endl;
return ;
}
int mid = l + r >> 1;
if(t == 0) r = mid; else l = mid;
}
int t = ask(vec[l], vec[r]);
std::cout<<"! "<<(t == 0?vec[l]:vec[r])<<endl;
return ;
}
}
}
std::cout<<"! "<<f<<endl;
}
int main(){
ios::sync_with_stdio(0),cin.tie(0), cout.tie(0);
int t = 1; std::cin>>t;
while(t--) sol();
return 0;
}
详细
Test #1:
score: 100
Accepted
time: 1ms
memory: 3488kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 0 1 2 0 2 0 0 2
output:
? 2 4 ? 1 5 ! 2 ? 1 2 ! 2
result:
ok OK (2 test cases)
Test #2:
score: -100
Runtime Error
input:
5555 8 2 0 8 6 0 0 3 0 0 0 7 0 0 0 5 4 2 0 0 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 0 1 1 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0 0 2 1
output:
? 6 8 ? 4 5 ? 4 3 ! 4 ? 7 8 ? 1 4 ? 7 2 ! 3 ? 1 7 ? 5 8 ? 2 4 ? 8 6