Military Problem(dfs序)

Military Problem

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

题目:

给你一棵有根树。个询问,输出从为根的子树往下得到的序列中第个数,超出则输出


做法:

求出树的序。每个询问输出结点中往后第个数。


代码:

#include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false), cin.tie(0)
#define debug(a) cout << #a ": " << a << endl
using namespace std;
typedef long long ll;
const int N = 2e5 + 7;
vector<int> g[N];
int dfn[N], tag, in[N], out[N];
void dfs(int u){
    dfn[++tag] = u, in[u] = tag;
    for (auto &v : g[u]) dfs(v);
    out[u] = tag;
}
int main(void){
    IOS;
    int n, m; cin >> n >> m;
    for (int i = 2; i <= n; ++i){
        int x; cin >> x; 
        g[x].push_back(i);
    }
    dfs(1);
    while (m--){
        int u, k; cin >> u >> k;
        if (k > out[u]-in[u]+1){
            cout << -1 << endl;
        }else{
            cout << dfn[in[u]+k-1] << endl;
        }
    }
    return 0;
}
全部评论

相关推荐

king122:专业技能不要写这么多,熟悉和熟练你经不住问,排版有些难看,中间的空隙搞小一点,项目描述的话感觉是从课程中抄下来的,改一改吧,不然烂大街了,每个项目都写一两点,用什么技术实现了什么难点,然后再写一些数字上去像时间又花了90%这样,这样面试会多一些,如果觉得自己的项目还是不够用的话,我有几个大厂最近做过的实习项目,感兴趣的话可以看我简介中的项目地址
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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