2013
11-11

Apple Catching

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.

* Line 1: Two space separated integers: T and W

* Lines 2..T+1: 1 or 2: the tree that will drop an apple each minute.

* Line 1: The maximum number of apples Bessie can catch without walking more than W times.

7 2
2
1
1
2
2
1
1

6

INPUT DETAILS:

Seven apples fall – one from tree 2, then two in a row from tree 1, then two in a row from tree 2, then two in a row from tree 1. Bessie is willing to walk from one tree to the other twice.

OUTPUT DETAILS:

Bessie can catch six apples by staying under tree 1 until the first two have dropped, then moving to tree 2 for the next two, then returning back to tree 1 for the final two.

//* @author: ccQ.SuperSupper
import java.io.*;
import java.util.*;

public class Main {

/**
* @param args
*/
public static int max(int x,int y)
{
if(x>y) return x;
return y;
}

public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub

int t,w,i,j,k,ans=0;
int dp[][][]=new int[1005][35][2];
int way[]=new int[1005];

for(i=0;i< 1005;++i) for(j=0;j< 35;++j) for(k=0;k< 2;++k)
dp[i][j][k]=0;

Scanner cin = new Scanner(System.in);

t = cin.nextInt();
w = cin.nextInt();

for(i=1;i<=t;++i)
way[i]=cin.nextInt()-1;

for(i=1;i<=t;++i) for(j=0;j<=w;++j) for(k=0;k< 2;++k)
{
if(way[i]==k)
dp[i][j][k]=max(dp[i-1][j][k]+1,j>0?dp[i-1][j-1][1-k]+1:1);
else dp[i][j][k]=max(dp[i-1][j][k],j>0?dp[i-1][j-1][1-k]:0);
if(dp[i][j][k]>ans&&((k==1&&j< w)||(k==0&&j<=w))) ans=dp[i][j][k];
}

System.out.println(ans);
}

}

1. 有限自动机在ACM中是必须掌握的算法，实际上在面试当中几乎不可能让你单独的去实现这个算法，如果有题目要用到有限自动机来降低时间复杂度，那么这种面试题应该属于很难的级别了。