滑动窗口

P1886 滑动窗口 /【模板】单调队列

 

 做题思路:

 

#include <bits/stdc++.h>
using namespace std;

#define int long long
const int maxn = 1e6 + 10;
int n,k,a[maxn];
deque<int> dp; //双端队列,普通队列队尾无法删除

signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> k;
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 1; i <= n; i++){
while(!dp.empty() && a[dp.back()] > a[i]) dp.pop_back();
while(!dp.empty() && i - dp.front() >= k) dp.pop_front();
dp.push_back(i);
if(i >= k) cout << a[dp.front()] << " ";
}
cout << endl;

dp.clear();
for(int i = 1; i <= n; i++){
while(!dp.empty() && a[dp.back()] < a[i]) dp.pop_back();
while(!dp.empty() && i - dp.front() >= k) dp.pop_front();
dp.push_back(i);
if(i >= k) cout << a[dp.front()] << " ";
}
return 0;
}

  

 

P1638 逛画展

 

#include <bits/stdc++.h>
using namespace std;

#define int long long
const int maxn = 1e6 + 10;
const int maxm = 2e3 + 10;
int n,m,a[maxn],cnt[maxm] = { 0 };

signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin >> n >> m;
	for(int i = 1; i <= n; i++) cin >> a[i];
	int l = 1, r = 1;
	int ansl = 0, ansr = 0;
	int ansmin = n + 1;
	int cnt_type = 0;
	while(r <= n){
		if(!cnt[a[r]]){
			cnt_type++;
		}
		cnt[a[r]]++;
		while(cnt_type == m){
			if(r - l + 1 < ansmin) {
				ansmin = r - l + 1;
				ansl = l;
				ansr = r;
			}
		
			cnt[a[l]]--;
			if(!cnt[a[l]]) cnt_type--;
			l++;
			
		}
		r++;
	}
	cout << ansl << " " << ansr << endl;
	return 0;
} 

  

posted @ 2025-09-15 14:43  Hazelxcf  阅读(6)  评论(0)    收藏  举报