股票价格3 HihoCoder - 1620

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

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

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

Input

第一行包含一个整数N。  

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

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

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

Output

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

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

Sample Input

5  
69  
73  
68  
81  
82

Sample Output

1  
2  
1  
1  
-1

地址:https://cn.vjudge.net/contest/244831#problem/A

方法:倒去多余,小填大换(运用栈)

#include<stdio.h>
const int max=1e5+5;
int a[max],b[max];//b 是答案
int s[max];
int main()
{
	int top=-1,n,i;
	scanf("%d",&n);
    for(i=0;i<n;i++)
		scanf("%d",a+i);
	for(i=n-1;i>=0;i--)//这就是   倒去多余
	{
		while(a[s[top]]<=a[i]&&top!=-1)//与栈中元素比较,找到股票大于他的(栈不为空)
			top--;
		if(top==-1)//没有比他大的,当然就置-1了
			b[i]=-1;
		else
			b[i]=s[top]-i;//找到了,赋值   s[top]存的是下标
		s[++top]=i;
	}
	for(i=0;i<n;i++)
		printf("%d\n",b[i]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/shenyulingyeye/article/details/81514706