天气变化 (单调栈的简单应用)

总结:给出一个序列,让你求每一个数字左/右第一个比它大/小的数
总共有4种情况:(单调递增减从栈底开始)
右大:单调递减栈
右小:单调递增栈
左大:单调递减栈
左小:单调递增栈


原题地址:http://10.64.70.166/problem/1003
Description

给你一个n天的天气气温表, 你需要输出对于每一天,至少需要多少天才能升温,如果不会升温,这一天输出0。

Input

输入第一行n代表天数。第二行n个数a[i]代表当天气温。1 <= n <= 1,000,000a[i] < 1,000,000

Output

一行输出n个整数。第i个整数代表对于第i天还需要多少天才能升温。行末不要有多余空格。
思路:单调栈的应用之一,求某个数字最左边或者最右边比它大或小的位置.

#include <bits/stdc++.h>
#include <cmath>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <cctype>
#define eps 1e-8
#define INF 0x3f3f3f3f
#define MOD 1e9+7
#define PI acos(-1)
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define CLR(x,y) memset((x),y,sizeof(x))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int seed = 131;
const int maxn = 1e6 + 5;
int n;
stack<int>s;//单调递减栈
int a[maxn];
int ans[maxn];
int main() {
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) {
        scanf("%d", &a[i]);
    }
    s.push(n);
    for(int i = n - 1; i >= 1; i--) {
        while(!s.empty()&&a[s.top()] <= a[i]) s.pop();
        if(s.empty()) ans[i] = 0;
        else ans[i] = s.top() - i;
        s.push(i);
    }
    for(int i = 1; i < n; i++) printf("%d ", ans[i]);
    printf("%d\n", ans[n]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yiqzq/article/details/81511823