(gplt真题)龙龙送外卖

题目链接:题目详情 - L2-043 龙龙送外卖 (pintia.cn)

题目:

 样例输入:

7 4
-1 1 1 1 2 2 3
5
6
2
4

样例输出:

2
4
4
6

分析:先来看一下样例

假如我们现在要从1号点经过2,4,5,6点而且还要回到1号点。那么距离最近也是图中每条边走两次,而且可以发现每条边走两次是一定可以做到的,现在我们不要求回到1号点,那么我们就可以在每条边走两次的基础上减去一些距离,容易发现,最后停留的点的距离越深那么减掉的边也就越多,最短距离也就越短,所以我们只需要求出点深度最深的点,然后用边数的2倍减去其深度即可。

细节见代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
#include<queue>
#include<vector>
#include<cmath>
using namespace std;
const int N=5e5+10;
int d[N],ans,fu[N];
int dfs(int x)
{
	if(d[x]!=-1) return d[x];
	ans++;
	d[x]=1+dfs(fu[x]);
	return d[x];
}
int main()
{
	int n,m;
	cin>>n>>m;
	int root;
	for(int i=1;i<=n;i++)
	{
		d[i]=-1;
		int t;
		cin>>t;
		if(t==-1) root=i;
		else fu[i]=t;
	}
	d[root]=0;
	int mx=0;
	while(m--)
	{
		int t;
		cin>>t;
		mx=max(mx,dfs(t));
		printf("%d\n",2*ans-mx);
	}
	return 0; 
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值