QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#776562#9570. Binary TreeLanthanmumRE 0ms0kbC++202.2kb2024-11-23 19:23:052024-11-23 19:23:05

Judging History

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

  • [2024-11-23 19:23:05]
  • 评测
  • 测评结果:RE
  • 用时:0ms
  • 内存:0kb
  • [2024-11-23 19:23:05]
  • 提交

answer

#include <iostream>
#include <vector>
using namespace std;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int N = 1e5 + 9;
int mxs, sum, rt, n;
int flag;
int del[N], sz[N];
vector<int> e[N];

auto ask(int u, int v) {
	if(flag){
		return 3;
	}
	cout << "?" << " " << u << " " << v << endl;
	int x;
	cin >> x;
	return x;
};

auto ok(int x) {
	if(flag){
		return;
	}
	cout << "!" << " " << x << endl;
	flag=1;
	
};

void add(int u, int v) {
	e[u].push_back(v);
	e[v].push_back(u);
}

void getroot(int u, int f) {
	if (del[u]) {
		sz[u] = 0;
	} else {
		sz[u] = 1;
	}
	int s = 0;
	for (auto &i : e[u]) {
		if (i == f || del[i]) {
			continue;
		}
		getroot(i, u);
		sz[u] += sz[i];
		s = max(s, sz[i]);
	}
	s = max(s, sum - sz[u]);
	if (s < mxs) {
		mxs = s;
		rt = u;
	}
}

void dfs(int rt) {
	if (flag) {
		return;
	}
	for (auto & i : e[rt]) {
		if (del[i]) {
			continue;
		}
		sum = sz[i];
		mxs = sz[i];
		getroot(i, 0);
	}
	
	if (del[rt]) {
		return;
	}
	vi t;
	for (auto &i : e[rt]) {
		if (!del[i]) {
			t.push_back(i);
		}
	}
	
	int SZ = t.size();

	if (!SZ) {
		ok(rt);
		flag = 1;
		return;
	} else if (SZ == 1) {
		int x = ask(rt, t[0]);
		if (!x) {
			ok(rt);
			return;
		} else {
			del[rt] = 1;
			dfs(t[0]);
			
		}
	} else if (SZ == 2) {
		int x = ask(t[0], t[1]);
		if (x == 1) {
			ok(rt);
			return;
		}
		del[rt] = 1;
		if (x == 0) {
			dfs(t[0]);
			
		}
		else{
			dfs(t[1]);
		}
		
	} else {
		int x = ask(t[0], t[1]);
		if (x == 0) {
			dfs(t[0]);
			del[rt] = 1;
			
		} else if (x == 1) {
			del[t[0]] = del[t[1]] = 1;
			dfs(rt);
		} else {
			del[rt] = 1;
			dfs(t[1]);
			
		}
	}
}

void solve() {
	cin >> n;
	for(int i=1;i<=n;i++){
		e[i].clear();
		sz[i]=0,del[i]=0;
	}
	for (int i = 1; i <= n; i++) {
		int u, v;
		cin >> u >> v;
		if (u) {
			add(u, i);
		}
		if (v) {
			add(v, i);
		}
	}
	// for(int i=1;i<=n;i++){
	// cout<<i<<'\n';
	// for(auto & j : e[i]){
	// cout<<j<<" ";
	// }
	// cout<<'\n';
	// }
	// cout<<'\n';
	mxs = n, sum = n;
	getroot(1,0);
	// cout<<rt<<'\n';
	dfs(rt);
	ed:;
};

int main() {
	int t;
	cin >> t;
	while (t--) {
		flag = 0;
		solve();
	}
	return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 0
Runtime Error

input:

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

output:

? 1 5
? 2 3
? 3 4

result: