欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(UVA - 12627)Erratic Expansion

程序员文章站 2022-03-11 23:47:56
...

(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.

(UVA - 12627)Erratic Expansion

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个红气球和一个蓝气球,而一个蓝气球会变成4个蓝气球,就像图中分别是0,1,2,3小时后的气球分布情况。问:经过k小时后,第A~B行一共有多少个红气球?

思路:我们易得k小时后的红气球总数为3k个,所以我们可以预处理出k小时后红色气球总数,即sum[i]=3sum[i1] (sum数组储存i小时后红色气球的总数)。我们设f(k,i)表示k小时后前i行红气球总数。那么如果i<=2k1 ,则f(k,i)=2f(k1,i);如果i>2k1,则f(k,i)=2sum[i1]+f(k1,i2k1)
ps:因为这里i可以为230,所以无法用数组下标表示,而用函数递归。同时这里数据可以很大所以开long long

#include<cstdio>
using namespace std;

typedef long long LL;
LL sum[35];

LL f(int k,int i)
{
    if(i==0) return 0;
    if(k==0) return 1;
    if(i<=1<<(k-1)) return 2*f(k-1,i);
    else return 2*sum[k-1]+f(k-1,i-(1<<(k-1)));
}

int main()
{
    sum[0]=1;
    for(int i=1;i<=30;i++) sum[i]=3*sum[i-1];
    int T,k,a,b,kase=1;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d%d",&k,&a,&b);
        printf("Case %d: %lld\n",kase++,f(k,b)-f(k,a-1));
    }   
    return 0;
} 
相关标签: uva