首先一个思考方法就是对比较小的样例进行纸上演算,了解题目的规律,看清本质。
不放p[i]=1; i=1,2,3,4,5;
然后就发现每次都艰难的到了某一个点,又回到1,“无功而返”。
但是,找到了一些规律,每次第一次到达某一个点的时候,前面的全部是0(0-偶数,1-奇数),然后即将直接跳回到pi这个点,count(pi)==奇数。 然后又会历尽千辛万苦到了i,只是这一次,count(i)==偶数了,可以往前走了。
那么记f(i)代表第一次到i号结点的时候走的步数。 那么f(i+1)=f(i)+1(走到pi)+重新回到i的步数+1(向前走一步到i+1),重新回到i的步数,由于1,2,3...i-1,这些结点的count属性,和第一次到pi的时候是一样的,那么重新回到i的步数==f(i)-f(p[i]) .
然后地推公式就是f(i+1)=2*f(i)+2-f(p[i]) ,dp即可。
/*#include<bits/stdc++.h>
using namespace std;
const int maxn = 1005;
const int mod = 1e9+7;
int p[maxn];
int cnt[maxn];
queue<int>q;
int main()
{
int n;
scanf("%d",&n);
for(int i = 1;i<=n;i++)
scanf("%d",&p[i]);
int ans = 0;
q.push(1);
while(!q.empty())
{
int now = q.front();q.pop();
cnt[now]++;
if(cnt[now]&1)
{
q.push(p[now]);
ans = (ans+1)%mod;
}
else
{
q.push(now+1);
ans = (ans+1)%mod;
if(now+1==n+1)
break;
}
}
printf("%d\n",ans);
}*/
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1005;
const int MOD = 1e9+7;
int p[maxn],c[maxn];
int n;
int lowbit(int i){return i&(-i);}
void update(int i,int v)
{
while(i<=n+1)
{
c[i]=(c[i]+v)%MOD;
i+=lowbit(i);
}
}
int sum(int i)
{
int ans=0;
while(i)
{
ans=(ans+c[i])%MOD;
i-=lowbit(i);
}
return ans;
}
int main()
{
int ans=0;
scanf("%d",&n);
for(int i = 1;i<n+1;i++)
scanf("%d",&p[i]);
for(int i = 1;i<n+1;i++)
{
int res=(2+sum(i-1)-sum(p[i]-1)+MOD)%MOD;
ans=(ans+res)%MOD;
update(i,res);
}
printf("%d\n",ans);
return 0;
}
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 numberpi, 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 pidenotes 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