QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#811798 | #9570. Binary Tree | Insert_Username_Here | TL | 0ms | 0kb | C++20 | 1.6kb | 2024-12-13 01:24:44 | 2024-12-13 01:24:54 |
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(ch[i].f < 0 && ch[i].s < 0) return i;
if(ch[i].f < 0 || ch[i].s < 0) {
if(ch[i].f < 0) swap(ch[i].f, ch[i].s);
if(sz[r] - sz[ch[i].f] < sz[ch[i].f]) return bk(ch[i].f, r);
if(qry(i, ch[i].f)) return bk(ch[i].f, ch[i].f);
sz[i] -= sz[ch[i].f], ch[i].f = -1;
return bk(r, r);
}
if(sz[ch[i].f] < sz[ch[i].s]) swap(ch[i].f, ch[i].s);
if(sz[r] - sz[i] + 1 < sz[ch[i].f] + sz[ch[i].s]) return bk(ch[i].f, r);
int ans = qry(ch[i].f, ch[i].s);
if(ans == 0) return bk(ch[i].f, ch[i].f);
if(ans == 2) return bk(ch[i].s, ch[i].s);
sz[i] = 1, ch[i] = {-1, -1};
return bk(r, 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();
}
}
詳細信息
Test #1:
score: 0
Time Limit Exceeded
input:
2 5 0 0 1 5 2 4 0 0 0 0 1
output:
? 1 5 ! 2