线性dp Codeforces Round #239 (Div. 2) D题 Long Path

Long Path

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 p i, where 1 ≤ p i ≤ i.

In order not to get lost, Vasya decided to act as follows.

  1. Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.
  2. 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 p i), 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.


题目大意:n 个房间,标号为 1-n,起始位置为 1,需要到 n+1 号房间,每次进入一个房间要在房间打个标记,如果该房间总的标记的数量为偶数,那么下一次可以去第 i+1 个房间,如果为奇数,那么下一次只能去第 p[i] 个房间,问到第 n+1 个房间的步数;

比较容易想到:dp[i]=dp[i-1]+1;dp[p[i]]=dp[i]+1; 然后写一个递归程序,但是超时;

#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=1100;
const int M=2000100;
const LL mod=1e9+7;
int n,p[N];
LL sum[N],dp[N];
void dfs(int q){
	if(q==n+1) return;
	sum[q]++;
	if(sum[q]%2ll==0){
		(dp[q+1]=dp[q]+1ll)%=mod;
		dfs(q+1);
	}
	else{
		(dp[p[q]]=dp[q]+1ll)%=mod;
		dfs(p[q]);
	}
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++) cin>>p[i];
	dfs(1);
	cout<<dp[n+1]<<endl;
	return 0;
}

可以发现如果第 i 个房间是第一次到达,那么第 i-1 个房间一定是到达2次,所以:

dp[i] 表示第一次到达第 i 个房间的步数,转移方程为:

dp[i]+=dp[i-1]+1;
dp[i]+=dp[i-1]+1-dp[p[i-1]];表示第 i-1 个房间绕回去再回到第 i-1 个房间的步数,因为是到达两次,所以必须绕;

代码:

#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=1100;
const int M=2000100;
const LL mod=1e9+7;
int n,p[N];
LL dp[N];
int main(){
	cin>>n;
	for(int i=1;i<=n;i++) cin>>p[i];
	for(int i=2;i<=n+1;i++){
		dp[i]+=dp[i-1]+1;
		dp[i]+=dp[i-1]+1-dp[p[i-1]];
		dp[i]%=mod; 
	}
	cout<<(dp[n+1]+mod)%mod<<endl;
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值