- C++
单调栈
- 2024-1-28 18:37:23 @
给定一个长度为 N 的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出 **−**1−1。
输入格式
第一行包含整数 N,表示数列长度。
第二行包含 N 个整数,表示整数数列。
输出格式
共一行,包含 N 个整数,其中第 i 个数表示第 i 个数的左边第一个比它小的数,如果不存在则输出 **−**1−1。
数据范围
1≤N≤10 1**≤数列中元素≤109**1≤数列中元素≤109
输入样例:
5
3 4 2 7 5
输出样例:
-1 3 -1 2 2
参考代码:
#include <iostream>
using namespace std;
const int N = 100010;
int stk[N], tt;
int main()
{
int n;
cin >> n;
while (n -- )
{
int x;
scanf("%d", &x);
while (tt && stk[tt] >= x) tt -- ;
if (!tt) printf("-1 ");
else printf("%d ", stk[tt]);
stk[ ++ tt] = x;
}
return 0;
}
2 条评论
-
mrhowe SU @ 2024-1-30 20:20:35已修改
P2866 [USACO06NOV] Bad Hair Day S[
[USACO06NOV] Bad Hair Day S](https://www.luogu.com.cn/problem/P2866)
#include <iostream> using namespace std; const int N = 100010; long long res; int stk[N], tt; int main() { int n; cin >> n; while (n -- ) { int x; scanf("%d", &x); while (tt && stk[tt] <= x) tt -- ; res+=tt; stk[ ++ tt] = x; } cout<<res; return 0; }
-
2024-1-30 19:43:17@
#include <iostream> using namespace std; const int N = 100010; int stk[N], tt; int main() { int n; cin >> n; while (n -- ) { int x; scanf("%d", &x); while (tt && stk[tt] >= x) { cout<<"出栈位置:"<<tt<<"出栈数字:"<<stk[tt]<<endl; tt -- ; } if (!tt) printf("-1 "); else printf("%d左边最大的是: %d \n", x,stk[tt]); stk[ ++ tt] = x; cout<<"入栈位置:"<<tt<<"入栈数字:"<<stk[tt]<<endl; } return 0; }
- 1