QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#778239 | #9570. Binary Tree | Lanthanmum | TL | 1ms | 3612kb | C++20 | 2.2kb | 2024-11-24 13:32:36 | 2024-11-24 13:32:44 |
Judging History
answer
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int N = 1e5 + 9;
int mxs, sum, n,rt;
int flag;
int del[N], sz[N];
vector<int> e[N];
auto ask(int u, int v) {
cout << "?" << " " << u << " " << v << endl;
int x;
cin >> x;
return x;
};
auto ok(int x) {
cout << "!" << " " << x << endl;
};
void add(int u, int v) {
e[u].push_back(v);
e[v].push_back(u);
}
void getroot(int u, int f,int &rt) {
sz[u]=1;
int s = 0;
for (auto &i : e[u]) {
if (i == f || del[i]) {
continue;
}
getroot(i, u,rt);
sz[u] += sz[i];
s = max(s, sz[i]);
}
s = max(s, sum - sz[u]);
if (s < mxs) {
mxs = s;
rt = u;
}
}
int getsize(int u,int f){
if(del[u])return 0;
int res=1;
for(auto & i : e[u]){
if(i==f)continue;
res+=getsize(i,u);
}
return res;
}
void dfs(int u) {
if (flag) {
return;
}
if (del[u]) {
return;
}
sum=getsize(u,0);
mxs=n;
getroot(u,0,u);
vi t;
for (auto &i : e[u]) {
if (!del[i]) {
t.push_back(i);
}
}
int SZ = t.size();
if (!SZ) {
ok(u);
} else if (SZ == 1) {
int x = ask(u, t[0]);
if (!x) {
ok(u);
} else {
ok(t[0]);
}
} else if (SZ == 2) {
int x = ask(t[0], t[1]);
if (x == 1) {
ok(u);
}else if(x == 0) {
del[u]=1;
dfs(t[0]);
return;
}else{
del[u]=1;
dfs(t[1]);
}
} else {
vector<pii> v;
for(int i=0;i<3;i++){
v.push_back({t[i],getsize(t[i],u)});
}
sort(v.begin(),v.end(),[](const pii &a,const pii &b){
return a.second>b.second;
});
vi tt;
for(auto &[x,y] : v){
tt.push_back(x);
}
int x=ask(tt[0],tt[1]);
if(!x){
del[u]=1;
dfs(tt[0]);
}else if(x==1){
del[tt[0]]=del[tt[1]]=1;
dfs(rt);
}else{
del[u]=1;
dfs(tt[1]);
}
}
return;
}
void solve() {
cin >> n;
for(int i=1;i<=n;i++){
e[i].clear();
sz[i]=0,del[i]=0;
}
for (int i = 1; i <= n; i++) {
int u, v;
cin >> u >> v;
if (u) {
add(u, i);
}
if (v) {
add(v, i);
}
}
mxs = n, sum = n;
getroot(1,0,rt);
dfs(rt);
};
int main() {
int t;
cin >> t;
while (t--) {
flag = 0;
solve();
}
return 0;
}
詳細信息
Test #1:
score: 100
Accepted
time: 1ms
memory: 3612kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 0 2 0 2 0 0 2
output:
? 3 1 ? 5 2 ! 5 ? 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 2 0 8 0 0 1 4 2 0 0 0 7 8 0 0 3 0 6 0 2 0 2 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0 0 1 0 5 4 5 3 1 0 0 0 0 0 0 1 0 8 0 0 0 0 5 6 0 0 1 4 2 0 3 8 0 0 0 0 5 3 0 5 1 0 0 0 0 4 0 2 0 5 5 0 0 0 0 0 3 0 2 4 0 2 3 3 0 1 0 0 0 1 2 2 0 0 0 2 3 2 3 0 0 0 0 2 10 2 8 9 7 0 0 ...
output:
? 8 6 ? 3 8 ? 5 8 ! 5 ? 2 7 ? 5 6 ? 7 5 ! 5 ? 8 3 ? 4 2 ? 6 8 ! 6 ? 2 4 ? 5 1 ! 5 ? 5 6 ? 1 4 ! 1 ? 5 1 ? 3 1 ! 3 ? 4 1 ? 3 4 ! 4 ? 3 2 ! 1 ? 1 2 ! 2 ? 2 3 ! 3 ? 7 1 ? 7 4