HDU5863 cjj's string game(DP + 矩阵快速幂)
題目
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; }?
轉載于:https://www.cnblogs.com/WABoss/p/5785052.html
總結
以上是生活随笔為你收集整理的HDU5863 cjj's string game(DP + 矩阵快速幂)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构-线性表之用队列实现栈用栈实现队
- 下一篇: PyQt5学习笔记05----Qt De