CodeForces 407B Long Path

来源:互联网 发布:印刷自助报价系统源码 编辑:程序博客网 时间:2024/05/21 22:27

B. Long Path
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

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.

Output

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).

Sample test(s)
input
21 2
output
4
input
41 1 2 3
output
20
input
51 1 1 1 1
output
62


这道题一开始当模拟题做,果断就TLE了o(╯□╰)o

后来一看题目都说了数据会很大,都让模10^9+7了

TLE简直是活该啊(⊙o⊙)…


蓝后...发现是DP题


根据题目可以推断出,当第一次走到 room i 时,再走一步会往回走,走到 room pi

只有第二次走到 room i 时,才会继续往前走

假设第一次走到 room i 需要dp[i]步

那么走到 room i+1 就需要先走一步退回 room pi,再经过不知道多少步再次走到 room i,再走一步走到room i+1

dp[i+1] = dp[i]+1+不知道多少步+1


那么这个不知道多少步到底是多少步捏╮(╯▽╰)╭

让我们来分析一下,嗯嗯


记第一次走到 room pi 时各room的状态集合为S = { s1, s2, s3,..., s(i-1) }(集合中的元素表示各房间的奇偶性,如用0表示even,1表示odd)

那么当走到 room i 再回到 room pi 时 S 不变

也就是此时与第一次走到 room pi 时处于同一状态(仅仅看room 1 - room i-1 的话)

因此再次走到 room i 所需的步数与第一次相同 即 dp[i]-dp[pi]

代入上面的式子,得状态转移方程:

dp[i+1] = 2dp[i]-dp[pi]+2


代码如下:

#include<iostream>using namespace std;const int maxn = 1000 + 5;const int mod = 1000000000 + 7;int portal[maxn];long long dp[maxn];int main() {  int n;  cin >> n;  for (int i = 1; i <= n; i++)    cin >> portal[i];  dp[1] = 0;  for (int i = 1; i <= n; i++)    dp[i+1] = (2*dp[i]-dp[portal[i]]+2+mod) % mod;  cout << dp[n+1] << endl;  return 0;}


代码中有一个要注意的地方

因为题目要求的是总步数对(10^7+7)的模

根据取模的性质,可以在每次状态转移后对结果进行取模

为了避免负数的产生,加上(10^7+7)再取模

0 0
原创粉丝点击