QOJ.ac
QOJ
ID | Problem | Submitter | Result | Time | Memory | Language | File size | Submit time | Judge time |
---|---|---|---|---|---|---|---|---|---|
#811865 | #9570. Binary Tree | Insert_Username_Here | TL | 1ms | 3636kb | C++20 | 1.8kb | 2024-12-13 05:59:53 | 2024-12-13 05:59:54 |
Judging History
answer
#include <bits/stdc++.h>
#define f first
#define s second
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pii;
// const ll mod = 1e9 + 7;
// #include <brawlstars>
// FOR PAIN OR FOR GLORYYY ELLL PRIMOOOOOO
const int N = 1e5 + 1;
pii ch[N];
int sz[N], p[N];
int dfs(int i) {
if(i < 0) return 0;
sz[i] = 1 + dfs(ch[i].f) + dfs(ch[i].s);
return sz[i];
}
int qry(int i, int j) {
cout << "? " << i + 1 << " " << j + 1 << "\n";
cout.flush();
int ans;
cin >> ans;
return ans;
}
int bk(int i, int r) {
if(sz[r] == 1) return i;
if(sz[r] == 2) {
int c = (ch[i].f >= 0 ? ch[r].f : ch[r].s);
if(qry(r, c)) return c;
return r;
}
if(ch[i].f < 0) swap(ch[i].f, ch[i].s);
else if(sz[ch[i].f] < sz[ch[i].s]) swap(ch[i].f, ch[i].s);
int smax = sz[r] / 2;
if(sz[r] - sz[ch[i].f] > smax) {
if(i == r) {
int ans = qry(ch[i].f, ch[i].s);
if(ans == 1) return i;
if(ans == 0) return bk(ch[i].f, ch[i].f);
return bk(ch[i].s, ch[i].s);
}
int ans = qry(p[i], ch[i].f);
if(ans == 2) return bk(ch[i].f, ch[i].f);
if(ans == 1) {
sz[i] -= sz[ch[i].f], ch[i].f = -1;
return bk(i, i);
}
int u = p[i];
if(ch[u].f == i) ch[u].f = -1;
else ch[u].s = -1;
while(p[u] != r) sz[u] -= sz[i], u = p[u];
sz[u] -= sz[i];
return bk(u, u);
}
return bk(ch[i].f, r);
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while(t--) {
int n;
cin >> n;
for(int i = 0; i < n; i++) p[i] = -1;
for(int i = 0; i < n; i++) {
cin >> ch[i].f >> ch[i].s;
ch[i].f--, ch[i].s--;
if(ch[i].f >= 0) p[ch[i].f] = i;
if(ch[i].s >= 0) p[ch[i].s] = i;
}
int r = 0;
while(p[r] >= 0) r = p[r];
dfs(r);
int ans = bk(r, r);
cout << "! " << ans + 1 << "\n";
cout.flush();
}
}
Details
Tip: Click on the bar to expand more detailed information
Test #1:
score: 100
Accepted
time: 1ms
memory: 3636kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 0 2 0 2 0 0 2
output:
? 3 1 ? 2 5 ! 2 ? 1 2 ! 2
result:
ok OK (2 test cases)
Test #2:
score: -100
Time Limit Exceeded
input:
5555 8 2 0 8 6 0 0 3 0 0 0 7 0 0 0 5 4 0 0
output:
? 2 4 ? 2 7