實機體驗,再天天抽M8來自星星的你也會打廣告?正妹的東京自助旅行反服貿流血 法官要警交...
2012-05-02 06:51:38 人氣(429) | 回應(0) | 推薦(0) | 收藏(0) 上一篇 | 下一篇

[UVA][Math] 10223 - How many nodes ?

0
收藏
0
推薦

 How many nodes ?

The Problem

One of the most popular topic of Data Structures is Rooted Binary Tree. If you are given some nodes you can definitely able to make the maximum number of trees with them. But if you are given the maximum number of trees built upon a few nodes, Can you find out how many nodes built those trees?

The Input

The input file will contain one or more test cases.

Each test case consists of an integer n (n<=4,294,967,295). Here n is the maximum number of trees.

The Output

For each test case, print one line containing the actual number of nodes.

Sample Input

5
14
42

Sample Output

3
4
5

公式 f[n] = C(2*n,n)/(n+1)
原本的遞迴公式 f[n]=f[0]*f[n-1]+f[1]*f[n-2]+…+f[n-1]*f[0]
產生遞迴後 f[n]=(4n-2)/(n+1)*f[n-1]

#include <stdio.h>
#include <iostream>
#include <map>
using namespace std;

int main() {
    long long f = 1;
    map<long long, int> record;
    record[1] = 1;
    for(int i = 2; i <= 100; i++) {
        f = f*(4*i-2)/(i+1);
        record[f] = i;
    }
    while(scanf("%lld", &f) == 1) {
        printf("%d\n", record[f]);
    }
    return 0;
}

順便練習 JAVA 的大數與 map使用

import java.math.BigInteger;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        BigInteger[] f = new BigInteger[1001];
        Map<String, Integer> map = new HashMap<String, Integer>();
        f[1] = BigInteger.valueOf(1);
        map.put(f[1].toString(), 1);
        for(int i = 2; i <= 100; i++) {
            f[i] = f[i-1].multiply(BigInteger.valueOf(4*i-2)).divide(BigInteger.valueOf(i+1));
            map.put(f[i].toString(), i);
        }
        Scanner cin = new Scanner(System.in);
        while(cin.hasNext()) {
            long n = cin.nextLong();
            System.out.println(map.get("" + n));
        }
    }
}

 

10223How many nodes二元樹
台長:Morris
人氣(429) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][Map] 902 - Password Search
此分類上一篇:[UVA][Java][Math] 10303 - How Many Trees?

我要回應
是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入以下數字 (ex:123)

(有*為必填)
詳全文