[蓝桥杯][2013年第四届真题]公式求值

题目链接

思路:母函数 lucas 大数

题解:

http://tieba.baidu.com/p/2832505865

代码:

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

public class Main {
    public static final BigInteger MOD = new BigInteger("999101");
    public static final long mod = 999101;
    public static final int N = 1005, M = 999101;
    public static long fac[] = new long[M];
    public static long invf[] = new long [M];
    public static long pp[] = new long[M];
    public static long dp[][] = new long[N][N];
    public static long q_pow(long n, long k) {
        long res = 1;
        while(k > 0) {
            if(k%2 == 1) res = (res * n) % mod;
            k >>= 1;
            n = (n*n) % mod;
        }
        return res;
    }
    
    public static void init(BigInteger x) {
        fac[0] = 1;
        pp[0] = 1;
        for (int i = 1; i < M; ++i) fac[i] = (fac[i-1]*i) % mod;
        invf[M-1] = q_pow(fac[M-1], mod-2);
        for (int i = M-2; i >= 0; --i) invf[i] = invf[i+1]*(i+1) % mod;
        for (int i = 1; i < M; ++i) pp[i] = (pp[i-1]*2) % mod;
        long n = Long.valueOf(x.remainder(MOD).toString());
        dp[1][1] = n;
        for (int i = 2; i < N; ++i) {
            dp[i][1] = n;
            for (int j = 2; j <= i; ++j) {
                dp[i][j] = (dp[i-1][j-1]*(n-j+1) + dp[i-1][j]*j) % mod;
                dp[i][j] = (dp[i][j] + mod) % mod;
            }
        }
    }
    public static long C(BigInteger n, BigInteger m) {
        if(m.compareTo(n) > 0) return 0;
        int x = Integer.valueOf(n.toString()), y = Integer.valueOf(m.toString());
        //System.out.println(((fac[x]*invf[y])% mod * invf[x-y]) % mod);
        return ((fac[x]*invf[y])% mod * invf[x-y]) % mod;
    }
    public static long lucas(BigInteger n, BigInteger m) {
        if(m.compareTo(BigInteger.ZERO) == 0) return 1;
        return (lucas(n.divide(MOD), m.divide(MOD))*C(n.remainder(MOD), m.remainder(MOD))) % mod;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);    
        BigInteger n = in.nextBigInteger();
        BigInteger m = in.nextBigInteger();
        int k = in.nextInt();
        init(n);
        long ans = lucas(n, m), res = 0;
        for (int i = 1; i <= k; i++) {
            int p = Integer.valueOf((n.subtract(BigInteger.valueOf(i)).remainder(BigInteger.valueOf(mod-1))).toString());
            res = (res + dp[k][i]*pp[p]) % mod;
        }
        ans = (ans * res) % mod;
        System.out.println(ans);
    }
}

以上代码不能ac,因为数据出错,加上特判才能ac

猜你喜欢

转载自www.cnblogs.com/widsom/p/10362763.html