1 条题解

  • 0
    @ 2025-9-10 9:04:44

    C++ :

    #include<iostream>
    #include<vector>
    #include<algorithm>
    #include<cstring>
    #include<cstdio>
    #include<cmath>
    #include<cstdlib>
    #include<ctime>
    #include<queue>
    #include<set>
    using namespace std;
    typedef long long LL;
    const int N=3e6;
    int gi() {
    	int w=0;bool q=1;char c=getchar();
    	while ((c<'0'||c>'9') && c!='-') c=getchar();
    	if (c=='-') q=0,c=getchar();
    	while (c>='0'&&c <= '9') w=w*10+c-'0',c=getchar();
    	return q? w:-w;
    }
    int son[N][10],fa[N],len[N],tot=1;
    int c[N];
    int head[N],nnext[N],to[N];
    inline int add(int p,int c) {
    	if (son[p][c]) {
    		int q=son[p][c];
    		if (len[q]==len[p]+1) return q;
    		int nq=++tot;
    		len[nq]=len[p]+1;
    		fa[nq]=fa[q],fa[q]=nq;
    		for (int i=0;i<10;i++) son[nq][i]=son[q][i];
    		for (;son[p][c]==q;p=fa[p])
    			son[p][c]=nq;
    		return nq;
    	} else {
    		int np=++tot,nq,q;
    		len[np]=len[p]+1;
    		for (;p&&!son[p][c];p=fa[p])
    			son[p][c]=np;
    		if (!p) fa[np]=1;
    		else if (len[q=son[p][c]]==len[p]+1) fa[np]=q;
    		else {
    			len[nq=++tot]=len[p]+1;
    			fa[nq]=fa[q],fa[q]=fa[np]=nq;
    			for (int i=0;i<10;i++) son[nq][i]=son[q][i];
    			for (;son[p][c]==q;p=fa[p])
    				son[p][c]=nq;
    		}
    		return np;
    	}
    }
    inline void dfs(int k,int fa,int p) {
    	p=add(p,c[k]);
    	for (int i=head[k];i;i=nnext[i])
    		if (to[i]!=fa)
    			dfs(to[i],k,p);
    }
    int main()
    {
    #ifndef ONLINE_JUDGE
    	freopen("substring.in","r",stdin);
    	freopen("substring.out","w",stdout);
    #endif
    	int a,b,n=gi(),i,tot=0;gi();
    	for (i=1;i<=n;i++) c[i]=gi();
    	for (i=1;i<n;i++) {
    		a=gi(),b=gi();
    		to[++tot]=b,nnext[tot]=head[a],head[a]=tot;
    		to[++tot]=a,nnext[tot]=head[b],head[b]=tot;
    	}
    	for (i=1;i<=n;i++) if (!nnext[head[i]]) dfs(i,0,1);
    	LL ans=0;
    	for (i=1;i<=::tot;i++) ans+=len[i]-len[fa[i]];
    	cout<<ans<<endl;
    	return 0;
    }
    
    • 1

    信息

    ID
    3721
    时间
    1000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者