java实现:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class 粉刷栅栏 {
private static int sum = 0;
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
ArrayList<Integer>A = new ArrayList<Integer>();
int n ;
n = in.nextInt();
int element;
for (int i = 0; i < n; i++) {
element = in.nextInt();
A.add(element);
}
paint(A, 0, n-1);
System.out.println(sum);
}
public static void paint(ArrayList<Integer>A, int left, int right) {
if (left > right) {
return;
}
if (left == right) {
sum ++;
}
else {
int max = Collections.max(A);
int index = A.indexOf(max);
if (max > A.size()) {
sum ++;
paint(A, left, index - 1);
paint(A, index + 1, right);
} else {
ArrayList<Integer> ZeroOf = new ArrayList<Integer>();
for (int i = left; i <= right; i++) {
int value = A.get(i);
value --;
A.set(i, value);
if (value == 0) {
ZeroOf.add(i);
}
}
if (!ZeroOf.isEmpty()) {
paint(A, left, ZeroOf.get(0));
int j = 1;
for (; j < ZeroOf.size(); j++) {
paint(A, ZeroOf.get(j-1)+1, ZeroOf.get(j) - 1);
}
paint(A, ZeroOf.get(j - 1) + 1, right);
}
}
}
}
}