typedefunsignedlonglong ULL; constint N = 2e6 + 7;//哈希表长 const ULL MOD = 2000003;//用于除留取余的模数,一般为最靠近但小于表长的质数 const ULL seed = 1e9 + 7;//哈希函数的种子值
structHash { structnode { ULL v; int nxt; node(ULL _v = 0ULL, int _nxt = 0): v(_v), nxt(_nxt) {} } code[N]; int head[MOD], tot;
voidinit(){ for (registerint i = 0; i < N; ++i) head[i] = -1; tot = 0; } voidadd(ULL v){ int pos = v % MOD; code[tot] = node(v, head[pos]); head[pos] = tot++; } intFind(ULL v){ int p = v % MOD; for (registerint i = head[p]; ~i; i = code[i].nxt) { if (code[i].v == v) return1; } return0; } } hashtable;
structHash { structnode { ULL v; int nxt; node(ULL _v = 0ULL, int _nxt = 0): v(_v), nxt(_nxt) {} } code[N]; int head[MOD], tot;
voidinit(){ for (registerint i = 0; i < N; ++i) head[i] = -1; tot = 0; } voidadd(ULL v){ int pos = v % MOD; code[tot] = node(v, head[pos]); head[pos] = tot++; } intFind(ULL v){ int p = v % MOD; for (registerint i = head[p]; ~i; i = code[i].nxt) { if (code[i].v == v) return1; } return0; } } hashtable;
intmain(void) { registerint i, ans, ls, len; register ULL bas = 1, af = 0, be = 0; while (~scanf("%s", s + 1)) { hashtable.init(); len = strlen(s + 1); for (i = 1; i <= len; ++i) { af = (af * seed + * (s + i)); bas = bas * seed; } hashtable.add(af); for (i = 1; i <= len; ++i) { af = (af * seed + s[i]); be = (be * seed + s[i]); hashtable.add(af - be * bas); } caseT { scanf("%s", s + 1); ls = strlen(s + 1); af = 0, be = 0; ans = 0; for (i = 1; i <= len && i <= ls; ++i) { af = af * seed + s[i]; } ans += hashtable.Find(af); for (i = len + 1; i <= ls; ++i) { af = af * seed + s[i]; be = be * seed + s[i - len]; ans += hashtable.Find(af - be * bas); } printf("%d\n", ans); } } return0; }