【模版】单调栈求救RE

#include <bits/stdc++.h>
using namespace std;
int a[3000005],f[3000005];
stack<int> st;
int main(){
    int n;
	cin>>n;
	for(int i=1;i<=n;i++){
        cin>>a[i];
    }
	for(int i=n;i>=1;i--){
		while(a[i]>a[st.top()]&&!st.empty()){
            st.pop();
        }
		if(!st.empty()){
            f[i]=st.top();
        }
		st.push(i);
	}
	for(int i=1;i<=n;i++){
        cout<<f[i]<<" ";
    }
}

送积分。题面:

1 个赞

把这个改成 !st.empty()&&a[i]>a[st.top()]

1 个赞

这里要插一个f[st.top()]=i;

1 个赞

而且i要从小到大

1 个赞

把这个if去掉

1 个赞

因为如果栈是空的,那么这里会先执行a[i]>a[st.top()],st.top()没有返回值

3 个赞
// 改了WA10
#include <bits/stdc++.h>
using namespace std;
int a[3000005],f[3000005];
stack<int> st;
int main(){
    int n;
	cin>>n;
	for(int i=1;i<=n;i++){
        cin>>a[i];
    }
	for(int i=n;i>=1;i--){
		while(!st.empty()&&a[i]>a[st.top()]){
            st.pop();
        }
		if(!st.empty()){
            f[i]=st.top();
        }
		st.push(i);
	}
	for(int i=1;i<=n;i++){
        cout<<f[i]<<" ";
    }
}
1 个赞

改成1~n

1 个赞

这个删掉

1 个赞

我代码就这么短,直接把我代码改成你代码了 :smiling_face_with_tear:

1 个赞

我来助你

1 个赞

那咋了?
你的目标不是AC吗?

1 个赞

楼主在我的帮助下已经AC了

1 个赞

在线下

1 个赞

不是,线下的也算???

1 个赞

那也得算我一半吧

1 个赞

我来晚了

2 个赞

我不需要把我的代码变成第二个你的代码,我需要将他变成第一个我的代码,此贴结

1 个赞

是调代码而不是AC,如果这样的话,老师为什么还要给我们讲题而不是直接把代码贴给我们

1 个赞

但问题是我的建议有用啊?
楼主不采纳应该不算我的事吧……

1 个赞