UVa 12627 Erratic Expansion 奇怪的气球膨胀 (分治_递归) 白书P245

16 篇文章 0 订阅
7 篇文章 0 订阅

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行的红色球的数量就可以得到第A行到第B行的红色气球的数量。

然后再观察第三小时和第二小时的图,发现第二小时的图和第三张图分成四块后的其中三块相同,而不相同的一块全是蓝色,不需要计算。

 假设函数f(k,i)表示第k小时,前i行的所有红球个数,则问题的答案就是f(k,B)-f(k,A-1)。f(k,i)的求解需要根据i与2的(k-1)次方的大小分类讨论,递归求解。


#include<cstring>
#include<cstdio>
#include<iostream>
using namespace std;
int T,k,a,b;
long long c[35];
long long f(int k, int i)
{
    if(!i) return 0;
    if(!k) return 1;
    if(i<1<<(k-1))
        return 2*f(k-1,i);
    else
        return f(k-1,i-(1<<(k-1)))+2*c[k-1];    1<<(k-1)=2的k-1次方
}
int main()
{
    c[0]=1;
    for(int i=1;i<30; i++)
        c[i]=3*c[i-1];
    cin>>T;
    for(int s=1;s<=T; s++)
    {
        cin>>k>>a>>b;
        long long total=f(k,b)-f(k,a-1);
        printf("Case %d: %lld\n",s,total);
    }
    return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值