2012-05-02 06:51:38Morris

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

 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));
        }
    }
}