1. 程式人生 > >[SHOI 2017] 組合數問題

[SHOI 2017] 組合數問題

problem sta 時間 min com etc printf ble https

[題目鏈接]

https://www.lydsy.com/JudgeOnline/problem.php?id=4870

[算法]

回顧組合數的定義 :

C(N , M)表示將N個小球放入M個盒子裏的方案數

我們發現題目要求的其實就是將nk個小球放入模k意義下於r個盒子中的方案數

不妨設Fi , j表示放了i個小球 , j個盒子(模k意義下)的方案數

有 : Fi , j = Fi - 1 , j - 1 + Fi - 1 , j

矩陣乘法即可

時間復雜度 : O(K ^ 3logNlogK)

[代碼]

#include<bits/stdc++.h>
using namespace std;
const int N = 1e9 + 10;
const int K = 55;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

int n , p , k , r;
int mat[K][K];

template <typename T> inline void chkmax(T &x , T y) { x = max(x , y); }
template 
<typename T> inline void chkmin(T &x , T y) { x = min(x , y); } template <typename T> inline void read(T &x) { T f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == -) f = -f; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1
) + c - 0; x *= f; } inline void multipy(int a[K][K] , int b[K][K]) { static int res[K][K]; for (int i = 0; i < k; ++i) { for (int j = 0; j < k; ++j) { res[i][j] = 0; } } for (int x = 0; x < k; ++x) { for (int i = 0; i < k; ++i) { for (int j = 0; j < k; ++j) { res[i][j] = (res[i][j] + 1ll * a[i][x] * b[x][j] % p) % p; } } } for (int i = 0; i < k; ++i) { for (int j = 0; j < k; ++j) { a[i][j] = res[i][j]; } } } inline void exp_mod(int mat[K][K] , ll n) { static int b[K][K]; for (int i = 0; i < k; ++i) { for (int j = 0; j < k; ++j) { b[i][j] = (i == j); } } while (n > 0) { if (n & 1) multipy(b , mat); multipy(mat , mat); n >>= 1; } for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { mat[i][j] = b[i][j]; } } } int main() { read(n); read(p); read(k); read(r); for (int i = 0; i < k; ++i) { ++mat[i][i]; ++mat[i][((i - 1) % k + k) % k]; } exp_mod(mat , (ll)n * k); printf("%d\n" , mat[r][0]); return 0; }

[SHOI 2017] 組合數問題