DP/單調隊列::poj3250 Bad Hair Day

来源:互联网 发布:74153数据选择器 编辑:程序博客网 时间:2024/05/23 14:47
 

题目:

Some of Farmer John's N cows (1 ≤ N ≤ 80,000) are having a bad hair day! Since each cow is self-conscious about her messy hairstyle, FJ wants to count the number of other cows that can see the top of other cows' heads.

Each cow i has a specified height hi (1 ≤ hi≤ 1,000,000,000) and is standing in a line of cows all facing east (to the right in our diagrams). Therefore, cowi can see the tops of the heads of cows in front of her (namely cows i+1, i+2, and so on), for as long as these cows are strictly shorter than cowi.

Let ci denote the number of cows whose hairstyle is visible from cowi; please compute the sum ofc1 throughcN.

分析:用DP去做,r[i]表示从右数第一个比a[i]大的数的前一个数的位置,则当a[i]<a[r[i]+1]时有r[i]=r[r[i]+1]. 求出了数组r[i]之后累加即可。一开始我把遍历的顺序弄错了,为for i=1..N,结果“Time Limit Exceeded”因为这里的DP根本不起作用,还是重复计算了!改了之后就对了,代码如下(Memory: 876K,Time: 641MS)

#include <iostream>using namespace std;unsigned long a[80001];unsigned long r[80001];unsigned long sum=0;int main(){int N;cin>>N;for(int i=1;i<=N;i++){cin>>a[i];r[i]=i;}for(int i=N-1;i>=0;i--){while(r[i]<N && a[r[i]+1]<a[i]){r[i]=r[r[i]+1];}sum+=r[i]-i;}cout<<sum;return 0;}


 本题最好的方法还是用单调队列,因为上面DP的实现效率不是很高,也不容易分析。单调队列的话,其实和在hist中找最大矩形的方法一样的。这里不在重复。