2013
11-12

# POJ 3250 Bad Hair Day [解题报告] Java

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, cow i 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 cow i.

Consider this example:

        ==       ==   -   =         Cows facing right -->=   =   == - = = == = = = = =1 2 3 4 5 6

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!

Let ci denote the number of cows whose hairstyle is visible from cow i; please compute the sum of c1 through cN.For this example, the desired is answer 3 + 0 + 1 + 0 + 1 + 0 = 5.

Line 1: The number of cows, N.

Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i.

Line 1: A single integer that is the sum of c1 through cN.

6
10
3
7
4
12
2

5

/* @author: */
(1)
import java.util.Scanner;
import java.util.Arrays;
public class Main{

public static void main(String args[])
{
Scanner sc=new Scanner(System.in);

int n,i;
int p[]=new int[80010],q[]=new int[80010];
n=sc.nextInt();
for(i=0;i< n;i++)
p[i]=sc.nextInt();
for(i=0;i< n;i++) q[i]=1;
p[n]=1000000010;
for(i=n-1;i>=0;i--)
{
int u=p[i+1];
while(p[i]>p[i+q[i]])
q[i]+=q[i+q[i]];
}
long  total=0;
for(i=0;i< n;i++)
total+=q[i];
total-=n;
System.out.printf("%d\n",total);
}
}

(2)
import java.util.Scanner;
import java.util.Arrays;
public class Main{
static final int maxn=80001;
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int h[]=new int[maxn];
int next[]=new int[maxn];
int s[]=new int[maxn];
int i, k, n;
long  sum;
while(sc.hasNext()){
Arrays.fill(next,0);
Arrays.fill(s,0);
n=sc.nextInt();
for(i = 0; i < n; i++){
h[i]=sc.nextInt();
s[i] = 0;
}

for (i = n - 1, sum = 0; i >= 0; i--) {
k = i + 1;
for (; k < n && h[k] < h[i]; k = next[k]){
s[i] += s[k] + 1;
}
next[i] = k;
sum += s[i];
}
System.out.printf("%d\n", sum);
}
}
}

1. 有一点问题。。后面动态规划的程序中
int dp[n+1][W+1];
会报错 提示表达式必须含有常量值。该怎么修改呢。。

2. 网站做得很好看，内容也多，全。前段时间在博客园里看到有人说：网页的好坏看字体。觉得微软雅黑的字体很好看，然后现在这个网站也用的这个字体！nice!