NHOI2015D 字符串
贪心
字符串查找
#include <cstdio>
#include <cstring>
using namespace std;
const int base = 52, MOD = 4999661, MAXN = 1e6 + 1;
char s[MAXN], t[MAXN];
int i, j, ans, lens, lent, hashs, hasht, tmp;
int main() {
freopen("string.in", "r", stdin);
freopen("string.out", "w", stdout);
scanf("%s", s);
scanf("%s", t);
lens = strlen(s);
lent = strlen(t);
for (i = 0; i < lens; i++)
s[i] -= (s[i] >= 'A' && s[i] <= 'Z') ? 'A' : ('a' - 26);
for (i = 0; i < lent; i++)
t[i] -= (t[i] >= 'A' && t[i] <= 'Z') ? 'A' : ('a' - 26);
hashs = s[0];
hasht = t[0];
tmp = 1;
for (i = 1; i < lens; i++) {
((hashs *= base) += s[i]) %= MOD;
((hasht *= base) += t[i]) %= MOD;
(tmp *= base) %= MOD;
}
for (j = lens; j <= lent; )
if (hashs == hasht) {
ans++;
if (j + lens <= lent) {
hasht = 0;
for (i = j; i < j + lens; i++)
((hasht *= base) += t[i]) %= MOD;
j += lens;
}
else
break;
} else {
hasht = ((hasht - t[j - lens] * tmp % MOD + MOD) % MOD * base + t[j]) % MOD;
j++;
}
printf("%d\n", ans);
return 0;
}