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

問題:

説明:

ステーキを一列に並べると、すべて右を向いています。背の高い牛は背の低い牛の視界を遮り、背の低い牛は背の高い牛に見えます。Σ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);
    }
}

 

おすすめ

転載: blog.csdn.net/qq_28033719/article/details/111562606