为什么单调栈中记录下标就对了,而记录数列中的数不对呢?
查看原帖
为什么单调栈中记录下标就对了,而记录数列中的数不对呢?
602372
Brilliant11001楼主2023/8/18 16:53

这是记录下标的:

#include <iostream>

using namespace std;
typedef unsigned long long ll;
const int N = 1000010;
ll stk[N], ans;
ll a[N];
int tt, n;
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin >> n;
	for(int i = 1; i <= n; i++) cin >> a[i];
	for(int i = 1; i <= n; i++) {
		if(!tt) {
			ans ^= i;
			stk[++tt] = i;
			cout << ans << endl;
		}
		else if(a[stk[tt]] > a[i]) {
			ans ^= i;
			stk[++tt] = i;
			cout << ans << endl;
		} 
		else {
			while(tt > 0 && a[stk[tt]] <= a[i]) ans ^= stk[tt], tt--;
			ans ^= i;
			stk[++tt] = i;
			cout << ans << endl; 
		}
	}
	return 0;
}

AC记录

这是记录数列中的数的:

#include <iostream>

using namespace std;
typedef unsigned long long ll;
const int N = 1000010;
ll stk[N], ans;
ll tt, n;
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin >> n;
	for(ll i = 1; i <= n; i++) {
		ll x;
		cin >> x;
		if(!tt) {
			ans ^= i;
			stk[++tt] = x;
			cout << ans << endl;
		}
		else if(stk[tt] > x) {
			ans ^= i;
			stk[++tt] = x;
			cout << ans << endl;
		} 
		else {
			while(tt > 0 && stk[tt] <= x) tt--;
			ans = i;
			stk[++tt] = x;
			cout << ans << endl; 
		}
	}
	return 0;
}

WA记录

为什么会这样呢?蒟蒻想了一中午+一下午都没想出来,求大佬指点。

2023/8/18 16:53
加载中...