【Codeforces Round #239 (Div. 1) B】 Long Path
阿新 • • 發佈:2018-02-14
pro tdi ont pre std [1] spa 鏈接 blog
【鏈接】 我是鏈接,點我呀:)
【題意】
在這裏輸入題意
【題解】
DP,設f[i]表示第一次到i這個房間的時候傳送的次數。
f[1] = 0,f[2] = 2
考慮第i個位置的情況。
它肯定是從i-1這個位置走過來的。
但是第一次走到i-1這個位置的時候。
需要再走回p[i-1],然後回到i-1才能再走到i
其實這個時候走到p[i-1]的時候,我們就和第一次走到p[i-1]的時候是一樣的。
因此再從p[i-1]走到i-1的話。
它的移動次數就等於f[i-1]-f[p[i-1]]
那麽
f[i] = f[i-1]+1+f[i-1] - f[p[i-1]] + 1
【代碼】
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3;
const int MOD = 1e9+7;
int n,p[N+10],f[N+10];
int main(){
#ifdef LOCAL_DEFINE
freopen("rush_in.txt", "r", stdin);
#endif
ios::sync_with_stdio(0),cin.tie(0);
cin >> n;
for (int i = 1;i <= n;i++) cin >> p[i];
f[1 ] = 0;f[2] = 2;
for (int i = 3;i <= n+1;i++){
f[i] = ((f[i-1] + 1 + f[i-1]-f[p[i-1]] + 1)%MOD+MOD)%MOD;
}
cout<<f[n+1]<<endl;
return 0;
}
【Codeforces Round #239 (Div. 1) B】 Long Path