Monotone queue optimization dp - WOJ # 2735 Hopscotch

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_42557561/article/details/102737198

Portal


Analysis

Then test when NOIP popular group, dp will not
see this question on the test, direct decisively abandoned

Two years later, I was finally able to understand the problem / laughing
is clearly a dichotomy + dp legal judgment

definition f [ i ] f[i] denotes the i reaches the position of maximum points available
is clearly f [ i ] = m a x ( f [ j ] ) + s c The r e [ i ] f[i]=max(f[j])+score[i]
j j meet m a x ( 1 , d g ) < = x [ i ] x [ j ] < = d + g max(1,d-g)<=x[i]-x[j]<=d+g
If only the second half of limitation, the queue can be directly monotone

Now consider more restrictions first half
we can maintain a pointer to the left, into the monotonous ensure queue limit values are met first half, limiting the latter part of the first bomb and then by the team out

Harvest:
monotonous pop up every time the queue queue can only meet one condition
to another condition that we maintain in other ways
This method is very common feeling [sTO lsr fairy Orz]

Code
#include<bits/stdc++.h>
#define in read()
#define re register
using namespace std;
inline int read(){
	char ch;int f=1,res=0;
	while((ch=getchar())<'0'||ch>'9') if(ch=='-') f=-1;
	while(ch>='0'&&ch<='9'){
		res=(res<<1)+(res<<3)+(ch^48);
		ch=getchar();
	}
	return f==1?res:-res;
}
const int N=5e5+10;
typedef long long ll;
int head,tail,q[N];
int n,d,K,x[N];
ll score[N],f[N];
bool check(int g){
	head=1;tail=0;f[0]=0;
	int up=d+g,down=max(1,d-g);
	int l=0;//传说中的指针 
	for(re int i=1;i<=n;++i){
		while(x[i]-x[l]>=down){
			while(head<=tail&&f[l]>f[q[tail]]) tail--;
			q[++tail]=l;
			l++;
		}
		while(head<=tail&&x[i]-x[q[head]]>up) head++;
		if(head<=tail) f[i]=f[q[head]]+score[i];
		else f[i]=-1e18;//如果无法到达设为-INF
	}
	ll ans=-1e18;
	for(re int i=0;i<=n;++i) ans=max(ans,f[i]);
	return ans>=K;
}
int main(){
	n=in;d=in;K=in;
	for(re int i=1;i<=n;++i) x[i]=in,score[i]=in;
	int l=0,r=1e9,ans=-1;
	while(l<=r){
		int mid=l+r>>1;
		if(check(mid)) ans=mid,r=mid-1;
		else l=mid+1;
	}
	cout<<ans;
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_42557561/article/details/102737198