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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章