QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#729024#9570. Binary Treeucup-team3661#RE 1ms3768kbC++202.0kb2024-11-09 16:22:362024-11-09 16:22:38

Judging History

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

  • [2024-11-09 16:22:38]
  • 评测
  • 测评结果:RE
  • 用时:1ms
  • 内存:3768kb
  • [2024-11-09 16:22:36]
  • 提交

answer

#include<bits/stdc++.h>
using namespace std;

int N;
vector<int>G[1<<17];
int seen[1<<17],sz[1<<17];

int cent(int root){
	auto dfs=[&](auto&&dfs,int now,int pre)->int{
		sz[now]=1;
		for(int nxt:G[now]){
			if(nxt==pre||seen[nxt])continue;
			sz[now]+=dfs(dfs,nxt,now);
		}
		return sz[now];
	};
	int total=dfs(dfs,root,-1);
	int cent=root;
	auto dfs2=[&](auto&&dfs2,int now,int pre)->void{
		bool ok=(total-sz[now])*2<=total;
		for(int nxt:G[now]){
			if(nxt==pre||seen[nxt])continue;
			dfs2(dfs2,nxt,now);
			if(sz[nxt]*2>total)ok=false;
		}
		if(ok)cent=now;
	};
	dfs2(dfs2,root,-1);
	return cent;
}

int ask(int u,int v){
	cout<<"? "<<++u<<' '<<++v<<endl;
	int ret;cin>>ret;
	return ret;
}

int main(){
	int T;cin>>T;
	
	while(T--){
		int N;cin>>N;
		for(int i=0;i<N;i++){
			G[i].clear();
			seen[i]=false;
			sz[i]=0;
		}
		for(int i=0;i<N;i++){
			int u,v;cin>>u>>v;
			u--;v--;
			if(u>=0){
				G[i].push_back(u);
				G[u].push_back(i);
			}
			if(v>=0){
				G[i].push_back(v);
				G[v].push_back(i);
			}
		}

		int ans=-1;
		auto solve=[&](auto&&solve,int now)->void{
			int ce=cent(now);
			seen[ce]=true;

			vector<int>ch;
			for(int nxt:G[ce]){
				if(!seen[nxt])ch.push_back(nxt);
			}

			int deg=ch.size();
			if(deg==0){
				ans=ce;
			}else if(deg==1){
				int res=ask(ce,ch.front());

				if(res==0){
					seen[ch.front()]=true;
					solve(solve,ce);
				}
				else if(res==2)solve(solve,ch.front());
				else assert(false);
			}else if(deg==2){
				int le=ch[0],ri=ch[1];
				int res=ask(le,ri);

				if(res==0)solve(solve,le);
				else if(res==1)ans=ce;
				else solve(solve,ri);
			}else if(deg==3){
				int res=ask(ch[0],ch[1]);

				if(res==1){
					seen[ce]=false;
					seen[ch[0]]=true;
					seen[ch[1]]=true;
					solve(solve,ce);
				}
				else if(res==0) solve(solve,ch[0]);
				else solve(solve,ch[0]);
			}
		};

		solve(solve,0);
		cout<<"! "<<++ans<<endl;
	}
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

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

input:

2
5
0 0
1 5
2 4
0 0
0 0
1
1
2
0 2
0 0
2

output:

? 1 5
? 2 4
! 3
? 1 2
! 2

result:

ok OK (2 test cases)

Test #2:

score: -100
Runtime Error

input:

5555
8
2 0
8 6
0 0
3 0
0 0
7 0
0 0
5 4
2

output:

? 1 8
! 1

result: