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.
The first line contains integer n (1 ≤ n ≤ 103) — the number of rooms. The second line contains n integers pi (1 ≤ pi ≤ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.
Print a single number — the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7).
2 1 2
4
4 1 1 2 3
20
5 1 1 1 1 1
62
题目的意思是叫我们求出从1号房间到达n+1号房间需要借用几次入口,入口有两种类型,一种是到达1和当前所在房间之间的房间,另外一种是到达当前所在房间的上一个房间,每到达一个房间都要在该房间的天花板上画一个十字,画完后当该房间的十字数量为奇数时,使用上面说述的第一种,否则就使用上面所述的第二种入口
我们会发现,当我们第一次进入一个房间时,接下来肯定会往下降,进入房间p[i],我们设dp[i](i为当前我们所在的房间号)为从第一次从i到进入i+1号房间所需要的入口次数,所以dp[i]就为
for(int j = p[i]; j < i; j ++) dp[i] = (dp[i] + dp[j]) % inf;
不过这里我们要初始化dp[i]为2,因为上述计算少加了两次,一次是第一次进入i号房间,另为一次时重新回到i+1号后进入i+1号房间,最后的答案就是dp[i]的累和
#include <bits/stdc++.h>
using namespace std;
typedef __int64 ll;
const int inf = 1e9 + 7;
ll p[1010];
ll dp[1010];
int main()
{
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i ++){
scanf("%I64d", &p[i]);
}
dp[1] = 2;
ll ans = 2;
for(int i = 2; i <= n; i ++){
dp[i] = 2;
for(int j = p[i]; j < i; j ++){
dp[i] = (dp[i] + dp[j]) % inf;
}
ans = (ans + dp[i]) % inf;
}
cout << ans << endl;
return 0;
}