参考博客:2019年4月11日单调队列讲义大佬讲的非常好,如果没看懂,B站上搜《大雪菜》,讲的非常的屌
题目:逛画展
代码:
#include<bits/stdc++.h>
using namespace std;
#define LL long long
const int maxn = 1e6+10;
int a[maxn], vis[2005];
deque<int>q;
int main(){
int n, m;
ios::sync_with_stdio(false);
cin>>n>>m;
for(int i = 1; i <= n; i++){
cin>>a[i];
}
memset(vis, 0, sizeof(vis));
int cn = 0, x, y, ans = 1e9;
for(int i = 1; i <= n; i++){
if(!vis[a[i]])cn++;//判断之前出没出现过
q.push_back(i);
vis[a[i]]++;//统计出现的个数
while(vis[a[q.front()]] >= 2){//如果出现的次数大于2就弹出队首
vis[a[q.front()]]--;//出现的次数减1
q.pop_front();
}
while(cn >= m && q.back() - q.front() +1 < ans){//如果cn大于或者m的时候出现出现不同数的次数一定会是大于等于m的
//因为当cn == m的时候接着向后移动的时候cn也一定会大于等于m的,因为最坏的情况下是加入一个删除一个
ans = q.back() - q.front() + 1;
x = q.back();
y = q.front();
}
}
cout<<y<<" "<<x<<endl;
return 0;
}
题目:切蛋糕
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 5000010;
typedef long long LL;
int a[maxn];
LL sum[maxn];
deque<int>q;
int main()
{
ios::sync_with_stdio(false);
int n, m;
cin>>n>>m;
for(int i = 1; i <= n; i++)
{
cin>>a[i];
sum[i] = sum[i-1] + a[i];//前缀和
}
LL MAX = 0;
for(int i = 1; i <= n; i++)
{
while(q.size() && i - q.front() > m)
{
q.pop_front();
}
while(q.size() && sum[i] <= sum[q.back()])//
{
q.pop_back();
}
q.push_back(i);
if(q.size())MAX = max(MAX, sum[i]-sum[q.front()]);
}
cout<<MAX<<endl;
return 0;
}