[poj.org- C++&Java]Bad Hair Day(看牛)

本文针对牛视距问题,提出了一种使用单调栈算法解决的方法。通过对牛的高度进行排序,利用单调栈找出每头牛能看到的其他牛的数量,并提供C++及Java实现代码。

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

问题:

说明:

牛排成一排,然后全部往右看,高的牛会挡住矮的牛视线,矮的牛会被高的牛看到,求 Σ0 ~ N 被高的牛看到牛匹数。

问题链接:http://poj.org/problem?id=3250

提交记录:

http://poj.org/showsource?solution_id=22224843

http://poj.org/showsource?solution_id=22225108

输入案例:

 

输入:
牛数量:6
牛的高度分别为
10
3
7
4
12
2

被看到的匹数:
5

解释:
Cow#1 can see the hairstyle of cows #2, 3, 4
Cow#2 can see no cow's hairstyle
Cow#3 can see the hairstyle of cow #4
Cow#4 can see no cow's hairstyle
Cow#5 can see the hairstyle of cow 6
Cow#6 can see no cows at all!

我的代码:

我感受到了没有数据和异常的痛苦,哪怕单调栈是很简单,但是我就是AC不了,不能脑内运行虚拟机和跑串我也是佛了。

其实就是单调栈的用法,创建一个栈,只保留从高到低的一系列元素即可,这就是单调栈。

1、每进来一个元素都比较下栈顶,如果大的就统计看牛头数,然后小的弹栈,直到可以压栈。

2、最后把栈内剩下的再和总牛数比较下即可。

C++:

#include <iostream>
int main()
{
	int n, top = -1, *stack, *height;
	unsigned long long res = 0;
	scanf_s("%d", &n);
	stack = new int[n], height = new int[n];
	for (int i = 0; i < n; i++) {
		scanf_s("%d", &height[i]);
		while (top >= 0 && height[i] >= height[stack[top]]) // 这里忘了要 >= ,坑死了
			res += i - stack[top--] - 1;
		stack[++top] = i;
	}
	while (top >= 0) res += n - stack[top--] - 1;
	printf("%lld\n", res);
	return 0;
}

Java:

import java.util.Scanner;

public class Main {
    private static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        int n, top;
        long res;
        n = sc.nextInt();
        int[] stack = new int[n], height = new int[n];
        top = 0;
        res = 0;
        stack[top] = 0;
        height[0] = sc.nextInt();
        for (int i = 1; i < n; i++) {
            height[i] = sc.nextInt();
            while (top >= 0 && height[i] >= height[stack[top]])
                res += i - stack[top--] - 1;
            stack[++top] = i;
        }
        while (top >= 0) res += n - stack[top--] - 1;
        System.out.println(res);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值