【模板】单调栈
题目背景
模板题,无背景。
2019.12.12 更新数据,放宽时限,现在不再卡常了。
题目描述
给出项数为
定义函数
试求出
输入格式
第一行一个正整数
第二行
输出格式
一行
样例 #1
样例输入 #1
5
1 4 2 3 5样例输出 #1
2 5 4 5 0提示
【数据规模与约定】
对于
对于
对于
题解
#include<iostream>
#include<stack>
using namespace std;
const int N = 3e6 + 5;
int a[N], ans[N], n;
stack<int> s;
int main() {
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= n; i++) {
while (!s.empty() && a[s.top()] < a[i]) {
ans[s.top()] = i;//记录答案
s.pop();//弹出接着判断下一个
}
s.push(i);
}
for (int i = 1; i <= n; i++)
cout << ans[i] << ' ';
}P2866 [USACO06NOV] Bad Hair Day S
题目描述
农夫约翰有
每一头牛都站在同一排面朝右,它们被从左到右依次编号为
对于第
定义
输入格式
输入共
第一行为一个整数
接下来
输出格式
输出共一行一个整数,代表
输入输出样例 #1
输入 #1
6
10
3
7
4
12
2输出 #1
5说明/提示
数据规模与约定
对于
题解
维护一个单调递减的栈,每次统计当前牛能被之前哪些牛看到
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
void solve() {
int n;
cin >> n;
stack<int> s;
i64 ans = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
while (!s.empty() && s.top() <= x) { // 维护一个单调递减的栈
s.pop();
}
ans += s.size();
s.push(x);
}
cout << ans << "\n";
}
// 10 3 7 4 12 2
// ans=1+1+2+1=5
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int _ = 1;
// cin >> _;
while (_--) {
solve();
}
return 0;
}P2947 [USACO09MAR] Look Up S
题目描述
Farmer John's N (1 <= N <= 100,000) cows, conveniently numbered 1..N, are once again standing in a row. Cow i has height H_i (1 <= H_i <= 1,000,000).
Each cow is looking to her left toward those with higher index numbers. We say that cow i 'looks up' to cow j if i < j and H_i < H_j. For each cow i, FJ would like to know the index of the first cow in line looked up to by cow i.
Note: about 50% of the test data will have N <= 1,000.
约翰的
Input
输入格式
- * Line 1: A single integer: N
* Lines 2..N+1: Line i+1 contains the single integer: H_i
第
输出格式
* Lines 1..N: Line i contains a single integer representing the smallest index of a cow up to which cow i looks. If no such cow exists, print 0.
共
输入输出样例 #1
输入 #1
6
3
2
6
1
1
2输出 #1
3
3
0
6
6
0说明/提示
FJ has six cows of heights 3, 2, 6, 1, 1, and 2.
Cows 1 and 2 both look up to cow 3; cows 4 and 5 both look up to cow 6; and cows 3 and 6 do not look up to any cow.
【输入说明】
【输出说明】奶牛 #1,#2 仰望奶牛 #3,奶牛 #4,#5 仰望奶牛 #6,奶牛 #3 和 #6 没有仰望对象。
【数据规模】
对于
对于
对于
题解
维护一个单调递减的栈,如果当前牛的身高比栈顶的牛的身高高,就记录答案
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
void solve() {
int n;
cin >> n;
vector<int> a(n), ans(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
stack<int> stk;
for (int i = 0; i < n; i++) {
while (!stk.empty() && a[stk.top()] < a[i]) { // 维护一个单调递减的栈
ans[stk.top()] = i + 1;
stk.pop();
}
stk.push(i);
}
for (auto i : ans) {
cout << i << "\n";
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int _ = 1;
// cin >> _;
while (_--) {
solve();
}
return 0;
}