QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#863853#9570. Binary TreeQianTL 1ms6144kbC++141.9kb2025-01-20 00:18:292025-01-20 00:18:30

Judging History

你现在查看的是最新测评结果

  • [2025-01-20 00:18:30]
  • 评测
  • 测评结果:TL
  • 用时:1ms
  • 内存:6144kb
  • [2025-01-20 00:18:29]
  • 提交

answer

#include<bits/stdc++.h>
using namespace std;
int read(){
	int num=0;bool flag=1;
	char c=getchar();
	for(;c<'0'||c>'9';c=getchar())
		if(c=='-')flag=0;
	for(;c>='0'&&c<='9';c=getchar())
		num=(num<<1)+(num<<3)+c-'0';
	return flag?num:-num;
}
const int N=1e5+10;
vector<int>e[N];
int n,sz[N],nown,hvrt,pp;
void dfs(int x,int fa1,int fa2){
	sz[x]=1;int Max=0;
	for(auto y:e[x]){
		if(y==fa1||y==fa2)continue;
		dfs(y,x,x);sz[x]+=sz[y];
		Max=max(Max,sz[y]);
	}
	Max=max(Max,nown-sz[x]);
	if(Max<pp){
		hvrt=x;
		pp=Max;
	}
}
int ask(int x,int y){
	fflush(stdout);
	printf("? %d %d\n",x,y);
	fflush(stdout);
	int u=read();
	fflush(stdout);
	return u;
}
signed main(){
	int T=read();
	while(T--){
		n=read();
		for(int i=1;i<=n;i++){
			e[i].clear();
		}
		for(int i=1;i<=n;i++){
			int l=read(),r=read();
			if(l){
				e[i].push_back(l);
				e[l].push_back(i);
			}
			if(r){
				e[i].push_back(r);
				e[r].push_back(i);
			}
		}
		fflush(stdout);
		int rt=1,fa1=0,fa2=0;nown=n;
		while(1){
			pp=INT_MAX;
			dfs(rt,fa1,fa2);
			vector<array<int,2>>kk;
			for(auto y:e[hvrt]){
				if(y==fa1||y==fa2)continue;
				if(sz[y]<sz[hvrt])
					kk.push_back({sz[y],y});
				else kk.push_back({nown-sz[hvrt],y});
			}
			sort(kk.begin(),kk.end());
			reverse(kk.begin(),kk.end());
			if(kk.size()==1){
				int dis=ask(kk[0][1],hvrt);
				if(dis==0)printf("! %d\n",kk[0][1]);
					else printf("! %d\n",hvrt);
				break;
			}
			else{
				int dis=ask(kk[0][1],kk[1][1]);
				if(dis==0){
					rt=kk[0][1];
					fa1=fa2=hvrt;
					nown=kk[0][0];
				}
				else if(dis==1){
					rt=hvrt;
					fa1=kk[0][1];
					fa2=kk[1][1];
					if(kk.size()==2)nown=1;
					else nown=kk[2][0]+1;
				}
				else{
					rt=kk[1][1];
					fa1=fa2=hvrt;
					nown=kk[1][0];
				}
			}
			if(nown==1){
				printf("! %d\n",rt);
				break;
			}
		}
		fflush(stdout);
	}
	return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 100
Accepted
time: 1ms
memory: 6144kb

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
Time Limit Exceeded

input:

5555
8
2 0
8 6
0 0
3 0
0 0
7 0
0 0
5 4
0
0
2
8
0 0
1 4
2 0
0 0
7 8
0 0
3 0
6 0
0
1
0
8
5 8
0 0
1 7
0 0
0 0
4 2
0 0
6 0
0
0
2
5
4 5
3 1
0 0
0 0
0 0
0
2
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
0
2
5
5 0
0 0
0 0
3 0
2 4
0
0
3
3 0
1 0
0 0
2
2
2 0
0 0
0
3
2 3
0 0
0 0
2
10
2 8
9 7
0 0
...

output:

? 2 4
? 2 7
? 2 1
! 1
? 3 5
? 4 3
? 2 1
! 2
? 1 6
? 1 7
? 1 5
! 5
? 2 5
? 2 3
! 3
? 5 7
? 4 1
! 4
? 5 1
? 5 4
! 4
? 4 2
? 4 3
! 4
? 3 2
! 2
? 1 2
! 1
? 3 2
! 2
? 2 6
? 9 1
? 1 8
! 8
? 1 2
! 1
? 9 5
? 9 6
? 3 4
! 3

result: