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.
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
#define LL long long
#define pa pair
#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
#define LL long long
#define pa pair
#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;
}