USACO 2009 Mar Silver 3.Look Up

本文介绍使用单调栈解决寻找每个元素左侧最近且比其高的元素的问题。具体为:对于N头编号为1到N的奶牛,每头奶牛有一个高度H_i,需找出每头奶牛左侧第一头比其高的奶牛的编号。文章提供了完整的C语言实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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

Output

* 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.

Sample Input

6
3
2
6
1
1
2

Sample Output

3
3
0
6
6
0

HINT

INPUT DETAILS:

FJ has six cows of heights 3, 2, 6, 1, 1, and 2.

 

OUTPUT DETAILS:

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.

求距离此点最近且比它高的点

可以用单调栈维护

有高的点直接比较大小之后赋值编号

#include<stdio.h>
int a[100001],s[100001],ans[100001],i,top;
int main()
{
	int n;
	scanf("%d",&n);
	for(i=1;i<=n;i++)
		scanf("%d",&a[i]);
	for(i=n;i>=0;i--)
	{
		while(top&&a[s[top]]<=a[i])
			top--;
		ans[i]=s[top];
		s[++top]=i;
	}	
	for(i=1;i<=n;i++)
		printf("%d\n",ans[i]);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值