【NOI2016模擬3.1】hypocritical

Description

這裏寫圖片描述

Input

這裏寫圖片描述

Output

第i行一個整數表示第i個詢問的答案

Sample Input

6 3 3
aaabbb
2 3 2 5 7 10
1 2
1 3
2 4
2 5
3 6
1 3
2 2
3 1

Sample Output

362
161
22

Data Constraint

n<=100000,s<=5,t<=16,保證字符集爲前s個小寫字母

Solution

把原樹看成一個trie,對trie建廣義後綴自動機
可以發現,並不需要知道每個狀態權值是什麼
設一個dp,f[i][j]表示第i個狀態,構成的串數量爲j時的方案數,因爲在一個狀態處的字符串,從min到max長度都是完全相同的
在加入時,對於加入的點dp一下,同時在fail鏈上dp一下,提前預處理好答案,詢問時直接輸出

Code

#include<cstdio>
#include<cstring>
#include<algorithm>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
#define N 101000
#define mo 998244353
#define ll long long
using namespace std;
int n,m,str,s[N],v[N],last[N],next[N*2],to[N*2],tot=0,d[N],a[N];
ll f[N*10][17],ans[17][N];
struct SAM{
    int len,size,fail;
    int to[6];
}t[N*10];
void putin(int x,int y)
{
    next[++tot]=last[x];last[x]=tot;to[tot]=y;
}
void dp(int x,ll val)
{
    fd(j,16,1)
    {
        (f[x][j]+=f[x][j-1]*val)%=mo;
        f[x][j]=(f[x][j]+mo)%mo;
    }
}
void add(int x,int cm,int last,int val)
{
    int p=last,np=++tot;f[tot][0]=1;
    t[np].len=t[p].len+1;t[np].size=1;a[cm]=np;
    for(;p&&t[p].to[x]==0;p=t[p].fail) t[p].to[x]=np;
    if(p==0) t[np].fail=1;
    else
    {
        int q=t[p].to[x];
        if(t[p].len+1==t[q].len) t[np].fail=q;
        else
        {
            int nq=++tot;t[nq]=t[q];
            fo(j,0,16) f[nq][j]=f[q][j];
            t[nq].len=t[p].len+1;t[q].fail=t[np].fail=nq;
            for(;p&&t[p].to[x]==q;p=t[p].fail) t[p].to[x]=nq;
        }
    }
    //--------------
    for(p=np;p;p=t[p].fail) dp(p,val);
}
void pre()
{
    int he=0,ta=1,mx=0;d[1]=1;tot=1;
    add(s[1],1,1,v[1]);
    while(he<ta)
    {
        int x=d[++he];
        for(int i=last[x];i;i=next[i])
        {
            int y=to[i];if(a[y]) continue;
            add(s[y],y,a[x],v[y]);d[++ta]=y;
        }
    }
    fo(i,1,tot)
    {
        fo(j,0,16)
        {
            ans[j][t[i].len+1]=(ans[j][t[i].len+1]-f[i][j]+mo)%mo;
            (ans[j][t[t[i].fail].len+1]+=f[i][j])%=mo;
        }
        mx=max(mx,t[i].len+1);
    }
    fo(i,1,mx) fo(j,0,16) (ans[j][i]+=ans[j][i-1])%=mo;
}
int main()
{
    scanf("%d%d%d\n",&n,&m,&str);
    fo(i,1,n)
    {
        char c=getchar();
        s[i]=c-97;
    }
    fo(i,1,n) scanf("%d",&v[i]);
    fo(i,1,n-1)
    {
        int x,y;scanf("%d%d",&x,&y);
        putin(x,y);putin(y,x);
    }
    pre();
    while(m--)
    {
        int k,t;scanf("%d%d",&k,&t);
        printf("%lld\n",(ans[t][k]+mo)%mo);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章