51nod 1228 (伯努利数 + 组合数学)

题目:

求这个 i=1nik
题目给你 n , k。

分析:

伯努利数于幂数和的关系:
这里写图片描述
伯努利数:
这里写图片描述
这里写图片描述
这么多性质可以直接写了

Code:

import java.util.Scanner;

public class Main {
    public static Scanner cin = new Scanner(System.in);
    public static int maxn = 2000 + 131;
    public static long MOD = (long)(1e9 + 7);
    public static long[] Inv = new long[maxn];
    public static long[] B = new long[maxn];
    public static long[] Mjie = new long[maxn];
    public static long[] InvM = new long[maxn];

    public static void INITC() {
        //逆元
        Inv[1] = 1;
        for(int i = 2; i < maxn; ++i) {
            Inv[i] = (MOD - MOD/i) * Inv[(int) (MOD % i)] % MOD;
        }
        // M!
        Mjie[0] = Mjie[1] = 1;
        for(int i = 1; i < maxn; ++i) {
            Mjie[i] = Mjie[i-1] * i % MOD;
        }
        //阶乘逆元
        InvM[1] = InvM[0] = 1;
        for(int i = 2; i < maxn; ++i) {
            InvM[i] = InvM[i-1] * Inv[i] % MOD;
        }
    }
    //组合数
    public static long CC(int m, int n) {
        if(n == 0) return 1L;
        return Mjie[m] * InvM[n] % MOD * InvM[m-n] % MOD;
    }
    //伯努利数
    public static void INIT() {
        B[0] = 1;
        for(int i = 1; i < maxn-1; ++i) {
            B[i] = 0;
            for(int j = 0; j < i; ++j) {
                B[i] += (CC(i+1,j) * B[j]) % MOD;
                B[i] %= MOD;
            }
            B[i] = B[i] * Inv[i+1] * -1 % MOD;
            B[i] = (B[i] + MOD) % MOD;
        }
    }

    public static long GetAns(long N, long K) {
        long Pow = 1;
        long ans = 0;
        for(int i = 1; i <= K+1; ++i) {
            Pow = Pow * (N+1) % MOD;
            ans = ans + (CC((int)(K+1),i) * B[(int)(K+1-i)]) % MOD * Pow % MOD;
            ans %= MOD;
        }
        ans = ans * Inv[(int)(K+1)] % MOD;
        return ans;
    }

    public static void main(String[] arg) {
        INITC();
        INIT();
        int T;
        long N, K;
        T = cin.nextInt();
        for(int t = 0; t < T; ++t) {
            N = cin.nextLong();
            K = cin.nextLong();
            System.out.println(GetAns(N % MOD,K));
        }
    }
}

你可能感兴趣的:(组合数学)