Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

Re:JAVA用BigInteger超时啊~~~~~~~~~怎么办,递归算法,难道真要写高精?

Posted by zzw890827 at 2010-05-20 21:22:29 on Problem 2506
In Reply To:JAVA用BigInteger超时啊~~~~~~~~~怎么办,递归算法,难道真要写高精? Posted by:slovx2 at 2010-04-14 19:08:42
f(n) = f(n-1)+2*f(n-2) 使用记忆化搜索+BigInteger 水过

import java.io.*;
import java.util.*;
import java.math.*;

public class Main {
    //遞推公式:f(n) = f(n-1)+2*f(n-2)
    //使用記憶化搜索
    
    public static BigInteger[] data = new BigInteger[251];
    public static BigInteger f(int n)
    {
        if(n==0) return BigInteger.valueOf(1);
        if(n==1) return BigInteger.valueOf(1);
        if(n==2) return BigInteger.valueOf(3);
        if(data[n].compareTo(BigInteger.valueOf(-1))!=0)
            return data[n];

        data[n] =  f(n-1).add(f(n-2).multiply(BigInteger.valueOf(2)));
        return data[n];
    }

    public static void main(String[] args) {
       int n;
       Scanner in = new Scanner(System.in);
       while(in.hasNextInt()){
           for(int i=0;i<251;i++){
               data[i] = BigInteger.valueOf(-1);
           }
           n = in.nextInt();
           System.out.println(f(n));
       }
    }

}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator