【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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值