CodeForces 1305D Kuroni and the Celebration

洛谷传送门

CF 传送门

萌萌交互题。

思路

考虑每次询问两个叶子的 \(\mathrm{LCA}\),若 \(\mathrm{LCA}\) 为两个叶子之一,那么 \(\mathrm{LCA}\) 必为根。

每次询问后需要加进来新的叶子。

若询问 \(\left\lfloor\dfrac{n}{2}\right\rfloor\) 次后仍未找到根,最后剩下的没询问过的点即为跟。

代码

code
/*

p_b_p_b txdy
AThousandSuns txdy
Wu_Ren txdy
Appleblue17 txdy

*/

#include <bits/stdc++.h>
#define pb push_back
#define fst first
#define scd second
#define mems(a, x) memset((a), (x), sizeof(a))

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<ll, ll> pii;

const int maxn = 1010;

int n, deg[maxn], head[maxn], len;
bool vis[maxn];

struct edge {
	int to, next;
} edges[maxn << 1];

void add_edge(int u, int v) {
	edges[++len].to = v;
	edges[len].next = head[u];
	head[u] = len;
}

int ask(int x, int y) {
	printf("? %d %d\n", x, y);
	fflush(stdout);
	scanf("%d", &x);
	return x;
}

void solve() {
	scanf("%d", &n);
	for (int i = 1, u, v; i < n; ++i) {
		scanf("%d%d", &u, &v);
		add_edge(u, v);
		add_edge(v, u);
		++deg[u];
		++deg[v];
	}
	queue<int> q;
	for (int i = 1; i <= n; ++i) {
		if (deg[i] == 1) {
			q.push(i);
		}
	}
	for (int _ = 0; _ < n / 2; ++_) {
		int u1 = q.front();
		q.pop();
		int u2 = q.front();
		q.pop();
		int u3 = ask(u1, u2);
		if (u3 == u1 || u3 == u2) {
			printf("! %d\n", u3);
			return;
		}
		vis[u1] = vis[u2] = 1;
		for (int i = head[u1]; i; i = edges[i].next) {
			int v = edges[i].to;
			if (!vis[v] && (--deg[v]) == 1) {
				q.push(v);
			}
		}
		for (int i = head[u2]; i; i = edges[i].next) {
			int v = edges[i].to;
			if (!vis[v] && (--deg[v]) == 1) {
				q.push(v);
			}
		}
	}
	for (int i = 1; i <= n; ++i) {
		if (!vis[i]) {
			printf("! %d\n", i);
			return;
		}
	}
}

int main() {
	int T = 1;
	// scanf("%d", &T);
	while (T--) {
		solve();
	}
	return 0;
}

posted @ 2022-07-21 09:14  zltzlt  阅读(21)  评论(0编辑  收藏  举报