QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#734537 | #9570. Binary Tree | _LSA_ | TL | 0ms | 5956kb | C++14 | 2.4kb | 2024-11-11 12:20:48 | 2024-11-11 12:20:48 |
Judging History
answer
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define pii pair<int,int>
#define fi first
#define se second
#define mk make_pair
using namespace std;
ll read(){
ll X = 0 ,r = 1;
char ch = getchar();
while(!isdigit(ch) && ch != '-') ch = getchar();
if(ch == '-') r = -1,ch = getchar();
while(isdigit(ch)) X = X*10+ch-'0',ch = getchar();
return X*r;
}
int ask(int x,int y){
cout << "? " << x << " " << y << endl;
return read();
}
void answer(int x){
cout << "! " << x << endl;
}
const int N = 1e5+10;
int n;
vector<int> G[N];
int siz[N],rt,S,mn;
bool vis[N];
void getroot(int x,int ft){
siz[x] = 1;
int mxpart = 0;
for(int y : G[x]){
if(y == ft || vis[y]) continue;
getroot(y,x);
siz[x] += siz[y];
mxpart = max(mxpart,siz[y]);
}
mxpart = max(mxpart,S-siz[x]);
if(mxpart <= mn) rt = x,mn = mxpart;
}
void solve(int x){
for(int i=0;i<G[x].size();){
int y = G[x][i];
if(vis[y]) swap(G[x][i],G[x].back()),G[x].pop_back();
else i++;
}
vis[x] = true;
vector<int> v;
for(int y : G[x]){
rt = 0; S = mn = siz[y];
getroot(y,x);
v.push_back(rt);
// cout << rt << "\n";
}
assert(v.size() <= 3);
if(v.size() == 3){
int a = v[2],b = v[1];
int t = ask(a,b);
if(t == 0) return solve(a);
if(t == 2) return solve(b);
G[x].pop_back(); G[x].pop_back();
vis[x] = false;
return solve(v[0]);
}
if(v.size() == 1){
int y = v[0];
if(siz[y] == 1){
int t = ask(x,y);
if(t == 0) answer(x);
else answer(y);
return ;
}
vis[x] = false;
return solve(v[0]);
}
if(v.size() == 2){
int a = v[0],b = v[1];
int t = ask(a,b);
if(t == 0) return solve(a);
if(t == 2) return solve(b);
}
return answer(x);
}
void solve(){
n = read();
for(int i=1;i<=n;i++) G[i].clear(),vis[i] = false;
for(int i=1;i<=n;i++){
int u = read(),v = read();
if(u) G[i].push_back(u),G[u].push_back(i);
if(v) G[i].push_back(v),G[v].push_back(i);
}
mn = S = n; rt = 0;
getroot(1,0);
// cout << rt << "\n";
solve(rt);
}
int main(){
int T = read();
while(T--) solve();
return 0;
}
詳細信息
Test #1:
score: 100
Accepted
time: 0ms
memory: 5956kb
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
Time Limit Exceeded
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 2 2 2 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0 0 0
output:
? 6 8 ? 4 5 ? 4 3 ! 4 ? 2 5 ? 7 8 ? 8 6 ! 6 ? 3 6 ? 3 7 ! 3