https://ac.nowcoder.com/acm/contest/5667/A
A-All with Pairs
题意:给定n个字符串,求所有字符串前缀与后缀相等的个数与前后缀的长度的平方的和。如样例,匹配长度为1,2,3的分别有4,4,1个,所以答案为4 *1 ^2 +4 *2 ^2 +1 *3 ^2=29
思路:对于字符串的后缀用hash进行存储,对于前缀,同样用hash但是和后缀hash有所不同,一个是从前往后,一个是从后往前,但是还要对这个数组进行去重,因为同一个可能进行了多次匹配,但我们想的是只能进行一次,而且那一次还是前缀最长的,所以要用kmp中的next数组进行快速查找最长的那个字符串,进行去重。
ac自动机也行,而且效率还更快
代码如下:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <unordered_map>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i < n; i++)
#define per(i, a, n) for(int i = n-1; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define INF 1ll<<60
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
const int maxn = 1e6+10;
const ll mod = 998244353;
inline int read(){
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;
}
unordered_map<ull, int> m;
void get_hash(string s){
int p = 1;
ull sum = 0;
for(int i = s.length()-1; i >= 0; i--){
sum += (s[i]-'a'+1)*p;
p *= 233;
m[sum]++;
}
}
string str[maxn];
int Next[maxn], ans[maxn];
void get_Next(string s) {
int len = s.size();
int k = -1;
Next[0] = k;
for(int i = 1; i < len; i++){
while(k>-1 && s[k+1]!=s[i]) k=Next[k];
if(s[k+1]==s[i]) k++;
Next[i] = k;
}
}
int main(){
IOS;
int n;
cin>>n;
rep(i,0,n){
cin>>str[i];
get_hash(str[i]);
}
ll cnt = 0;
rep(i,0,n){
ull sum = 0;
rep(j,0,str[i].length()){
sum = sum*233+(str[i][j]-'a'+1);
ans[j] = m[sum];
}
get_Next(str[i]);
rep(j,0,str[i].length()){
if(Next[j]>=0) ans[Next[j]] -= ans[j];
}
rep(j,0,str[i].length()){
cnt += ans[j]*(j+1)%mod*(j+1)%mod;
cnt %= mod;
}
}
printf("%lld\n", cnt);
return 0;
}
1万+

被折叠的 条评论
为什么被折叠?



