QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#769097 | #9570. Binary Tree | kisaki | TL | 0ms | 0kb | C++14 | 1.9kb | 2024-11-21 16:04:42 | 2024-11-21 16:04:49 |
answer
#include<cstdio>
#include<iostream>
#include<algorithm>
#define INF 0x3f3f3f3f
#define N 100010
typedef long long ll;
int t,n,root;
bool vis[N];
int l[N],r[N],fa[N],size[N],dl[5],cnt;
void dfs_size(int p){
size[p]=1;
if(l[p])dfs_size(l[p]),size[p]+=size[l[p]];
if(r[p])dfs_size(r[p]),size[p]+=size[r[p]];
}
int max(int a,int b,int c){
return std::max(a,std::max(b,c));
}
int pos;
void minn(int p,int min){
if(max(size[l[p]],size[r[p]],size[root]-size[l[p]]-size[r[p]])<min&&((fa[p]&&l[p])||(fa[p]&&r[p])||(l[p]&&r[p]))){
min=max(size[l[p]],size[r[p]],size[root]-size[l[p]]-size[r[p]]);
pos=p;
}
if(l[p])minn(l[p],min);
if(r[p])minn(r[p],min);
}
int main(){
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i=1;i<=n;i++)vis[i]=0,size[i]=0,fa[i]=0;
for(int i=1;i<=n;i++)scanf("%d%d",&l[i],&r[i]),fa[l[i]]=fa[r[i]]=i;
for(int i=1;i<=n;i++){
if(!fa[i]){
root=i;
break;
}
}
int st;
dfs_size(root);
while(size[root]>2){
dfs_size(root);
minn(root,INF);
if(l[pos]&&r[pos]){//d=2 or 3
std::cout<<"? "<<l[pos]<<" "<<r[pos];std::cout.flush();
scanf("%d",&st);
if(st==0)root=l[pos],fa[root]=0;
else if(st==2)root=r[pos],fa[root]=0;
else l[pos]=r[pos]=0;
}
else if(l[pos]){
std::cout<<"? "<<l[pos]<<" "<<fa[pos];std::cout.flush();
scanf("%d",&st);
if(st==0)root=l[pos],fa[root]=0;
else l[pos]=r[pos]=0;
}
else if(r[pos]){
std::cout<<"? "<<r[pos]<<" "<<fa[pos];std::cout.flush();
scanf("%d",&st);
if(st==0)root=r[pos],fa[root]=0;
else l[pos]=r[pos]=0;
}
}
if(size[root]==1){
std::cout<<"! "<<root;std::cout.flush();
}
else{
int qwq=std::max(l[root],r[root]);
std::cout<<"? "<<qwq<<" "<<root;std::cout.flush();
scanf("%d",&st);
if(st==0){
std::cout<<"! "<<qwq;std::cout.flush();
}
else{
std::cout<<"! "<<root;std::cout.flush();
}
}
}
return 0;
}
詳細信息
Test #1:
score: 0
Time Limit Exceeded
input:
2 5 0 0 1 5 2 4 0 0 0 0
output:
? 2 4