24h購物| | PChome| 登入
2013-07-05 15:36:18| 人氣485| 回應0 | 上一篇 | 下一篇

[UVA][遞迴] 12627 - Erratic Expansion

推薦 0 收藏 0 轉貼0 訂閱站台


A

Erratic Expansion

Input: Standard Input

Output: Standard Output

 

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 0th, 1st, 2nd and 3rd hour are depicted in the following diagram.

 

 

As you can see, a red balloon in the cell (i, j) (that is ith row and jth 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 Kth 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 ≤ AB ≤ 2K.

 

Output

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

 

Sample Input                               Output for Sample Input

3

0 1 1

3 1 8

3 3 7

 

Case 1: 1

Case 2: 27

Case 3: 14


Problemsetter: Sohel Hafiz, Special Thanks: Md. Mahbubul Hasan



題目解法:

還好這題 column, row 怎麼擺放並不重要, 剛好對稱不影響。
這題就遞迴解決它, 不過要預算一個 (2^k)*(2^k) 如果全選的個數是多少, 得到了 3^k 個紅色氣球。



#include <stdio.h>
long long I[50];
long long dfs(int k, int i, int j) {
    if(k == 0)  return 1;
    long long ret = 0;
    int w = 1<<(k-1);
    if(i == 1 && j == w*2)
        return I[k];
    if(w >= j)
        return dfs(k-1, i, j)*2;
    if(i > w)
        return dfs(k-1, i-w, j-w);
    return dfs(k-1, i, w)*2 + dfs(k-1, 1, j-w);
}
int main() {
    I[0] = 1;
    for(int i = 1; i < 50; i++)
        I[i] = I[i-1]*3;
    int testcase, cases = 0;
    scanf("%d", &testcase);
    while(testcase--) {
        int k, i, j;
        scanf("%d %d %d", &k, &i, &j);
        printf("Case %d: %lld\n", ++cases, dfs(k, i, j));
    }
    return 0;
}

台長: Morris
人氣(485) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][bfs] 10422 - Knights in FEN
此分類上一篇:[UVA][模擬] 12608 - Garbage Collection

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文