codeforces D. Kuroni and the Celebration

在这里插入图片描述
题目

题意:

给你一棵树,然后有两个点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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值