其他分享
首页 > 其他分享> > 奶牛生牛问题

奶牛生牛问题

作者:互联网

链接

假设农场中成熟的母牛每年只会生 1 头小母牛,并且永远不会死。第一年农场中有一只成熟的母牛,从第二年开始,母牛开始生小母牛。每只小母牛 3 年之后成熟又可以生小母牛。给定整数 n,求出 n 年后牛的数量。


f(1) = 1
f(2) = 2
f(3) = 3
f(n) = f(n - 1) + f(n - 3) (n > 3)
f(n) = (f(3), f(2), f(1)) (x ^ (n - 3))
所以有,
(f(4), f(3), f(2)) = (f(3), f(2), f(1)) (x ^ 1)
(f(5), f(4), f(3)) = (f(3), f(2), f(1)) (x ^ 2)
(f(6), f(5), f(4)) = (f(3), f(2), f(1)) (x ^ 3)
得矩阵
{1, 1, 0},
{0, 0, 1}.
{1, 0, 0}

import java.util.Scanner;

public class Main {

    private static final int MOD = 1000000007;

    private static long[][] multiply(long[][] a, long[][] b) {
        long[][] result = new long[a.length][b[0].length];

        for (int i = 0; i < a.length; ++i) {
            for (int j = 0; j < b[0].length; ++j) {
                for (int k = 0; k < a[0].length; ++k) {
                    result[i][j] = (result[i][j] + a[i][k] * b[k][j]) % MOD;
                }
            }
        }
        return result;
    }

    private static long solve(long n) {
        if (n <= 3) {
            return n;
        }

        n -= 3;

        long[][] result = {
                {3, 2, 1}
        };
        long[][] base = {
                {1, 1, 0},
                {0, 0, 1},
                {1, 0, 0}
        };

        while (n > 0) {
            if ((n & 1) != 0) {
                result = multiply(result, base);
            }
            n >>= 1;
            base = multiply(base, base);
        }
        return result[0][0];
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            long n = in.nextLong();
            System.out.println(solve(n));
        }

    }
}

标签:生牛,int,long,问题,length,static,result,奶牛,母牛
来源: https://www.cnblogs.com/tianyiya/p/15403167.html