QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#862216 | #9570. Binary Tree | 2018ljw# | ML | 0ms | 13956kb | C++14 | 2.0kb | 2025-01-18 23:04:30 | 2025-01-18 23:04:31 |
Judging History
answer
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ft fflush(stdout)
using namespace std;
int n,hed[1000001],net[2000001],ver[2000001],tot;
void add(int x,int y){
ver[++tot]=y;
net[tot]=hed[x];
hed[x]=tot;
}
bool cut[1000001];
int sz[1000001],son[1000001],deg[1000001];
int qr(int x,int y){
ft;
printf("? %d %d\n",x,y);
ft;
int res;
scanf("%d",&res);
ft;
return res;
}
void dfs0(int x,int fr){
sz[x]=1;son[x]=0;
int i;
for(i=hed[x];i;i=net[i]){
int y=ver[i];
if(y==fr||cut[y])continue;
dfs0(y,x);
sz[x]+=sz[y];
if(sz[y]>=sz[son[x]])son[x]=y;
}
}
int findh(int x,int ps){
while(son[x]&&sz[son[x]]>ps/2)x=son[x];
return x;
}
void dfs(int x){
int i;
dfs0(x,0);
cut[x]=1;
for(i=hed[x];i;i=net[i]){
int y=ver[i];
if(cut[y])deg[x]--;
}
if(!deg[x]){
ft;
printf("! %d\n",x);
ft;
return;
}
int f1=0,f2=0,f3=0;
for(i=hed[x];i;i=net[i]){
int y=ver[i];
if(cut[y])continue;
if(!f1)f1=y;
else if(!f2)f2=y;
else f3=y;
}
if(deg[x]==1){
ft;
int res=qr(x,f1);
if(!res)printf("! %d\n",x);
else printf("! %d\n",f1);
ft;
return;
}
if(deg[x]==2){
ft;
int res=qr(f1,f2);
if(res==0)dfs(findh(f1,sz[f1]));
else if(res==1)printf("! %d\n",x);
else dfs(findh(f2,sz[f2]));
ft;
return;
}
int mn=min(sz[f1],min(sz[f2],sz[f3]));
if(sz[f1]==mn)f1^=f3^=f1^=f3;
else if(sz[f2]==mn)f2^=f3^=f3^=f3;
int res=qr(f1,f2);
if(res==1){
cut[x]=0;
cut[f1]=cut[f2]=1;
dfs0(x,0);
dfs(findh(x,sz[x]));
return;
}
if(res==0)dfs(findh(f1,sz[f1]));
else dfs(findh(f2,sz[f2]));
}
void solve(){
int i,j;
scanf("%d",&n);
tot=0;
for(i=1;i<=n;i++)cut[i]=deg[i]=hed[i]=0;
for(i=1;i<=n;i++){
int x,y;
scanf("%d%d",&x,&y);
if(x){
add(i,x);add(x,i);
deg[x]++;deg[i]++;
}
if(y){
add(i,y);add(y,i);
deg[y]++;deg[i]++;
}
}
ft;
dfs0(1,0);
dfs(findh(1,n));
}
int main(){
int t;
scanf("%d",&t);
while(t--)solve();
}
详细
Test #1:
score: 100
Accepted
time: 0ms
memory: 13956kb
input:
2 5 0 0 1 5 2 4 0 0 0 0 1 0 2 0 2 0 0 2
output:
? 3 5 ? 2 1 ! 2 ? 1 2 ! 2
result:
ok OK (2 test cases)
Test #2:
score: -100
Memory 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 0 0 2 8 5 8 0 0 1 7 0 0 0 0 4 2 0 0 6 0 2 1 2 5 4 5 3 1 0 0 0 0 0 0 0 0 8 0 0 0 0 5 6 0 0 1 4 2 0 3 8 0 0 0 2 5 3 0 5 1 0 0 0 0 4 0 0 0 5 5 0 0 0 0 0 3 0 2 4 1 2 3 3 0 1 0 0 0 2 2 2 0 0 0 2 3 2 3 0 0 0 0 2 10 2 8 9 7 0 0 ...
output:
? 6 8 ? 4 5 ? 4 3 ! 4 ? 7 2 ? 8 7 ? 8 6 ! 6 ? 3 8 ? 4 2 ? 6 8 ! 8 ? 2 5 ? 2 3 ! 2 ? 5 6 ? 4 1 ! 1 ? 1 5 ? 1 3 ! 1 ? 4 2 ? 5 1 ! 1 ? 2 3 ! 3 ? 1 2 ! 2 ? 3 2 ! 2 ? 7 9 ? 7 3 ? 7 5 ! 7 ? 1 2 ! 1 ? 9 5 ? 4 8 ? 3 5 ! 3 ? 10 3 ? 8 2 ? 8 10 ! 10 ? 9 4 ? 6 5 ? 3 8 ! 8 ? 1 2 ! 2 ? 4 3 ? 7 1 ! 1 ? 4 9 ? 4 8 ?...