烽火传递【单调队列+DP】

学会单调队列的第一道题就WA了
最后发现是我想简单了

spojP394

用一个单调队列单减的答案
每次计算答案: f i = f h e a d + w i f_i=f_{head}+w_i
最后求出最小的f

单调队列需要注意的要点:
1 移动l与r的时候注意不等号的方向
2 最后得到答案的时候注意起搜的下标

#include<bits/stdc++.h>
using namespace std;
#define in Read()
#define re register
const int NNN=(int)1e6+10;
const int INF=~0u>>1;
int n,m;
int c[NNN],p[NNN],f[NNN];
int l=1,r=1,ans;

inline int in{
	int i=0,f=1;char ch;
	while((ch>'9'||ch<'0')&&ch!='-')ch=getchar();
	if(ch=='-')f=-1,ch=getchar();
	while(ch<='9'&&ch>='0')i=(i<<1)+(i<<3)+ch-48,ch=getchar();
	return i*f;
}

int main(){
	n=in,m=in;
	for(re int i=1;i<=n;i++)c[i]=in;
	
	for(re int i=1;i<=n;i++){
		while(l<=r&&p[l]<i-m)l++;
		f[i]=f[p[l]]+c[i];
		while(l<=r&&f[i]<=f[p[r]])r--;
		p[++r]=i;
	}
	
	int ans=INF;
	for(re int i=n-m+1;i<=n;i++)
		ans=min(ans,f[i]);
	printf("%d\n",ans);
	
	return 0;
}
发布了26 篇原创文章 · 获赞 3 · 访问量 908

猜你喜欢

转载自blog.csdn.net/Antimonysbguy/article/details/102987818
今日推荐