Long Path/CodeForces - 407B/DP
题目
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.
题目来源:CodeForces - 407B
题目链接
题意
有n座宫殿,每个宫殿有两条道路,道路1通往Pi(1<=Pi<=i),道路2通往i+1宫殿,当你到达第i座宫殿为奇数次时只能选择道路1,偶数次时只能选择道路2,问首次到达第(n+1)座宫殿的需要走多少次。
解法
DP,我们可以发现首次到达第i座宫殿需要经过2次(i-1)座宫殿,我们可以设dp[i]为首次到达第i座宫殿需要的走的次数。
问题是怎么计算第二次走过第(i-1)座宫殿所需要的次数,可以推出当我们首次走到第(i-1)座宫殿时,前面i-2座宫殿走过的次数必都为偶数次,所以第一次到到第(i-1)座宫殿时,会不断地向前传送,我们假设向前传送了m次,依次经过了A1,A2…Ai这几座宫殿,状态转移方程就为
dp[i]=2*dp[i-1]-(dp[A1]+dp[A2]+…+dp[Ai])+m+1;
代码:
#include <stdio.h>
#include <cstring>
#include <math.h>
#include <algorithm>
using namespace std;
const int MOD=1000000007;
int n,a[1010],now,tp;
long long dp[1010];
int main()
{
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
dp[0]=0;
dp[1]=0;
for (int i=2;i<=n+1;i++)
{
dp[i]=(dp[i]+dp[i-1])%MOD;
now=i-1;
while (1)
{
tp=a[now];
dp[i]=(dp[i]-dp[tp]+MOD)%MOD;
dp[i]=(dp[i]+1)%MOD;
now=tp;
if (tp==now) break;
}
dp[i]=(dp[i]+dp[i-1])%MOD;
dp[i]=(dp[i]+1)%MOD;
}
printf("%lld",dp[n+1]%MOD);
return 0;
}