问题:
说明:
牛排成一排,然后全部往右看,高的牛会挡住矮的牛视线,矮的牛会被高的牛看到,求 Σ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);
}
}