您的位置:首页 > 运维架构

hihocoder - 股票价格3 - 维护栈 & 线段树

2017-11-05 15:58 260 查看

题目

时间限制:10000ms

单点时限:1000ms

内存限制:256MB

描述

小Hi最近在关注股票,为了计算股票可能的盈利,他获取了一只股票最近N天的价格A1~AN。

小Hi想知道,对于第i天的股票价格Ai,几天之后股价会第一次超过Ai。

假设A=[69, 73, 68, 81, 82],则对于A1=69,1天之后的股票价格就超过了A1;对于A2=73,则是2天之后股票价格才超过A2。

输入

第一行包含一个整数N。

以下N行每行包含一个整数Ai。

对于50%的数据,1 ≤ N ≤ 1000

对于100%的数据,1 ≤ N ≤ 100000, 1 ≤ Ai ≤ 1000000

输出

输出N行,其中第i行代表对于第i天的股票价格Ai,几天之后股价会第一次超过Ai。

如果Ai+1~AN之内没有超过Ai,输出-1。

样例输入

5

69

73

68

81

82

样例输出

1

2

1

1

-1

题解

单调栈法

#include<stdio.h>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#include<stack>
#include<deque>
using namespace std;
typedef long long LL;
#define ms(a,b) memset(a,b,sizeof(a))
#define eps 1e-8

const int maxn=1e5+100;
int A[maxn];
int B[maxn];

int main() {
int n;
cin>>n;
for(int i=0;i<n;i++) cin>>A[i];
stack<pair<int,int> >s;
for(int i=0;i<n;i++){
if(s.empty() || s.top().first>=A[i]){
s.push({A[i],i});
}else{
while(!s.empty() && s.top().first<A[i]){
B[s.top().second]=i-s.top().second;
s.pop();
}
s.push({A[i],i});
}
}
while (!s.empty()) {
B[s.top().second] = -1;
s.pop();
}
for(int i=0;i<n;i++) printf("%d\n",B[i]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: