Long Path/CodeForces - 407B/DP

Long Path/CodeForces - 407B/DP

题目

One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.
The maze is organized as follows. Each room of the maze has two one-way portals. Let’s consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 ≤ pi ≤ i.
In order not to get lost, Vasya decided to act as follows.
Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.
Let’s assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal.
Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.
题目来源:CodeForces - 407B
题目链接

题意

有n座宫殿,每个宫殿有两条道路,道路1通往Pi(1<=Pi<=i),道路2通往i+1宫殿,当你到达第i座宫殿为奇数次时只能选择道路1,偶数次时只能选择道路2,问首次到达第(n+1)座宫殿的需要走多少次。

解法

DP,我们可以发现首次到达第i座宫殿需要经过2次(i-1)座宫殿,我们可以设dp[i]为首次到达第i座宫殿需要的走的次数。
问题是怎么计算第二次走过第(i-1)座宫殿所需要的次数,可以推出当我们首次走到第(i-1)座宫殿时,前面i-2座宫殿走过的次数必都为偶数次,所以第一次到到第(i-1)座宫殿时,会不断地向前传送,我们假设向前传送了m次,依次经过了A1,A2…Ai这几座宫殿,状态转移方程就为
dp[i]=2*dp[i-1]-(dp[A1]+dp[A2]+…+dp[Ai])+m+1;

代码:

#include <stdio.h>
#include <cstring>
#include <math.h>
#include <algorithm>
using namespace std;
const int MOD=1000000007;
int n,a[1010],now,tp;
long long dp[1010];

int main()
{
	scanf("%d",&n);
	for (int i=1;i<=n;i++) scanf("%d",&a[i]);
	dp[0]=0;
	dp[1]=0;
	for (int i=2;i<=n+1;i++) 
	{
		dp[i]=(dp[i]+dp[i-1])%MOD;
		now=i-1;
		while (1) 
		{
			tp=a[now];
			dp[i]=(dp[i]-dp[tp]+MOD)%MOD;
			dp[i]=(dp[i]+1)%MOD;
			now=tp;
			if (tp==now) break;
		}
		dp[i]=(dp[i]+dp[i-1])%MOD;
		dp[i]=(dp[i]+1)%MOD;
	}
	printf("%lld",dp[n+1]%MOD);
	return 0;
} 

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、下载 4使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、 4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值