题意:给定一个序列,求出出现次数大于m,长度最长的子串的最大下标
思路:DJB哈希,这是一个十分好用的哈希法,很久之前曾在另一个题里和队友学过,终于又碰到了一题。就像n进制一样,对字符串每个字符位置进行处理,对一个字符串求出哈希值。用unsigned longlong 还会自动取模,非常好!一般来说,这个n取一个很大的素数,建议用那个人的生日,没冲突过,谁用谁知道((#^.^#))。作为真正的粉丝,我可以轻松背出这段数字!
代码:
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
#include<map>
#include<vector>
#include<set>
#include<queue>
using namespace std;
typedef unsigned long long ull;
const ull happy = 19260817;
const int maxv = 40040;
int n, len, ans, pos;
map<ull, int>mp;
ull mul[maxv], hs[maxv];
char s[maxv];
void init()
{
mul[0] = 1;
for (int i = 1; i <= 40000; i++)
{
mul[i] = mul[i - 1] * happy;
}
}
void djbhash()
{
hs[0] = 0;
for (int i = 1; i <= len; i++)
{
hs[i] = hs[i - 1] * happy + s[i] - 'a';
}
}
int check(int x)
{
mp.clear();
int f = 0;
for (int i = 1; i <= len - x + 1; i++)
{
ull num = hs[i + x - 1] - hs[i - 1] * mul[x];
mp[num]++;
if (mp[num] >= n)
{
if (x >= ans)
{
ans = x;
pos = i;
}
f = 1;
}
}
return f;
}
int main()
{
init();
while (scanf("%d", &n), n)
{
scanf("%s", s + 1);
len = strlen(s + 1);
djbhash();
int l = 1, r = len;
ans = pos = -1;
while (l <= r)
{
int mid = (l + r) / 2;
if (check(mid))
{
l = mid + 1;
}
else
{
r = mid - 1;
}
}
if (ans == -1)
{
printf("none\n");
}
else
{
printf("%d %d\n", ans, pos - 1);
}
}
return 0;
}