L2-043 龙龙送外卖

考察的是贪心+记忆化搜索。
最短路=走过的路径*2-从根到小区最深路径长度

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int p[maxn],dis[maxn],dp[maxn];
int maxdepth = 0, sumpath = 0;
int dfs(int s) {//记忆化搜索
	if (p[s] == -1) return 0;
	if (dp[s]) return dp[s];
	sumpath++;
	dp[s] = dfs(p[s]) + 1;
	return dp[s];
}
int main() {
	int n, m;
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		cin >> p[i];
	}
	while (m--) {
		//最深
		int input;
		cin >> input;
		int depth = dfs(input);//到外卖地点的深度
		maxdepth = max(maxdepth, depth);
		cout << 2 * sumpath - maxdepth << '\n';
	}
	return 0;
}
posted @ 2024-03-28 09:10  YuKiCheng  阅读(43)  评论(0编辑  收藏  举报