P1886&&POJ2823 [Sliding Window/[Template] Monotonic Queue]

Sliding window/【template】monotonic queue

topic

Sliding window/【template】monotonic queue


Parsing

Monotonic Queue Template Question:
Monotonic Queue : Implemented with a double-ended queue. When taking the value, it is taken from the head of the queue. When inserting the value, all the values ​​at the end of the queue are thrown out to maintain the monotonic increase/decrease. The
magic is, Luogu’s question, including pictures, are all directly copied from POJ, but Luogu’s scribbling can be passed, POJ must speed up the reading. The most important thing is that POJ gave 12 seconds, Luogu only 1 second...
In contrast to the program efficiency , The same is fast reading, fast loss, Konjac, my program POJ uses 750MS, and a certain sentence of the program POJ actually uses 11922MS (it’s almost a T)
"The Peak of Life"

code:

#include<cstdio>
#include<deque>
using namespace std;
bool isdigit(char x){
    
    return (x<'0'|x>'9')?0:1;}
int n,m,a[1000010],b[1000010];
deque <int> c,d;//c递减,d递增
inline int read()
{
    
    
	int num=0,f=1;
	char c=0;
	while(!isdigit(c=getchar())){
    
    if(c=='-')f=-1;}
	while(isdigit(c))num=(num<<1)+(num<<3)+(c&15),c=getchar();
	return num*f;
}
inline void write(int x)
{
    
    
	int F[20];
	int tmp=x>0?x:-x;
	if(x<0)putchar('-');
	int cnt=0;
	while(tmp>0){
    
    F[cnt++]=tmp%10+'0';tmp/=10;}
	while(cnt>0)putchar(F[--cnt]);
	if(x==0)putchar('0');
	putchar(' ');//手动添加
}//高质量的快读快输
int main()
{
    
    
	n=read(),m=read();
	for(int i=1;i<=n;i++)a[i]=read();
	for(int i=1;i<m;i++)
	{
    
    
		while(!c.empty()&&a[c.back()]>a[i])c.pop_back();
		c.push_back(i);
		while(!d.empty()&&a[d.back()]<a[i])d.pop_back();
		d.push_back(i);//压入值
	}
	for(int i=m;i<=n;i++)
	{
    
    
		while(!c.empty()&&a[c.back()]>a[i])c.pop_back();
		c.push_back(i);
		while(!d.empty()&&a[d.back()]<a[i])d.pop_back();
		d.push_back(i);//压入
		while(!c.empty()&&c.front()<=i-m)c.pop_front();
		while(!d.empty()&&d.front()<=i-m)d.pop_front();
		b[i]=a[d.front()],write(a[c.front()]);//取出
	}
	printf("\n");
	for(int i=m;i<=n;i++)write(b[i]);//注意先最小再最大
	return 0;
}

Guess you like

Origin blog.csdn.net/zhanglili1597895/article/details/113096974