Problem Description
On Saint Valentine's Day, Alex imagined to present a special pendant to his girl friend made by K kind of pearls. The pendant is actually a string of pearls, and its length is defined as the number of pearls in it. As is known to all, Alex is very rich, and he has N pearls of each kind. Pendant can be told apart according to permutation of its pearls. Now he wants to know how many kind of pendant can he made, with length between 1 and N. Of course, to show his wealth, every kind of pendant must be made of K pearls.
Output the answer taken modulo 1234567891.
Output the answer taken modulo 1234567891.
Input
The input consists of multiple test cases. The first line contains an integer T indicating the number of test cases. Each case is on one line, consisting of two integers N and K, separated by one space.
Technical Specification
1 ≤ T ≤ 10
1 ≤ N ≤ 1,000,000,000
1 ≤ K ≤ 30
Technical Specification
1 ≤ T ≤ 10
1 ≤ N ≤ 1,000,000,000
1 ≤ K ≤ 30
Output
Output the answer on one line for each test case.
Sample Input
2 2 1 3 2
Sample Output
2 8
Source
解题思路:很容易想到,本题应该利用动态规划来进行求解,dp[i][j]表示i颗珠子共有j种的不同方案数,则dp[i][j] = dp[i-1][j-1]*(k-j+1) + dp[i-1][j]*j,由于本题中要求求解dp[1][k]+...+dp[n][k]且n很大,因此我们可以通过构造转移矩阵,通过矩阵快速幂进行优化,构造转移矩阵的出发点便是根据转移方程,利用由于我们需要求解前缀和,因此我们在构造转移矩阵的时候增加一维用来存储前缀和,这样我们在求解完矩阵幂之后,最终便会得出相应的前缀和,矩阵构造的十分巧妙,学习了。
#include <cmath>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
typedef long long ll;
const ll mod = 1234567891;
struct Matrix {
int n;
ll mat[35][35];
void zero() {
memset(mat, 0, sizeof(mat));
}
void unit() {
memset(mat, 0, sizeof(mat));
for(int i = 0; i < 35; ++i) {
mat[i][i] = 1;
}
}
friend Matrix operator * (const Matrix &a, const Matrix &b) {
Matrix c;
c.n = a.n;
c.zero();
for(int i = 1; i <= c.n; ++i) {
for(int j = 1; j <= c.n; ++j) {
for(int k = 1; k <= c.n; ++k) {
c.mat[i][j] = (c.mat[i][j] + a.mat[i][k] * b.mat[k][j]) % mod;
}
}
}
return c;
}
friend Matrix operator ^ (Matrix a, int x) {
Matrix c;
c.n = a.n;
c.unit();
while(x) {
if(x&1) c = c * a;
a = a * a;
x >>= 1;
}
return c;
}
};
int main() {
int T, N, K;
Matrix a;
ll x[40];
scanf("%d", &T);
while(T--) {
scanf("%d %d", &N, &K);
memset(x, 0, sizeof(x));
x[1] = K;
a.n = K + 1;
a.zero();
for(int i = 1; i <= K; ++i) {
a.mat[i][i] = i;
a.mat[i-1][i] = K - i + 1;
}
a.mat[K][K+1] = 1;
a.mat[K+1][K+1] = 1;
a = a^(N-1);
ll ans = 0;
for(int i = 1; i <= K + 1; ++i) {
ans = (ans + x[i] * a.mat[i][K] + x[i] * a.mat[i][K+1]) % mod;
}
printf("%I64d\n", ans);
}
return 0;
}