Long Path CodeForces - 407B(动态规划+思维+公式推导)
題意:
起點為1,終點為n+1,對應第i個各點,如果我奇數次到達i點,那么下一步走到a【i】的位子,如果是偶數次到達,那么下一步走到i+1的位子。
問從1走到n+1一共需要走多少步?結果對1e9+7取模。
題目
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
分析:
1.定義狀態dp[x][y]為從x走到y需要走多少次。
2.如果我們要到達某個點y,則要到達y-1的點,第一次到達y-1,按照題目要求,奇數次到達y-1點,會到達s【y-1】,所以第二次到達y-1,需從s【y-1】到達y-1:故推出公式,
dp【x】【y】=dp【x】【y-1】+【s【y-1】】【y-1】+1;
AC代碼
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int M=1e3+10; const int mod=1e9+7; int dp[M][M],s[M];//設定dp【i】【j】表示從i走到j一共需要多少步。 int n; void dfs(int x,int y) {if(x==y){dp[x][y]=1;return ;}if(dp[x][y])return ;/**如果要到達y,有兩種情況,第一次到達y-1,回到s[i-1],在偶數次到達y-1時,可直接到達y*/dfs(x,y-1);dfs(s[y-1],y-1);///考慮到s【i】<=i,那么要想到i+1這個格點去,那么一定是從第i個格點走過去的。所以推出普遍公式dp[x][y]=dp[x][y-1]+dp[s[y-1]][y-1]+1;/**那么x-->y,需要先第一次從x-->y-1,由規則到達【y-1】,再從是【y-1】->y-1*/dp[x][y]%=mod; } int main() {while(~scanf("%d",&n)){memset(dp,0,sizeof(dp));for(int i=1; i<=n; i++)scanf("%d",&s[i]);dfs(1,n+1);printf("%d\n",dp[1][n+1]-1);}return 0; }總結
以上是生活随笔為你收集整理的Long Path CodeForces - 407B(动态规划+思维+公式推导)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑提子的功效与作用、禁忌和食用方法
- 下一篇: Minimum Inversion Nu