题意:给 k个字符串,长度为n
是否存在一个串 换两个字符可以包含k个字符串
正解是 n^2*k 这里是字符串hash n^2*klogk 超时,只是没有好好做过字符串hash,这里记录一下
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5010;
ll p[N],h[N],w[N];
char s[N>>1][N];
ll seed = 20123;
int k,n;
ll rnd(){ return seed = seed * 87378051+29;}
unordered_map<ll,int> f,mp;
ll solve(int i,int x,int y)
{
ll ret=h[i];
ret=ret-p[x]*w[s[i][x]];
ret=ret-p[y]*w[s[i][y]];
ret=ret+p[x]*w[s[i][y]];
ret=ret+p[y]*w[s[i][x]];
return ret;
}
//unordered_map
void work()
{
for(int i=1;i<=k;i++)
{
mp.clear();
for(int x=1;x<=n-1;x++)
{
for(int y=x+1;y<=n;y++)
{
ll now = solve(i,x,y);
if(mp.count(now)==0)
{
mp[now]=1;
++f[now];
}
}
}
}
for(int x=1;x<=n-1;x++)
{
for(int y=x+1;y<=n;y++)
{
ll now = solve(1,x,y);
if(f[now]==k)
{
swap(s[1][x],s[1][y]);
printf("%s\n",s[1]+1 );
exit(0);
}
}
}
puts("-1");
exit(0);
}
int main()
{
scanf("%d%d",&k,&n);
for(int i=1;i<=k;i++)
scanf("%s",s[i]+1);
for(int i=1;i<=n;i++) p[i]=rnd()*rnd();
for(int i=0;i<=300;i++) w[i]=rnd()*rnd();
for(int i=1;i<=k;i++)
{
ll now=0;
for(int j=1;j<=n;j++) now=now+w[s[i][j]]*p[j];
h[i]=now;
}
work();
}