关于P1886 滑动窗口 /【模板】单调队列
这题快给我写吐了
单调队列模板题,我想试试用deque写
然后
#include <iostream>
#include <deque>
using namespace std;
deque<int> p;int l, r, n, k, a[1000001];
struct min_q
{
deque<int> d;
int front(){return d.front();}
void pop()
{
if(p.front() < l)
d.pop_front(), p.pop_front();
}
void push(int x)
{
if(!d.empty())
while(x < d.back())
{
d.pop_back();p.pop_back();
if(d.empty()) break;
}
d.push_back(x);
}
}x;
struct max_q
{
deque<int> d;
int front(){return d.front();}
void pop()
{
if(p.front() < l)
d.pop_front(), p.pop_front();
}
void push(int x)
{
if(!d.empty())
while(x > d.back())
{
d.pop_back();p.pop_back();
if(d.empty()) break;
}
d.push_back(x);
}
}y;
int main()
{
cin >> n >> k;r = k;
for(int i = 0;i < n;++i)
cin >> a[i];
for(int i = 0;i < k;++i)
x.push(a[i]), p.push_back(i);
cout << x.front() << " ";
for(int i = k;i < n;++i)
{
++l;++r;x.pop();
x.push(a[i]);p.push_back(i);
cout << x.front() << " ";
}
cout << endl;
l = 0;r = k;
while(!p.empty()) p.pop_back();
for(int i = 0;i < k;++i)
y.push(a[i]), p.push_back(i);
cout << y.front() << " ";
for(int i = k;i < n;++i)
{
++l;++r;y.pop();
y.push(a[i]);p.push_back(i);
cout << y.front() << " ";
}
return 0;
}
72行超短代码
这个故事告诉我们$STL$会增加代码长度
压了压行之后
#include <iostream>
#include <deque>
using namespace std;
deque<int> p;int l, r, n, k, a[1000001];
bool c1(int a, int b) {return a < b;}
bool c2(int a, int b) {return a > b;}
struct q
{
deque<int> d;bool (*c)(int a, int b);
q(bool (*b)(int a, int b)) {c = b;}
int front(){return d.front();}
void pop()
{
if(p.front() < l)
d.pop_front(), p.pop_front();
}
void push(int x)
{
if(!d.empty())
while((*c)(x, d.back()))
{
d.pop_back();p.pop_back();
if(d.empty()) break;
}
d.push_back(x);
}
}x(c1), y(c2);
void work(q z)
{
for(int i = 0;i < k;++i)
z.push(a[i]), p.push_back(i);
cout << z.front() << " ";
for(int i = k;i < n;++i)
{
++l;++r;z.pop();
z.push(a[i]);p.push_back(i);
cout << z.front() << " ";
}
}
int main()
{
cin >> n >> k;r = k;
for(int i = 0;i < n;++i)
cin >> a[i];
work(x);
cout << endl;
l = 0;r = k;
while(!p.empty()) p.pop_back();
work(y);
return 0;
}
不管怎么说反正这道题是A了