单调队列 60分 卡了4个wa 求大佬解答(
查看原帖
单调队列 60分 卡了4个wa 求大佬解答(
1090625
njuptxzy楼主2024/8/20 15:40
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
typedef long long ll;
namespace IO {
	const int MAXSIZE = 1 << 20;
	char buf[MAXSIZE], * p1, * p2;
#define gc()                                                               \
  (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, MAXSIZE, stdin), p1 == p2) \
       ? EOF                                                               \
       : *p1++)

	ll rd() {
		ll x = 0, f = 1;
		char c = gc();
		while (!isdigit(c)) {
			if (c == '-') f = -1;
			c = gc();
		}
		while (isdigit(c)) x = x * 10 + (c ^ 48), c = gc();
		return x * f;
	}

	char pbuf[1 << 20], * pp = pbuf;

	void push(const char& c) {
		if (pp - pbuf == 1 << 20) fwrite(pbuf, 1, 1 << 20, stdout), pp = pbuf;
		*pp++ = c;
	}

	void write(int x) {
		static int sta[35];
		int top = 0;
		do {
			sta[top++] = x % 10, x /= 10;
		} while (x);
		while (top) push(sta[--top] + '0');
	}
}

int n, m;
int a[maxn];
int ans[maxn];
deque<int> qmin;
//维护一个从前往后是从小到大的一个序列;
void get_min() {
	qmin.clear();
	for (int i = 1; i <= n; i++) {
		if (qmin.empty()) {
			ans[i] = 0;
			qmin.push_back(i);
			continue;
		}
		int u = qmin.front();
		
		if (a[i] <= a[u]) {
			qmin.clear();
			qmin.push_front(i);
		}
		else {
			while (1) {
				int v = qmin.back();
				if (a[i] > a[v]) {
					qmin.push_back(i);
					break;
				}
				else {
					qmin.pop_back();//值相同的情况下优先储存新的
					v = qmin.back();
					continue;
				}
			}	
		}
		if (i - u >= m) {
			qmin.pop_front();
			u = qmin.front();
		}
		if (i >= m) {
			cout << a[u] << endl;
		}
	}
}

int main() {
	n = IO::rd();
	m = IO::rd();
	for (int i = 1; i <= n; i++) {
		a[i] = IO::rd();
	}
	get_min();
	return 0;
}
2024/8/20 15:40
加载中...