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.
InputThe 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
OutputOutput the answer on one line for each test case.Sample Input
2
2 1
3 2
Sample Output
2
8
题意:给定N,K。求不超过N的链子的所有染色情况,使得起使用了K种颜色。
思路:
法1:容斥,用K种颜色,则其方案=1^K+2^K+...N^K,符号为正。 用K-1种颜色,方案=1^(K-1)+2^(K-2)...N^(K-1),符号为负...。用1种颜色...然后累加即可,但是我不会。
法2:不难得到其DP方程,dp[i][j]=dp[i-1][j-1]*(K-j+1)+dp[i-1][j]*j;然后用矩阵优化DP。在第一维加个1用来累加前缀和。
#include<bits/stdc++.h>
#define ll long long
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn=;
const int Mod=;
int L;
struct mat
{
int M[maxn][maxn];
mat() { memset(M,,sizeof(M)); }
mat friend operator *(mat a,mat b)
{
mat res;
for(int k=;k<=L;k++)
for(int i=;i<=L;i++)
for(int j=;j<=L;j++)
res.M[i][j]=(res.M[i][j]+(ll)a.M[i][k]*b.M[k][j]%Mod)%Mod;
return res;
}
mat friend operator ^(mat a,ll x)
{
mat res; rep(i,,L) res.M[i][i]=;
while(x){
if(x&1LL) res=res*a; a=a*a; x/=;
} return res;
}
}; int main()
{
int T,N,K;
scanf("%d",&T);
while(T--){
scanf("%d%d",&N,&K); L=K;
mat base,a;
a.M[][]=K; //单独考虑,因为base的第0行是累加dp的,不能再用了。
base.M[][]=; base.M[][K]=;
rep(i,,K){
if(i!=)//这里单独考虑了。
base.M[i][i-]=K-i+;
base.M[i][i]=i;
}
a=(base^(N))*a;
printf("%d\n",a.M[][]);
}
return ;
}