CF 407B Long Path[观察性质 DP]

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

Examples
input
2
1 2
output
4
input
4
1 1 2 3
output
20
input
5
1 1 1 1 1
output
62

官方题解
In this problem you had to simulate route of character in graph.
Note that if you are in vertice i, then edges in all vertices with numbers less than i are turned to pi. It gives us opportunity to see a recurrence formula: let dpi be number of steps, needed to get from vertice to vertice i, if all edges are rotated back, into pi. Then dpi +  = 2dpi +  - dppi. Answer will be dpn + .

很明显要用到DP

考虑d+1,只可能从i走到,但是第一次到达i,下一步会走到pi,然后又到达i

可以发现到i时i之前的全是偶数个叉,所以这两次的传送门数是一样的,第二次只是少了到p[i]到次数而已

d[i]表示第一次到达i的传送门次数,d[i]=d[i]+1+(d[i]-d[p[i]])+1

//
// main.cpp
// cf407b
//
// Created by Candy on 9/15/16.
// Copyright © 2016 Candy. All rights reserved.
// #include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
const ll N=,MOD=1e9+;
int n,p[N];
ll d[N];
void dp(){
for(int i=;i<=n;i++)
d[i+]=(d[i]++(d[i]-d[p[i]])++MOD)%MOD;
}
int main(int argc, const char * argv[]) {
scanf("%d",&n);
for(int i=;i<=n;i++) scanf("%d",&p[i]);
dp();
cout<<d[n+];
return ;
}
上一篇:if __name__== "__main__" 的意思(作用)python代码复用


下一篇:重复造*,编写一个轻量级的异步写日志的实用工具类(LogAsyncWriter)