UVa OJ 12627 - Erratic Expansion

UVa OJ 12627 - Erratic Expansion

Problem

这个问题要带图才能方便理解题意,这里为了节省时间,大家自己去网站看题目就好。我真是太懒了 :p

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 ≤ 2K.

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

Solution

这道题目递归求解即可。

用solve(k,i)表示i行及其以上的红球数量,然后根据i大于2K-1的一半与否,求出k-1时对应的状态,直到递推边界。

这里用了一个节省了一点时间的办法,就是用idx数组将需要预先知道的3的倍数储存了起来,方便之后的搜索。(这是我AC之后在网上看到的方法)

#include <iostream>
using namespace std;

long long k, a, b, tot;
long long idx[31] = {1};

long long solve(long long k, long long i){
    if (!i) return 0;
    if (!k) return 1;
    if (i > (1LL << k-1))
        return (solve(k-1, i-(1LL << k-1)) + 2 * idx[k-1]);
    return 2 * solve(k-1, i);
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);

    int cas, n = 0;
    cin >> cas;
    for (int i = 1; i < 30; ++i)
        idx[i] = 3 * idx[i-1];
    while (++n <= cas){
        cin >> k >> a >> b;
        tot = solve(k, b) - solve(k, a-1);
        cout << "Case " << n  << ": "<< tot << '\n';
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值