题意:
给你一棵树,然后有两个点u,v,给出u,v的最近公共祖先,问询问的u,v,如果知道了结点是旅馆,也就是根节点那么直接输出。
思路:
因为我们最终是要知道根结点是多少的,如果是用叶子节点了,如果最后将叶子结点删除到最后,那么最后一个结点一定就是根节点,如果在期间出现有u = lca或者v = lca的情况,因为叶子节点没有子节点(也就是度=1),所以那么=lca的节点必是根节点(这个时候就是根节点没有左节点点或者右节点的情况了,因为都有,那么度不是1),最近公共祖先就是自己也就是说这个节点是本条链的最高的节点,那么就是根节点了,所以每次更新叶子节点就行了。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <string>
#include <cmath>
#include <set>
using namespace std;
typedef long long ll;
typedef vector<int> vec;
template <class T>
inline void read(T &ret) {
char c;
int sgn;
if (c = getchar(), c == EOF) return ;
while (c != '-' && (c < '0' || c > '9')) c = getchar();
sgn = (c == '-') ? -1:1;
ret = (c == '-') ? 0:(c - '0');
while (c = getchar(), c >= '0' && c <= '9') ret = ret * 10 + (c - '0');
ret *= sgn;
return ;
}
inline void out(int x) {
if (x > 9) out(x / 10);
putchar(x % 10 + '0');
}
const int maxn = 1010;
vec node[maxn];
set<int> leaf;
int d[maxn] = {0};
void del(int u) {
for (int i = 0; i < node[u].size(); i++) {
int v = node[u][i];
d[v]--;
if (d[v] == 1) leaf.insert(v);
}
}
int main() {
ios::sync_with_stdio(false);
int n;
read(n);
for (int i = 0; i < n - 1; i++) {
int u, v;
read(u), read(v);
node[u].push_back(v);
node[v].push_back(u);
d[u]++, d[v]++;
}
for (int i = 1; i <= n; i++) {
if (d[i] == 1) leaf.insert(i);
}
while (leaf.size() > 1) {
int u = *leaf.begin();
leaf.erase(u);
int v = *leaf.begin();
leaf.erase(v);
int lca;
cout << "? " << u << " " << v << endl;
cin >> lca;
if (lca == u || lca == v) {
cout << "! " << lca;
return 0;
}
del(u), del(v);
}
cout << "! " << *leaf.begin();
return 0;
}