C++滑动门问题(附两种方法)

题目如下:

滑动窗口 - 题目 - Liuser's OJ

------引用自OJ网站

方法如下:

1.常规思想

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n,k;
	int a[110];
	cin>>n>>k;
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
	}
	for(int i=0;i<n-k;i++)
	{
		int ma=-1;
		for(int j=i;j<i+k;j++)
		{
			ma=max(ma,a[j]);
		}
		cout<<ma<<endl;
	}
	
	
	
	return 0;
}

做起来很简单,缺点也很明显

时间复杂度太高

遇到极端数据就会出错

2.栈思想

cpp 复制代码
#include<bits/stdc++.h>
#include<stack>
using namespace std;
int a[110];
int ma[110];
int n,k;
int l=0;
int main()
{
	stack<int> s;
	stack<int> ss;
	cin>>n>>k;
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
	}
	for(int i=0;i<k;i++)
	{
		if(s.empty()==true||s.top()<=a[i])
		{
			s.push(a[i]);
		}
		else if(s.top()>a[i])
		{
			int t=0;
			while(!(s.empty()==true||s.top()<=a[i]))
			{
				ss.push(s.top());
				s.pop();
				t++;
			}
			s.push(a[i]);
			for(int j=0;j<t;j++)
			{
				s.push(ss.top());
				ss.pop();
			}
		}
	}
	ma[++l]=s.top();
	while(s.empty()!=true)
	{
		ss.push(s.top());
		s.pop();
	}
	cout<<ss.top()<<" ";
	while(ss.empty()!=true)
	{
		s.push(ss.top());
		ss.pop();
	}
	for(int i=k;i<n;i++)
	{
		while(true)
		{
			if(a[i-k]==s.top())
			{
				s.pop();
				break;
			}
			ss.push(s.top());
			s.pop();
		}
		if(s.empty()==true)
		{
			s.push(ss.top());
			ss.pop();
		}
		if(a[i]<s.top())
		{
			while(true)
			{
				if(s.empty()==true)
				{
					s.push(a[i]);
					break;
				}
				if(a[i]<s.top())
				{
					ss.push(s.top());
					s.pop();
				}
				else
				{
					s.push(a[i]);
					break;
				}
			}
		}
		else if(a[i]>=s.top())
		{
			if(ss.empty()==true)
			{
				s.push(a[i]);
			}
			else
			{
				while(true)
				{
					if(ss.empty()==true)
					{
						s.push(a[i]);
						break;
					}
					if(ss.top()<=a[i])
					{
						s.push(ss.top());
						ss.pop();
					}
					else
					{
						s.push(a[i]);
						break;
					}
				}
			}
		}
		while(ss.empty()!=true)
		{
			s.push(ss.top());
			ss.pop();
		}
		ma[++l]=s.top();
		while(s.empty()!=true)
		{
			ss.push(s.top());
			s.pop();
		}
		cout<<ss.top()<<" ";
		while(ss.empty()!=true)
		{
			s.push(ss.top());
			ss.pop();
		}
	}
	cout<<endl;
	for(int i=1;i<=l;i++)
	{
		cout<<ma[i]<<" ";
	}
	
	
	return 0;
}

虽然写起来有亿点点麻烦,但是胜在稳定

!!!注意 !!!

作者写代码的时候没有注意数据范围,在网站里测试的时候会出错

自己在网站里测试的时候记得根据实际情况调整数据范围!!!!

相关推荐
闲人编程6 分钟前
Python第三方库IPFS-API使用详解:构建去中心化应用的完整指南
开发语言·python·去中心化·内存·寻址·存储·ipfs
CTRA王大大1 小时前
【golang】制作linux环境+golang的Dockerfile | 如何下载golang镜像源
linux·开发语言·docker·golang
zhangfeng11332 小时前
以下是基于图论的归一化切割(Normalized Cut)图像分割工具的完整实现,结合Tkinter界面设计及Python代码示
开发语言·python·图论
还梦呦3 小时前
2025年09月计算机二级Java选择题每日一练——第五期
java·开发语言·计算机二级
鱼鱼说测试4 小时前
postman接口自动化测试
开发语言·lua
從南走到北4 小时前
JAVA国际版东郊到家同城按摩服务美容美发私教到店服务系统源码支持Android+IOS+H5
android·java·开发语言·ios·微信·微信小程序·小程序
_不会dp不改名_4 小时前
C++ 20: Concepts 与Requires
开发语言·c++20
韭菜钟5 小时前
Qt从qmake迁移到cmake的记录
开发语言·qt
重启的码农5 小时前
llama.cpp 分布式推理介绍(7) 远程后端缓冲区 (RPC Buffer)
c++·人工智能·神经网络
Vect__5 小时前
链表漫游指南:C++ 指针操作的艺术与实践
数据结构·c++·链表