P4081 [USACO17DEC]Standing Out from the Herd

题目

P4081 [USACO17DEC]Standing Out from the Herd

做法

一眼合并\(endpos\)裸题

其实是不需要合并的,因为保证只在一个串出现,建个\(parent\)树统计一下就好了

My complete code

#include<cstdio>
#include<cstring>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
typedef int LL;
const LL maxn=200009;
LL n,m,nod=1,lst;
LL len[maxn],fail[maxn],son[maxn][26],visit[maxn],ans[maxn],mark[maxn];
string s;
inline void Insert(LL c,LL id){
	LL np=++nod,p=lst; lst=np; mark[np]=id;
	len[np]=len[p]+1;
	while(p&&!son[p][c]){
		son[p][c]=np;
		p=fail[p];
	}
	if(!p)
	    fail[np]=1;
	else{
		LL q=son[p][c];
		if(len[q]==len[p]+1)
		    fail[np]=q;
		else{
			LL nq=++nod; len[nq]=len[p]+1; mark[nq]=mark[q];
			memcpy(son[nq],son[q],sizeof(son[q]));
			fail[nq]=fail[q];
			fail[np]=fail[q]=nq;
			while(p&&son[p][c]==q){
				son[p][c]=nq;
				p=fail[p];
			}
		}
	}
}
struct node{
	LL to,next;
}dis[maxn]; 
LL num,head[maxn];
inline void Add(LL u,LL v){
	dis[++num]=(node){v,head[u]},head[u]=num;
}
void Dfs(LL u){
	for(LL i=head[u];i;i=dis[i].next)
	    Dfs(dis[i].to);
	for(LL i=head[u];i;i=dis[i].next){
		LL v(dis[i].to);
		if(mark[v]==-1||mark[u]!=mark[v]){
		    mark[u]=-1;
		    break;
		}
	}
}
int main(){
	scanf("%d%d",&n);
	for(LL i=1;i<=n;++i){
		cin>>s;
		lst=1;
		for(LL j=0,Len=s.length();j<Len;++j)
		    Insert(s[j]-'a',i);
	}
	for(LL i=1;i<=nod;++i)
		Add(fail[i],i);
	Dfs(1);
	for(LL i=1;i<=nod;++i)
	    if(mark[i]!=-1)
	        ans[mark[i]]+=len[i]-len[fail[i]];
	for(LL i=1;i<=n;++i)
	    printf("%d\n",ans[i]);
	return 0;
}
posted @ 2019-01-25 10:58  y2823774827y  阅读(158)  评论(0编辑  收藏  举报