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.
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
Output
Output the answer on one line for each test case.
Sample Input
22 13 2
Sample output
28
Q: How many necklaces with N length composed of K pearls?
Idea: Use DP [I] [J] to represent the number of I and j types of pearls. It is easy to introduce DP [I] [J] = DP [I]-1 [J] * j + dp [I-1] [J-1] * (k-J + 1 ), because of the large amount of data, we need to use matrix optimization. The key is to construct a matrix. Originally, we used a K-dimensional matrix to construct a relational matrix. But now we need:
DP [1] [k] + dp [1] [k] +... DP [N] [K], so we add one dimension to record and.
First, we use the rolling array Dimensionality Reduction idea to construct a matrix: F [J] = f [J-1] * j + F [J] * (k-J + 1 ), because we need and FK, the first dimension is determined.
| 1 0 ...... 0 1 | G |
| 0 1 0 ...... 0 | F1 |
| 0 K-1 2 ...... 0 | F2 |
| ...... | *.
| 0... 0 k-(J-1) j 0... 0 |.
| ...... |.
| 0 ...... 0 1 k | FK |
#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <cmath>using namespace std;typedef unsigned long long ll;const int maxn = 35;const int mod = 1234567891;int cnt;struct Matrix {ll v[maxn][maxn];Matrix() {}Matrix(int x) {init();for (int i = 0; i < maxn; i++) v[i][i] = x;}void init() {memset(v, 0, sizeof(v));}Matrix operator *(Matrix const &b) const {Matrix c;c.init();for (int i = 0; i < cnt; i++)for (int j = 0; j < cnt; j++)for (int k = 0; k < cnt; k++)c.v[i][j] = (c.v[i][j] + (ll)(v[i][k]*b.v[k][j])) % mod;return c;}Matrix operator ^(int b) {Matrix a = *this, res(1);while (b) {if (b & 1)res = res * a;a = a * a;b >>= 1;}return res;}} a, b, tmp;int main() {int t, n, k;scanf("%d", &t);while (t--) {scanf("%d%d", &n, &k);a.init();a.v[0][0] = a.v[0][k] = 1;for (int j = 1; j <= k; j++) {if (j > 1)a.v[j][j-1] = k-(j-1);a.v[j][j] = j;}cnt = k + 1;ll num[maxn];memset(num, 0, sizeof(num));num[1] = k;tmp = a^n;ll ans[maxn];memset(ans, 0, sizeof(ans));for (int i = 0; i < cnt; i++)if (num[i])for (int j = 0; j < cnt; j++)if (tmp.v[j][i])ans[j] = (ans[j]+ (ll)(tmp.v[j][i]*num[i])) % mod;cout << ans[0] << endl;}return 0;}