美文网首页程序员半栈工程师
POJ 1953 World Cup Noise(斐波那契数)

POJ 1953 World Cup Noise(斐波那契数)

作者: TinyDolphin | 来源:发表于2017-12-21 11:08 被阅读0次

题意:求一个长度为 n 的由0和1组成的序列中,满足没有两个 1 相邻的序列的数目。如 n = 3 时,000、001、010、100、101 一共 5 个序列满足条件。

分析:
n = 0 时,0个;n = 1 时,2个;n = 2 时,3个;
n = 3 时,5个;n = 4 时,8个...... n = n 时,f(f-1) + f(n-2) 个。

分析得:这是斐波那契数列的应用。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int scenario;
        int[] f = new int[50];
        FibonacciPlus(f);
        while (in.hasNext()) {
            scenario = in.nextInt();
            for (int i = 1; i <= scenario; i++) {
                out.println("Scenario #" + i + ":");
                out.println(f[in.nextInt()]);
                if (i != scenario)
                    out.println();
            }
        }
        out.flush();
    }

    //*// 方法一:预处理,斐波那契数组打表。
    public static void FibonacciPlus(int[] arr) {
        arr[0] = 0;
        arr[1] = 2;
        arr[2] = 3;
        for (int i = 3; i < 48; i++) {
            arr[i] = arr[i - 1] + arr[i - 2];
        }
    }
    //*/

    /*// 方法二:计算
    public static BigInteger Fibonacci(int n) {
        if (n == 0) {
            return BigInteger.valueOf(0);
        }
        if (n == 1) {
            return BigInteger.valueOf(2);
        }
        if (n == 2) {
            return BigInteger.valueOf(3);
        }
        BigInteger one = BigInteger.valueOf(3);
        BigInteger two = BigInteger.valueOf(2);
        BigInteger sum = BigInteger.valueOf(0);
        for (int i = 3; i <= n; i++) {
            sum = one.add(two);
            two = one;
            one = sum;
        }
        return sum;
    }//*/
}

相关文章

网友评论

    本文标题:POJ 1953 World Cup Noise(斐波那契数)

    本文链接:https://www.haomeiwen.com/subject/pbwowxtx.html