单调栈做法全错,求调,测试了几组数据没问题呀。
查看原帖
单调栈做法全错,求调,测试了几组数据没问题呀。
172240
kuaiCreator楼主2024/10/4 17:18
#include <bits/stdc++.h>
using namespace std;
const int N = 300005;
int n, a[N], st[N], top, nxt[N], lst[N];
void work(int i) {
	int now = i, j;
	if (nxt[i]) {      //如果后面有大于等于a[x]的值
		do {
			j = nxt[now] - i;  //获得j的值
			if (a[i] <= j && j <= a[i + j]) {  //判断是否在a[]
				cout << 1 << " " << j << endl;
				return ;
			}
			now = nxt[now];
		} while (now);
	}
	now = i;
	if (lst[i]) {
		do {
			j = lst[now] - i;
			if (a[i] <= j && j <= a[i + j]) {
				cout << 1 << " " << j << endl;
				return ;
			}
			now = lst[now];
		} while (now);
	}
	cout << 0 << endl;
}
//void test() {
//	cout << "a[]  ";
//	for (int i = 1; i <= n; i++) cout << setw(3) << a[i] << " ";
//	cout << endl << "nxt  ";
//	for (int i = 1; i <= n; i++) cout << setw(3) << nxt[i] << " ";
//	cout << endl << "lst  ";
//	for (int i = 1; i <= n; i++) cout << setw(3) << lst[i] << " ";
//	cout << endl;
//}
int main() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
	}
	for (int i = 1; i <= n; i++) {
		while (top && a[st[top]] <= a[i]) {
			nxt[st[top]] = i;  //记录比当前栈顶元素后更大元素的下标
			top--;
		}
		st[++top] = i;
	}
	top = 0;
	for (int i = 1; i <= n; i++) {
		while (top && a[st[top]] < a[i])top--;
		if (top) lst[i] = st[top];
		st[++top] = i;
	}

	for (int i = 1; i <= n; i++)
		work(i);

//	test();
	return 0;
}
2024/10/4 17:18
加载中...