E43【模板】单调队列优化DP 烽火传递

视频链接:451 单调队列优化DP 烽火传递_哔哩哔哩_bilibili

 

E11【模板】单调队列 滑动窗口最值 - 董晓 - 博客园 (cnblogs.com)

LOJ10180 烽火传递

复制代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=2e5+10;
int n,m,w[N],f[N],q[N];

int main(){
  cin>>n>>m;
  for(int i=1;i<=n;i++) cin>>w[i];
  
  int ans=2e9;
  int h=1,t=0;                          //清空队列
  for(int i=1;i<=n;i++){                //枚举序列
    while(h<=t && f[q[t]]>=f[i-1]) t--; //队尾出队(队列不空且新元素更优)
    q[++t]=i-1;                         //队尾入队(存储下标 方便判断队头出队)
    if(q[h]<i-m) h++;                   //队头出队(队头元素滑出窗口)
    f[i]=f[q[h]]+w[i];                  //转移
    if(i>n-m) ans=min(ans,f[i]);
  }
  cout<<ans;
}
复制代码
复制代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=2e5+10;
int n,m,w[N],f[N],q[N];

int main(){
  cin>>n>>m;
  for(int i=1;i<=n;i++) cin>>w[i];
  
  int ans=2e9;
  int h=1,t=0;                          //清空队列
  for(int i=1;i<=n;i++){                //枚举序列
    while(h<=t && q[h]<i-m) h++;        //队头出队(队列不空且队头元素滑出窗口)
    while(h<=t && f[q[t]]>=f[i-1]) t--; //队尾出队(队列不空且新元素更优)
    q[++t]=i-1;                         //队尾入队(存储下标 方便判断队头出队)
    f[i]=f[q[h]]+w[i];                  //转移
    if(i>n-m) ans=min(ans,f[i]);
  }
  cout<<ans;
}
复制代码

 

复制代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <deque>
using namespace std;

const int N=2e5+10;
int n,m,w[N],f[N];

int main(){
  cin>>n>>m;
  for(int i=1;i<=n;i++) cin>>w[i];
  
  int ans=2e9;
  deque<int> q;           //清空队列
  for(int i=1;i<=n;i++){  //枚举序列
    while(q.size()&&f[q.back()]>=f[i-1])q.pop_back(); //队尾出队(队列不空且新元素更优)
    q.push_back(i-1);                                 //队尾入队(存储下标 方便判断队头出队)
    if(q.front()<i-m) q.pop_front();                  //队头出队(队头元素滑出窗口)
    f[i]=f[q.front()]+w[i];                           
    if(i>n-m) ans=min(ans,f[i]);
  }
  cout<<ans;
}
复制代码

 

posted @   董晓  阅读(393)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 易语言 —— 开山篇
点击右上角即可分享
微信分享提示