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; }