滑动窗口POJ2823

滑动窗口POJ2823

思路

题干在这:POJ2823
写一个单调队列就好

ac代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<queue>
#include<cstring>
#include<vector>
#define ll long long
#define N 1000010
using namespace std;
pair<int,int> high[N], low[N];
vector<int> h, l;
int px = 0, qx = 0;
int pi = 0, qi = 0;
int main() {
	int n, k;
	cin >> n >> k;
	for (int i = 0; i < n; i++) {
		int x;
		scanf_s("%d", &x);
		if (k == 1) {
			h.push_back(x);
			l.push_back(x);
			continue;
		}
		//最小值
		if (i == 0) {
			high[0].first = low[0].first = x;
			high[0].second = low[0].second = 0;
			continue;
		}
		if (low[qi].second - low[pi].second + 1 == k) {
			pi++;
		}
		if (x <= low[pi].first) {
			qi++;
			pi = qi;
			l.push_back(x);
			low[pi].first = x;
			low[pi].second = i;
		}
		else {
			while (qi > pi&& low[qi].first >= x)
				qi--;
			qi++;
			low[qi].first = x;
			low[qi].second = i;
			l.push_back(low[pi].first);
		}
		//最大值
		if (high[qx].second - high[px].second + 1 == k) {
			px++;
		}
		if (x >= high[px].first) {
			qx++;
			px = qx;
			h.push_back(x);
			high[px].first = x;
			high[px].second = i;
		}
		else {
			while (qx > px&& high[qx].first <= x)
				qx--;
			qx++;
			high[qx].first = x;
			high[qx].second = i;
			h.push_back(high[px].first);
		}
	}
	if (k == 1) {
		for (int i = 0; i < n ; i++) {
			printf("%d ", l[i]);
		}
		cout << endl;
		for (int i = 0; i < n ; i++) {
			printf("%d ", h[i]);
		}
		return 0;
	}
	for (int i = k - 2; i <= n - 2; i++) {
		printf("%d ",l[i]);
	}
	cout << endl;
	for (int i = k - 2; i <= n - 2; i++) {
		printf("%d ", h[i]);
	}
	return 0;
}
发布了24 篇原创文章 · 获赞 0 · 访问量 342

猜你喜欢

转载自blog.csdn.net/qq_45616764/article/details/104261425