LightOJ 1095 Arrange the Numbers (容斥原理)

题意 : 1到n的排列中前m个中恰好有k个数每个数都和他的下标相同。问这样有几个 ? 答案取模。

思路 : 前m个(1~m)选择k个是组合数C(m, k)种, 然后令x = m - k, y = n - m; 则 x中会有[0, x]个位置是下标和值一样, 这里可以利用容斥原理做,即减去i为奇数的加上i 为偶数的。

ans = C(m, k) * ∑ (C(x, i) * (x + y - i) ! * (-1)^i ) % mod;


#include 
#include 

typedef long long lld;
const int mod = 1000000007;
const int maxn = 1005;

lld C[maxn][maxn], F[maxn];

int ii(int x){return x & 1 ? -1 : 1;}

void init(){
    F[0] = 1; C[0][0] = 1;
    for (int i = 1; i <= 1000; i++){
        F[i] = F[i-1] * i % mod;
    }
    for (int i = 1; i <= 1000; i++){
        C[i][0] = 1;
        for (int j = 1; j <= i; j++){
            C[i][j] = (C[i-1][j] + C[i-1][j-1]) % mod;
        }
    }
}

lld solve(int n, int m, int k){
    int x = m - k, y = n - m;
    lld sum = 0;
    for (int i = 0; i <= x; i++){
        sum += C[x][i] * F[x+y-i] * ii(i) % mod;
        sum = (sum + mod) % mod;
    }
    return sum * C[m][k] % mod;
}

int n, m, k;

int main(){
    int T; init();
    scanf("%d", &T);
    for (int cas = 1; cas <= T; cas++){
        scanf("%d%d%d", &n, &m, &k);
        printf("Case %d: %lld\n", cas, solve(n, m, k));
    }
    return 0;
}

你可能感兴趣的:(『ACM,Jan's,LightOJ』,『ACM,数论』)