题目链接:https://vjudge.net/problem/CodeForces-1200E
题意:
给出n个字符串,要求将它们首位合并
思路:
用hash,O(n)遍历输入的字符串,判断一下之前合并好的字符串的后缀s1,与当前字符串s2的前缀的hash值是否相同。
记录那个相同的位置pos,从pos后链接新串,复杂的为O(n)。
但是上面的做法一直卡在65点处,后来改用双哈希就过了。
这里一直取模时间会变长,其实unsigned long long 也行。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 2e6+10;
typedef long long ll;
const ll base1 = 131;
const ll base2 = 137;
const ll mod1 = 1e9+7;
const ll mod2 = 1e9+9;
char s1[N],s2[N];
ll h[2][N],p[2][N];
ll H1(int l,int r)
{
ll tp = h[0][r] - h[0][l-1]*p[0][r-l+1]%mod1;
return (tp%mod1 + mod1)%mod1;
}
ll H2(int l,int r)
{
ll tp = h[1][r] - h[1][l-1]*p[1][r-l+1]%mod2;
return (tp%mod2 + mod2)%mod2;
}
int main(void)
{
h[0][0] = h[1][0] = 0;
p[0][0] = p[1][0] = 1;
for(int i=1;i<N;i++)
{
p[0][i] = p[0][i-1]*base1%mod1;
p[0][i] = (p[0][i]%mod1 + mod1)%mod1;
p[1][i] = p[1][i-1]*base2%mod2;
p[1][i] = (p[1][i]%mod2 + mod2)%mod2;
}
int n,tot = 0;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s",s1);
int len = strlen(s1),pos = -1;
ll t1 = 0,t2 = 0;
for(int j=0;j<len;j++)
{
t1 = (t1*base1%mod1 + (ll)s1[j])%mod1;
t1 = (t1%mod1+mod1)%mod1;
t2 = (t2*base2%mod2 + (ll)s1[j])%mod2;
t2 = (t2%mod2+mod2)%mod2;
if(j+1<=tot && H1(tot-j,tot) == t1 && H2(tot-j,tot) == t2) pos = j;
}
for(int j=pos+1;j<len;j++)
{
tot++;
s2[tot] = s1[j];
h[0][tot] = (h[0][tot-1]*base1%mod1 + (ll)s2[tot])%mod1;
h[0][tot] = (h[0][tot]%mod1 + mod1)%mod1;
h[1][tot] = (h[1][tot-1]*base2%mod2 + (ll)s2[tot])%mod2;
h[1][tot] = (h[1][tot]%mod2 + mod2)%mod2;
}
}
//printf("tot = %d\n",tot);
for(int i=1;i<=tot;i++) printf("%c",s2[i]);
return 0;
}