1 条题解
-
1
考点:树的dfs
AC做法
我们可以用邻接表来存储,同时为了防止dfs根,来一个标记来进行特判,然后继续深度优先搜索。
#include <bits/stdc++.h> using namespace std; const int MAXN = 2e5 + 10; int n, q, a[MAXN]; bool vis[MAXN]; vector<pair<int, bool>> adj[MAXN]; int ans = -1, step = 0; void dfs(int now, int fa, int target); int main(void) { freopen("command.in", "r", stdin); freopen("command.out", "w", stdout); ios::sync_with_stdio(false); cin.tie(nullptr), cout.tie(nullptr); cin >> n >> q; for (int i = 2;i <= n;i++) { cin >> a[i]; adj[i].push_back({a[i], true}); adj[a[i]].push_back({i, false}); } while (q--) { int u, k; cin >> u >> k; dfs(u, -1, k); cout << ans << '\n'; step = 0, ans = -1; } return 0; } void dfs(int now, int fa, int target) { if (ans != -1) { return; } step++; if (step == target) { ans = now; return; } for (auto v : adj[now]) { if (v.first != fa && !v.second) { dfs(v.first, now, target); if (ans != -1) { return; } } } }
信息
- ID
- 580
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 6
- 标签
- 递交数
- 27
- 已通过
- 12
- 上传者