KMP 60分求助
查看原帖
KMP 60分求助
521283
wangif424楼主2023/12/23 15:01
#include <bits/stdc++.h>
#define R(x) x = read()
#define ENDL push('\n');
#define SPACE push(' ');
#define int long long
using namespace std;
char pbuf[1<<20], *pp=pbuf;
inline void push(const char &c) {
	if(pp - pbuf == 1<<20)fwrite(pbuf, 1, 1<<20, stdout),pp = pbuf;
	*pp++ = c;
}
class io {public:~io() {fwrite(pbuf, 1, pp - pbuf, stdout);}} _;
inline void write(int x) {
	if (x<0)x=-x,push('-');
	int sta[35],top=0;
	do {
		sta[top++]=x%10,x/=10;
	} while (x);
	while(top)push(sta[--top]^'0');
}
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;
}
int n;
string s[310];
int l[310];
int border[1000100];
void kmp(string s,int l){
	memset(border,0,sizeof(border));
	for(int i=2,j=0;i<=l;i++){
		while(j&&s[i]!=s[j+1])j=border[j];
		if(s[i]==s[j+1])j++;
		border[i]=j;
	}
}
int ans[310];
int find(string s1,string s2,int l1,int l2){
	int res=0;
	for(int i=1,j=0;i<=l2;i++){
		while(j&&s2[i]!=s1[j+1])j=border[j];
		if(s1[j+1]==s2[i])j++;
		if(j==l1)res++;
	}
	return res;
}
signed main(){
	R(n);
	for(int i=1;i<=n;i++){
		cin >> s[i];
		l[i]=s[i].size();
		s[i]=' '+s[i];
	}
	for(int i=1;i<=n;i++){
		kmp(s[i],l[i]);
		for(int j=1;j<=n;j++){
			ans[j]+=find(s[j],s[i],l[j],l[i]);
		}
	}
	for(int i=1;i<=n;i++){
		write(ans[i]);push('\n');
	}
    return 0;
}
2023/12/23 15:01
加载中...