Apple Catching

来源:互联网 发布:onvif java类库 编辑:程序博客网 时间:2024/05/16 15:21

题目:It is a little known fact that cows love apples. Farmer John has two apple trees (which are conveniently numbered 1 and 2) in his field, each full of apples. Bessie cannot reach the apples when they are on the tree, so she must wait for them to fall. However, she must catch them in the air since the apples bruise when they hit the ground (and no one wants to eat bruised apples). Bessie is a quick eater, so an apple she does catch is eaten in just a few seconds.

Each minute, one of the two apple trees drops an apple. Bessie, having much practice, can catch an apple if she is standing under a tree from which one falls. While Bessie can walk between the two trees quickly (in much less than a minute), she can stand under only one tree at any time. Moreover, cows do not get a lot of exercise, so she is not willing to walk back and forth between the trees endlessly (and thus misses some apples).

Apples fall (one each minute) for T (1 <= T <= 1,000) minutes. Bessie is willing to walk back and forth at most W (1 <= W <= 30) times. Given which tree will drop an apple each minute, determine the maximum number of apples which Bessie can catch. Bessie starts at tree 1.

import java.util.Scanner;public class AppleCatching {    public static void main(String[] args) {        Scanner input=new Scanner(System.in);        int t=input.nextInt();        int w=input.nextInt();        int dp[][][]=new int[1010][35][2];//i表示第i个时刻,j表示走了j步,k表示在那棵树下面。        int tree[]=new int[1010];//tree[i]表示第i个时刻苹果在那棵树落下        for (int i = 0; i < 1010; i++) {//将数组清0            for (int j = 0; j < 35; j++) {                for (int k = 0; k < 2; k++) {                    dp[i][j][k]=0;                }            }        }        for (int i = 1; i <= t; i++) {            tree[i]=input.nextInt()-1;        }        int count=0;        for (int i = 1; i <= t; i++) {            for (int j = 0; j < 35; j++) {                for (int k = 0; k < 2; k++) {                    int temp;                    if (tree[i]==k) {//当人刚好站在树下                         temp=j>0?dp[i-1][j-1][1-k]+1:1;//如果没移动过 则获得苹果树为1 否则在第i-1在移动情况的获得苹果数基础上加1                         dp[i][j][k]=max(dp[i-1][j][k]+1,temp);//比较移动还是不移动情况下的苹果数 求最大获得的苹果数                    }else {                        temp=j>0?dp[i-1][j-1][1-k]:0;//如果没移动过 则获得苹果树为0 否则等于第i-1移动情况的获得苹果数                        dp[i][j][k]=max(dp[i-1][j][k],temp);//求最大获得的苹果数                    }                    if (dp[i][j][k]>count && ((k==1 && j<w) || (k==0 && j<=w))) {                        count=dp[i][j][k];                    }                }            }        }        System.out.println(count);        // TODO Auto-generated method stub    }    public static int max(int n,int t){        if (n>t) {            return n;        }else{            return t;        }    }}