codeforces E. Trains and Statistic 线段树优化dp
E. Trains and Statistic
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it’s possible to buy only tickets to stations from i + 1 to a**i inclusive. No tickets are sold at the last station.
Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values ρi, j among all pairs 1 ≤ i < j ≤ n.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of stations.
The second line contains n - 1 integer a**i (i + 1 ≤ a**i ≤ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to a**i inclusive.
Output
Print the sum of ρi, j among all pairs of 1 ≤ i < j ≤ n.
Examples
input
4
4 4 4
output
6
input
5
2 3 5 5
output
17
Note
In the first sample it’s possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.
Consider the second sample:
- ρ1, 2 = 1
- ρ1, 3 = 2
- ρ1, 4 = 3
- ρ1, 5 = 3
- ρ2, 3 = 1
- ρ2, 4 = 2
- ρ2, 5 = 2
- ρ3, 4 = 1
- ρ3, 5 = 1
- ρ4, 5 = 1
Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.
题意: 懒得说了….
分析: 这题看的官方题解, 但是依然不懂状态转移方程,,,,(不要打我..), 只是学到了新的线段树姿势, 求l和r之间的最大值的下标位置… 等以后学到了新的姿势, 再来看这题.
官方题解:
Let the indexation will be from zero. So we should subtract one from all a**i. Also let a**n - 1 = n - 1.
dp**i is sum of shortests pathes from i to i + 1… n - 1.
dp**n - 1 = 0
dp**i = dp**m - (a**i - m) + n - i - 1 where m belongs to range from i + 1 to a**i and a**m is maximal. We can find m with segment tree or binary indexed tree or sparse table.
Now answer equals to sum of all dp**i.
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int N=100010,MOD=1e9+7;
ll dp[N];
int b[N];
struct st
{
int l,r;
pii mx;
}a[N<<2];
int n;
void build(int l,int r,int i)
{
a[i].l=l,a[i].r=r;
if(l==r){
if(l==n){
a[i].mx = pii(n,n);
return;
}
scanf("%d",&a[i].mx.first);
a[i].mx.first--;
b[l-1]=a[i].mx.first;
a[i].mx.second=l;
return;
}
int mid=l+r>>1;
build(l,mid,i<<1);
build(mid+1,r,i<<1|1);
a[i].mx = max(a[i<<1].mx,a[i<<1|1].mx);
}
pii query(int l,int r,int i)
{
if(a[i].l>=l && a[i].r<=r) return a[i].mx;
if(a[i].l>r || a[i].r<l) return pii(-1,-1);
return max(query(l,r,i<<1),query(l,r,i<<1|1));
}
int main()
{
cin>>n;
build(1,n,1);
ll ans=0;
dp[n-1]=0;
for(int i=n-2;i>=0;i--){
int m = query(i+1+1,b[i]+1,1).second-1;
dp[i] = dp[m] - (b[i]-m)+n-1-i;
ans += dp[i];
}
cout<<ans<<endl;
return 0;
}
还没有评论,来说两句吧...