UVA - 12627 : Erratic Expansion

Piotr found a magical box in heaven. Its magic power is that if you place any red balloon inside it then, after one hour, it will multiply to form 3 red and 1 blue colored balloons. Then in the next hour, each of the red balloons will multiply in the same fashion, but the blue one will multiply to form 4 blue balloons. This trend will continue indefinitely.

The arrangements of the balloons after the 0-th, 1-st, 2-nd and 3-rd hour are depicted in the following diagram.

As you can see, a red balloon in the cell (i, j) (that is i-th row and j-th column) will multiply to produce 3 red balloons in the cells (i ∗ 2 − 1, j ∗ 2 − 1), (i ∗ 2 − 1, j ∗ 2), (i ∗ 2, j ∗ 2 − 1) and a blue balloon in the cell (i ∗ 2, j ∗ 2). Whereas, a blue balloon in the cell (i, j) will multiply to produce 4 blue balloons in the cells (i ∗ 2 − 1, j ∗ 2 − 1), (i ∗ 2 − 1, j ∗ 2), (i ∗ 2, j ∗ 2 − 1) and (i ∗ 2, j ∗ 2). The grid size doubles (in both the direction) after every hour in order to accommodate the extra balloons. In this problem, Piotr is only interested in the count of the red balloons; more specifically, he would like to know the total number of red balloons in all the rows from A to B after K-th hour.

Input

The first line of input is an integer T (T < 1000) that indicates the number of test cases. Each case contains 3 integers K, A and B. The meanings of these variables are mentioned above. K will be in the range [0, 30] and 1 ≤ A ≤ B ≤ 2 K.

Output

For each case, output the case number followed by the total number of red balloons in rows [A, B] after K-th hour.

Sample Input

3

0 1 1

3 1 8

3 3 7

Sample Output

Case 1: 1

Case 2: 27

Case   3: 14 

 

 

题意:一开始有一个红气球,每小时,一个红气球会变成3个红气球和1个蓝气球,而一个蓝气球会变成4个蓝气球。

问在k小时后,第A行到第B行有几个红色的气球。可以用前B行的气球数减去前A-1行的气球数。

由图可知,有三个部分是一样,还有一部分都是篮球不用计算。所以可以将前n行分成两种,一种是小于2^k-1,递推式为2*f(k-1,n);

另一种是不小于2^k-1,递推式为2*3^k-1+f(k-1,n-2^k-1)

 

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 long long a[35];
 6 
 7 long long q(int k,int i)
 8 {
 9     if(!i)
10         return  0;
11     if(!k)
12         return 1;
13     int x=1<<k-1;
14     if(i<x)
15         return 2*q(k-1,i);
16         else
17             return 2*a[k-1]+q(k-1,i-x);
18             
19 }
20 
21 int main()
22 {
23     a[0]=1;
24     for(int i=1;i<31;i++)
25         a[i]=3*a[i-1];
26     int n,s=1;
27     cin>>n;
28     while(n--)
29     {
30         int k,i,i1;
31         cin>>k>>i>>i1;
32         cout<<"Case "<<s++<<": "<<q(k,i1)-q(k,i-1)<<endl;
33         
34     }    
35     
36     return 0;
37 }

 

posted @ 2017-07-27 16:02  西北会法语  阅读(173)  评论(0编辑  收藏  举报