QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#758252 | #9570. Binary Tree | Yuu | RE | 0ms | 3512kb | C++23 | 2.5kb | 2024-11-17 17:09:32 | 2024-11-17 17:09:33 |
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);
for(int i = 1;i <= n;i++){
int l, r;
std::cin>>l>>r;
if(l) G[l].insert(i), G[i].insert(l);
if(r) G[r].insert(i), G[i].insert(r);
}
auto dfs = [&](auto& self, int u)->void{
for(auto v : G[u]){
G[v].erase(u);
self(self, v);
}
};
dfs(dfs, 1);
std::vector<int>vec;
int f = 1;
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());
};
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<<"! "<<t<<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: 0ms
memory: 3512kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 0 2 0 2 0 0 2
output:
? 3 5 ? 1 2 ! 1 ? 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 2 1 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0
output:
? 6 8 ? 4 5 ? 4 3 ! 4 ? 3 4 ? 3 6 ? 5 6 ! 8 ! 1