Fata7y Ya Warda! SPOJ - DRUIDEOI 单调栈
题意:1e5个数围成一个环。现在要输出每个数左右第一个大于它的数的下标。若没有,则输出-1.
题解:单调栈板题。只是要把数据压入栈压两遍来模仿环。
具体分析:考虑一个递减的数列。要找左边最大的数,我们从左到右对于每一个数,只要往回枚举一步就能找到,时间复杂度为O(n);
考虑一个递增的数列。同样用暴力枚举,每次都要找到头(尾),复杂度为O(n*n); 如何优化?
我们发现在递增数列的例子中如果a[N]一直遍历到头才停止,那么只要a[N+1]>a[N],就可以直接跳过之前的n-1次遍历。
那如何记录“一直遍历到某点才停止”呢?
一种方法是写一个数组,记录可以走到最远的地方有点记忆递归的意思。
另一种就是把遍历过的数全删光,这就是单调栈的思想。
#define _CRT_SECURE_NO_WARNINGS #include<cstring> #include<cctype> #include<cmath> #include<cstdio> #include<string> #include<stack> #include<ctime> #include<list> #include<set> #include<map> #include<queue> #include<vector> #include<sstream> #include<iostream> #include<algorithm> #define INF 0x3f3f3f3f #define N 1111 #define eps 1e-6 #define pi acos(-1.0) #define e exp(1.0) //std::ios::sync_with_stdio(false); using namespace std; const int maxn = 1e5 + 5; const int mod = 1e9 + 7; typedef long long ll; typedef unsigned long long ull; stack<int>s; deque<int>l, r; int h[maxn]; #define ONLINE_JUDGE int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); long _begin_time = clock(); #endif int t; cin >> t; while (t--) { int n; while (!s.empty())s.pop(); l.clear(), r.clear(); cin >> n; int mx = 0, mxi = 0; for (int i = 1; i <= n; i++) { scanf("%d", &h[i]); while (!s.empty() && h[s.top()] <= h[i])s.pop(); s.push(i);//存 个下降子序列 末位是最高的那个 } for (int i = 1; i <= n; i++) { while (!s.empty() && h[s.top()] <= h[i])s.pop(); if (!s.empty())l.push_back(s.top()); else l.push_back(-1); s.push(i); } while (!s.empty())s.pop(); for (int i = n; i > 0; i--) { while (!s.empty() && h[s.top()] <= h[i])s.pop(); s.push(i); } for (int i = n; i > 0; i--) { while (!s.empty() && h[s.top()] <= h[i])s.pop(); if (!s.empty())r.push_front(s.top()); else r.push_front(-1); s.push(i); } int sz = l.size(); for (int i = 0; i < sz; i++) { printf("%d %d\n", l[i], r[i]); } } #ifndef ONLINE_JUDGE long _end_time = clock(); printf("time = %ld ms.", _end_time - _begin_time); #endif return 0; }
成功的路并不拥挤,因为大部分人都在颓(笑)
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 历时 8 年,我冲上开源榜前 8 了!
· 物流快递公司核心技术能力-海量大数据处理技术
· 四大AI编程工具组合测评
· 关于能否用DeepSeek做危险的事情,DeepSeek本身给出了答案
· 如何在 Github 上获得 1000 star?