Military Problem

Military Problem

https://ac.nowcoder.com/acm/problem/112932

Military Problem

DFS序模板题了,l[rt]标记rt节点第一次进入,r[rt]表示rt节点退出,
然后只要判断l[rt] + k - 1 是否小于等于r[rt]即可。

/*
  Author : lifehappy
*/
#include <bits/stdc++.h>

using namespace std;

const int N = 2e5 + 10;

vector<int> G[N];

int id[N], l[N], r[N], rk[N], tot, n, m;

void dfs(int rt, int fa) {
    id[rt] = ++tot;
    rk[tot] = rt;
    l[rt] = tot;
    for(auto i : G[rt]) {
        if(i == fa) continue;
        dfs(i, rt);
    }
    r[rt] = tot;
}

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    scanf("%d %d", &n, &m);
    for(int i = 2; i <= n; i++) {
        int x;
        scanf("%d", &x);
        G[x].push_back(i);
    }
    dfs(1, 0);
    for(int i = 1; i <= m; i++) {
        int rt, k;
        scanf("%d %d", &rt, &k);
        printf("%d\n", l[rt] + k - 1 <= r[rt] ?  rk[l[rt] + k - 1] : -1);
    }
    return 0;
}
全部评论

相关推荐

身边有人上海、深圳&nbsp;6、7k&nbsp;都去了,真就带薪上班了。
程序员小白条:木的办法, 以后越来越差,还是家附近宅着吧,毕业的人越来越多,岗位都提供不出来,经济又过了人口红利期
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 12:10
点赞 评论 收藏
分享
06-14 19:09
门头沟学院 Java
darius_:给制造业搞的,什么物料管理生产管理,设备管理点检,最最关键的就是一堆报表看板。个人觉得没啥技术含量都是些基本的crud,但是业务很繁琐那种
点赞 评论 收藏
分享
牛客92804383...:在他心里你已经是他的员工了
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务