[hackerank]Red John is Back

Red John has committed another murder. This time, he doesn't leave a red smiley behind. Instead he leaves a puzzle for Patrick Jane to solve. He also texts Teresa Lisbon that if Patrick is successful, he will turn himself in. The puzzle begins as follows.

There is a wall of size 4xn in the victim's house. The victim has an infinite supply of bricks of size 4x1 and 1x4 in her house. There is a hidden safe which can only be opened by a particular configuration of bricks. First we must calculate the total number of ways in which the bricks can be arranged so that the entire wall is covered. The following diagram shows how bricks might be arranged to cover walls where :

image

There is one more step to the puzzle. Call the number of possible arrangements . Patrick must calculate the number of prime numbers  in the inclusive range .

As an example, assume . From the diagram above, we determine that there is only one configuration that will cover the wall properly.  is not a prime number, so .

A more complex example is . The bricks can be oriented in  total configurations that cover the wall. The two primes  and  are less than or equal to , so .

image

Input Format

The first line contains the integer , the number of test cases. 
Each of the next  lines contains an integer , the length of the  wall.

Constraints

  •  
  •  

Output Format

Print the integer  on a separate line for each test case.

Sample Input

2
1
7

Sample Output

0
3

Explanation

For , the brick can be laid in 1 format only: vertically.

The number of primes  is .

For , one of the ways in which we can lay the bricks is

Red John

There are  ways of arranging the bricks for  and there are  primes .

解析:

类似汉诺塔和兔子繁殖问题,是一个含有重复操作的限制问题。有点像不断对数列求前n项和的过程。

从墙的最左侧开始,放一块木板,只能由两种选择,放4*1或者4*4,一次递归找到解。

We can convert the first part of the problem into a recurrence relation i.e. F(N) = F(N-1) + F(N-4) with the base case : F(0) = F(1) = F(2) = F(3) = 1. 
Here, F(N) represents the number of ways of tiling the 4xN rectangle with 4x1 and 1x4 tiles. The explanation goes as :
If we place a 4x1 tile, then we just need to solve for F(N-1).
If we place a 1x4 tile, then we can't place a 4x1 tile under it. Basically, we will have to place a set of four 1x4 tiles together, hence we solve forF(N-4).

Finally, we take the sum and get the total number of configuration i.e. M.

Once we get M, we need to to calculate the number of primes less than or equal to M. We use Sieve of Eratosthenes(http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to do the same.

The time complexity of the first part of the problem is O(n) since we can calculate M using Dynamic Programming. The time complexity of the second part is O(n log log n). Hence, the overall time complexity for the problem becomes O(n log log n).

猜你喜欢

转载自blog.csdn.net/liangjiubujiu/article/details/81216913