1009: [HNOI2008]GT考試
Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 2269 Solved: 1384
[Submit][Status][Discuss]
Description
阿申準備報名參加GT考試,准考證號爲N位數X1X2....Xn(0<=Xi<=9),他不希望准考證號上出現不吉利的數字。他的不吉利數學A1A2...Am(0<=Ai<=9)有M位,不出現是指X1X2...Xn中沒有恰好一段等於A1A2...Am. A1和X1可以爲0
Input
第一行輸入N,M,K.接下來一行輸入M位的數。 100%數據N<=10^9,M<=20,K<=1000 40%數據N<=1000 10%數據N<=6
Output
阿申想知道不出現不吉利數字的號碼有多少種,輸出模K取餘的結果.
Sample Input
111
Sample Output
F[i][j]表示當前爲第i位匹配了j位且前i位未出現匹配的考號的方案數。因爲F[i]只與F[i - 1]有關所以考慮用滾動數組。又發現該DP方程可以寫成一次齊次遞推式,所以可以用矩陣快速冪加速。
DP方程由KMP的Next數組得到。
代碼如下:
/**************************************************************
Problem: 1009
User: duyixian
Language: C++
Result: Accepted
Time:60 ms
Memory:1292 kb
****************************************************************/
/*
* @Author: duyixian
* @Date: 2015-09-10 11:16:06
* @Last Modified by: duyixian
* @Last Modified time: 2015-09-15 17:13:20
*/
#include "cstdio"
#include "cstdlib"
#include "iostream"
#include "algorithm"
#include "cstring"
#include "queue"
using namespace std;
#define MAX_SIZE 50
#define INF 0x3F3F3F3F
#define Eps
#define Mod K
inline int Get_Int()
{
int Num = 0, Flag = 1;
char ch;
do
{
ch = getchar();
if(ch == '-')
Flag *= -1;
}
while(ch < '0' || ch > '9');
do
{
Num = Num * 10 + ch - '0';
ch = getchar();
}
while(ch >= '0' && ch <= '9');
return Num * Flag;
}
int Next[MAX_SIZE], X[MAX_SIZE];
int N, K, M, Ans;
struct Matrix
{
int A[MAX_SIZE][MAX_SIZE];
int n, m;
inline Matrix operator * (Matrix const &a) const
{
Matrix temp;
memset(&temp, 0, sizeof(Matrix));
temp.n = n;
temp.m = a.m;
for(int i = 0; i <= temp.n; ++i)
for(int j = 0; j <= temp.m; ++j)
for(int k = 0; k <= m; ++k)
temp.A[i][j] = (temp.A[i][j] + A[i][k] * a.A[k][j]) % Mod;
return temp;
}
inline void operator *= (Matrix const &a)
{
*this = (*this) * a;
}
inline Matrix operator ^ (const int k)
{
Matrix ans, K1;
memset(&ans, 0, sizeof(Matrix));
K1 = *this;
ans.n = ans.m = n;
for(int i = 0; i <= n; ++i)
ans.A[i][i] = 1;
int temp = k;
while(temp)
{
if(temp & 1)
ans *= K1;
temp >>= 1;
K1 *= K1;
}
return ans;
}
}a, DP;
int main()
{
cin >> N >> M >> K;
char ch = getchar();
while(ch < '0' || ch > '9')
ch = getchar();
for(int i = 1; i <= M; ++i)
X[i] = ch - '0', ch = getchar();
X[M + 1] = 10;
int temp = 0;
for(int i = 2; i <= M; ++i)
{
while(temp && X[i] != X[temp + 1])
temp = Next[temp];
if(X[i] == X[temp + 1])
Next[i] = ++temp;
}
a.n = a.m = M - 1;
for(int i = 0; i < M; ++i)
{
for(int j = 0; j < 10; ++j)
{
int temp = i;
while(temp && X[temp + 1] != j)
temp = Next[temp];
if(X[temp + 1] == j)
++temp;
++a.A[i][temp];
}
}
DP.A[0][0] = 1;
DP.n = 0;
DP.m = M - 1;
DP *= (a ^ N);
for(int i = 0; i < M; ++i)
Ans = (Ans + DP.A[0][i]) % Mod;
cout << Ans << endl;
return 0;
}