Bare string matching. the maximum length of the substring is 10,000, and that of the parent string is 1,000,000.
The number of times the substring appears in the parent string.
If the length of the substring is small, you can directly use the RK match. When the hash value is the same, you can directly compare whether the string is the same.
However, the substring of this question is too long, and it will time out to compare strings. If the substring is not compared, it is theoretically incorrect, although
The error probability is very small, and the probability is related to the selection of modulus and whether the operation overflows.
At the beginning, we used int and found that we had been wa. It is estimated that the operation would exceed int, And the modulo operation did not work. Module Selection
Select to improve the accuracy. Although Rabin-Karp string matching is easy to write and understand, it is applicable
It is not very wide. For example, if the substring is too long, it will be difficult to handle it. It is not very good to discard the substring.
However, if the substring is not long, the Rabin-Karp string matches well.
In comparison, kmp should be much better for this question.
The Code is as follows:
# Include <stdio. h>
# Include <string. h>
# Include <algorithm>
Using namespace std;
Typedef long INT;
Char szStrM [1000010];
Char szStrS [10010];
Const int mod = 16381*4733 + 1;
Int main ()
{
Int nT;
Scanf ("% d", & nT );
While (nT --)
{
Scanf ("% s", szStrS, szStrM );
INT nMatch = szStrS [0]-'A ';
INT nPowN = 1;
Int nSizeS = 1;
Char * pszStr = szStrS + 1;
While (* pszStr)
{
NMatch = (26 * nMatch + * pszStr-'A') % MOD;
NPowN = (nPowN * 26) % MOD;
++ NSizeS;
++ PszStr;
}
// PrINTf ("match: % d \ n", nMatch );
Int nSizeM = strlen (szStrM );
INT nKey = 0;
For (int I = 0; I <nSizeS; ++ I)
{
NKey = (26 * nKey + szStrM [I]-'A') % MOD;
}
// PrINTf ("key: % d \ n", nKey );
Int nAns = 0;
For (int I = 0; I <= nSizeM-nSizeS; ++ I)
{
// PrINTf ("key: % d \ n", nKey );
If (nKey = nMatch)
// & Memcpy (szStrS, szStrM + I, nSizeS) = 0)
{
++ NAns;
}
NKey = (26 * (nKey-nPowN * (szStrM [I]-'A') % MOD
+ SzStrM [I + nSizeS]-'A') % MOD;
NKey = (nKey + MOD) % MOD;
}
Printf ("% d \ n", nAns );
}
Return 0;
}