2 solutions
-
1
注释版,易理解
#include<bits/stdc++.h> using namespace std; const int N=1e5+10; int s[N],t; // s[]模拟栈,t为栈顶指针,t=0代表栈空 int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); // 输入输出加速,处理1e5大数据 int n; cin>>n; // 依次遍历每一个数字 for(int i=1;i<=n;i++){ int x; cin>>x; // 单调栈核心:栈不为空,且栈顶元素 >= 当前x,直接弹出 // 因为栈顶元素比x大,它不可能成为后面元素的"左边更小值",直接舍弃 while(t&&s[t]>=x){ t--; } // 栈不为空:栈顶就是左边第一个比x小的数 if(t){ cout<<s[t]<<" "; } // 栈空:左边没有比x小的数字,输出-1 else{ cout<<"-1 "; } // 将当前x压入栈,供后面的数字查询使用 s[++t]=x; } return 0; }精简版,可以直接使用
#include<bits/stdc++.h> using namespace std; const int N=1e5+10; int s[N],t; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int n,cin>>n; for(int i=1;i<=n;i++){ int x; cin>>x; while(t&&s[t]>=x) t--; if(t) cout<<s[t]<<" "; else cout<<"-1 "; s[++t]=x; } return 0; } -
0
#include<bits/stdc++.h> using namespace std; const int N=1e5+10; int stk[N],tt; //单调栈结构 int main() { int n; cin>>n; for(int i=1;i<=n;i++) { int x; cin>>x; while(tt&&stk[tt]>=x) tt--; //栈中元素大于等于当前元素(一定不可能是答案) if(tt) cout<<stk[tt]<<" "; //如果栈中还有元素,一定比当前元素小 else cout<<"-1 "; //输出无解 stk[++tt]=x; //记录当前元素 } return 0; }
- 1
Information
- ID
- 334
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 5
- Tags
- # Submissions
- 12
- Accepted
- 7
- Uploaded By