Question:
Make it possible to eat watermelon every day. The minimum cost.
Train of Thought Analysis:
Dp [pos] indicates how much it will cost to have watermelon eaten every day in the previous day.
So if you buy this watermelon. Update the duration of the watermelon.
Then, the minimum value is obtained from the updated part of each watermelon.
It is actually dp [I] = min (dp [I], dp [j-k + 1] + a [j]);
However, if the enumeration times out, the line segment tree is used for maintenance.
5
1 2 3 4 5
1 2 2 2
Given this set of data, it means that each time you buy a watermelon, You have to compare it with the size of the previous one to indicate that the watermelon is just eaten here.
#include
#include
#include #include
#define maxn 55555#define lson num<<1,s,mid#define rson num<<1|1,mid+1,e#define inf ((1LL)<<60)typedef long long LL;using namespace std;LL dp[maxn<<2];void pushdown(int num){ if(dp[num]!=inf) { dp[num<<1]=min(dp[num<<1],dp[num]); dp[num<<1|1]=min(dp[num<<1|1],dp[num]); dp[num]=inf; }}void build(int num,int s,int e){ dp[num]=inf; if(s==e) { return; } int mid=(s+e)>>1; build(lson); build(rson);}void update(int num,int s,int e,int l,int r,LL val){ if(l<=s && r>=e) { dp[num]=min(val,dp[num]); return; } pushdown(num); int mid=(s+e)>>1; if(l<=mid)update(lson,l,r,val); if(r>mid)update(rson,l,r,val);}LL query(int num,int s,int e,int pos){ if(s==e) { return dp[num]; } pushdown(num); int mid=(s+e)>>1; if(pos<=mid)return query(lson,pos); else return query(rson,pos);}int cost[maxn];int last[maxn];int main(){ int n; while(cin>>n) { for(int i=1;i<=n;i++)cin>>cost[i]; for(int i=1;i<=n;i++)cin>>last[i]; build(1,1,n); int pos=last[1]; if(pos>n)pos=n; update(1,1,n,1,pos,(LL)cost[1]); for(int i=2;i<=n;i++) { LL cur=min(query(1,1,n,i),query(1,1,n,i-1)); pos=i+last[i]-1; if(pos>n)pos=n; update(1,1,n,i,pos,cur+(LL)cost[i]); } cout<