题解:CF1006E Military Problem

· · 题解

CF1006E Military Problem 题解

终于发现了一到没题解的水题

juruo 的第一篇题解 qwq。

题目传送门

大概意思就是求 u 的子树的 dfs 序的第 k 个是啥。

首先,一颗树的子树的 dfs 序一定是这颗树的 dfs 序的连续的一段。

举个栗子:

这颗树的 dfs 序是:[1 , 2 , 3 , 5 , 6 , 8 , 7 , 9 , 4]。

节点 3 的 dfs 序是:[3 , 5 , 6 , 8 , 7 , 9] ,对应这颗树的 dfs 序的第 3 \sim 8 个。

所以这题就比较好写了,先求每个节点的子树大小,和每个子树对应整颗树的 dfs 序的区间,再求这个区间的第 k 个就 ok 了。

3,2,1 上代码

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

int n , q , a , c[200005] , u , k , pp[200005];
vector <int> ff[200005] , v;
void dfs(int x)
{
    v.push_back(x);
    if(ff[x].size() == 0)
    {
        c[x] = 1;
        return;
    }
    for(auto i : ff[x])
    {
        dfs(i);
        c[x] += c[i];
    }
    c[x] ++;
}
int main()
{
    cin >> n >> q;
    for(int i = 2;i <= n;i ++)
    {
        cin >> a;
        ff[a].push_back(i);
    }
    dfs(1);     //把dfs序存到v里,c[i]代表以i为根的子树有多少个节点
    for(int i = 0;i < v.size();i ++)
    {
        pp[v[i]] = i;    //节点i在dfs序的第pp[i]个
    }
    while(q --)
    {
        cin >> u >> k;
        if(k > c[u])    //超出区间要特判一下
        {
            cout << "-1\n";
            continue;
        }
        int p = pp[u];
        cout << v[p + k - 1] << "\n";
    }
    return 0;
}