题目
Source
http://acm.split.hdu.edu.cn/showproblem.php?pid=5863
Description
cjj has k kinds of characters the number of which are infinite. He wants to build two strings with the characters. The lengths of the strings are both equal to n.
cjj also define a cjj_val for two string.
a[i,j] means the substring a[i],a[i+1],...,a[j-1],a[j] of string a.
cjj_val = max({ j-i+1 }) where a[i,j]=b[i,j] for every 0<=i<=j<n.
Know cjj wants to know that if he wants to build two strings with k different characters whose cjj_val is equal to m, how many ways can he do that.
Input
The first line of the input data is an integer T(1<=T<=100), means the number of test case.
Next T lines, each line contains three integers n(1<=n<=1000000000), m(1<=m<=10), k(1<=k<=26).
Output
For each test case, print one line, the number of the ways to build the string. The answer will be very large, you just need to output ans mod 1000000007.
Sample Input
2
3 2 3
3 3 3
Sample Output
108
27
分析
题目大概说用k个不同的字母,有多少种方法构造出两个长度n最长公共子串长度为m的字符串。
n的规模达到了10亿,而且又是方案数,自然就想到构造矩阵用快速幂解决。
考虑用DP解决可以这么表示状态:
- dp[i][j]表示两个字符串前i个字符都构造好了 并且 它们后面的j个字符相同的方案数
状态的转移就是,末尾j个相同的可以转移到0个相同的也能转移到j+1个相同的(前提是j<m)。
而对于这个状态可以构造矩阵去转移,即一个(m+1)*(m+1)的矩阵,矩阵i行j列表示从末尾i个相同转移到末尾j个相同的方案数,而该矩阵的n次幂的第0行的和就是长度n的字符串末尾各个情况的方案数。
不过样表示状态最后求出来不是要求的,因为LCS小于m的也会包含于其中。那么减去小于m的方案数不就OK了!
- 即 至少包含m个相同公共子串的方案数 - 至少包含m-1个相同公共子串的方案数 = 恰好包含m个相同公共子串的方案数
于是,一样再构造一个m*m的矩阵求n次幂,就OK了。
代码
#include<cstdio> #include<cstring> using namespace std; struct Mat{ int m[11][11]; int len; }; Mat operator*(const Mat &m1,const Mat &m2){ Mat m={0}; m.len=m1.len; for(int i=0; i<=m.len; ++i){ for(int j=0; j<=m.len; ++j){ for(int k=0; k<=m.len; ++k){ m.m[i][j]+=(long long)m1.m[i][k]*m2.m[k][j]%1000000007; m.m[i][j]%=1000000007; } } } return m; } int main(){ int t,n,m,k; scanf("%d",&t); while(t--){ scanf("%d%d%d",&n,&m,&k); Mat e={0},me={0}; e.len=m; me.len=m; for(int i=0; i<=m; ++i) e.m[i][i]=1; for(int i=0; i<=m; ++i){ if(i<m) me.m[i][i+1]=k; me.m[i][0]=k*k-k; } int exp=n; while(exp){ if(exp&1) e=e*me; me=me*me; exp>>=1; } int ans=0; for(int i=0; i<=m; ++i){ ans+=e.m[0][i]; ans%=1000000007; } memset(e.m,0,sizeof(e.m)); memset(me.m,0,sizeof(me.m)); e.len=m-1; me.len=m-1; for(int i=0; i<m; ++i) e.m[i][i]=1; for(int i=0; i<m; ++i){ if(i<m-1) me.m[i][i+1]=k; me.m[i][0]=k*k-k; } exp=n; while(exp){ if(exp&1) e=e*me; me=me*me; exp>>=1; } for(int i=0; i<m; ++i){ ans-=e.m[0][i]; ans%=1000000007; } if(ans<0) ans+=1000000007; printf("%d\n",ans); } return 0; }
HDU5863 cjj's string game(DP + 矩阵快速幂)