QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#793265 | #9570. Binary Tree | Sunwking | RE | 0ms | 0kb | C++20 | 3.6kb | 2024-11-29 18:06:15 | 2024-11-29 18:06:16 |
answer
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
using PII = pair<int , int>;
void solved() {
int n;
cin >> n;
vector<vector<int>> g(n + 1);
int nn = n;
auto add = [&](int a , int b){
g[a].push_back(b);
g[b].push_back(a);
};
auto ask = [&](int u , int v){
cout << "? " << u << " " << v << endl;
cout.flush();
int x;
cin >> x;
return x;
};
for(int i = 1 ; i <= n ; i ++ ){
int x , y;
cin >> x >> y;
if(x) add(i , x);
if(y) add(i , y);
}
auto find = [&](int x){
vector<int> cnt(nn + 1) , sum(nn + 1) , st(nn + 1);
int mx = 1e9 , k = 0;
auto dfs = [&](auto f , int u) -> int {
st[u] = true;
for(int v : g[u]){
if(st[v]) continue;
int s = f(f , v);
sum[u] += s;
cnt[u] = max(cnt[u] , s);
}
cnt[u] = max(cnt[u] , n - sum[u] - 1);
if(mx > cnt[u]){
mx = cnt[u];
k = u;
}
return sum[u] + 1;
};
dfs(dfs , x);
return k;
};
int last = 1;
while(1){
if(n == 1){
cout << "! " << last << endl;
cout.flush();
return ;
}
int x = find(last);
cout << "! " << x << endl;
cout.flush();
return ;
// cout << x << endl;
if(g[x].size() == 0){
cout << "! " << x << endl;
cout.flush();
return ;
}
if(g[x].size() == 1){
int t = ask(x , g[x][0]);
int ans;
if(t == 0) ans = x;
else ans = g[x][0];
cout << "! " << ans << endl;
cout.flush();
return ;
}
if(g[x].size() == 2){
cout << "! " << x << endl;
cout.flush();
return ;
auto a = g[x];
int t = ask(x , a[0]);
g[x].clear();
if(t == 0){
last = a[1];
g[a[1]].erase(std::find(g[a[1]].begin(), g[a[1]].end(),x));
}else last = a[0] , g[a[0]].erase(std::find(g[a[0]].begin(), g[a[0]].end(),x));
}
if(g[x].size() == 3){
cout << "! " << x << endl;
cout.flush();
return ;
// auto a = g[x];
// int t = ask(a[0] , a[1]);
// g[x].clear();
// if(t == 0) {
// last = a[0];
// g[a[0]].erase(std::find(g[a[0]].begin(), g[a[0]].end(),x));
// }else if(t == 1){
// last = a[2];
// g[a[2]].erase(std::find(g[a[2]].begin(), g[a[2]].end(),x));
// }else { last = a[1];
// g[a[1]].erase(std::find(g[a[1]].begin(), g[a[1]].end(),x));
// }
}
vector<int> st(nn + 1);
n = 0;
auto dfs = [&](auto f , int u) -> void{
st[u] = true;
n ++;
for(int x : g[u]){
if(st[x]) continue;
f(f , x);
}
};
dfs(dfs , last);
// for(int i = 1 ; i <= nn ; i ++ )
// for(int x : g[i])
// cout << i << " " << x << endl;
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
cin >> t;
while(t -- )
solved();
return 0;
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 0
Runtime Error
input:
2 5 0 0 1 5 2 4 0 0 0 0
output:
! 2