[BZOJ]4477: [Jsoi2015]字符串树 可持久化trie

Description

萌萌买了一颗字符串树的种子,春天种下去以后夏天就能长出一棵很大的字
符串树。字符串树很奇特,树枝上都密密麻麻写满了字符串,看上去很复杂的样
子。
【问题描述】
字符串树本质上还是一棵树,即N个节点N-1条边的连通无向无环图,节点
从1到N编号。与普通的树不同的是,树上的每条边都对应了一个字符串。萌萌
和JYY在树下玩的时候,萌萌决定考一考JYY。每次萌萌都写出一个字符串S和
两个节点U,V,需要JYY立即回答U和V之间的最短路径(即,之间边数最少的
路径。由于给定的是一棵树,这样的路径是唯一的)上有多少个字符串以为前
缀。
JYY虽然精通编程,但对字符串处理却不在行。所以他请你帮他解决萌萌的难题。

题解:

无脑的题,和BZOJ2588的思路比较像,那题是可持久化线段树,这题是可持久化trie,以 root[x] 为根的字典树就存的是 x <script type="math/tex" id="MathJax-Element-37">x</script>到根节点的信息,然后乱搞一下就好了。过了样例就AC了,很爽。

代码:

#include<bits/stdc++.h>
using namespace std;
#define LL long long
const int Maxn=100010;
struct Edge{int y,next;char str[12];}e[Maxn*2];
int last[Maxn],len=0;
int n,q;
int son[Maxn*10][27],root[Maxn],c[Maxn*10],tot=0;
void build(int last,int p,int o)
{
    root[p]=++tot;c[tot]=1;char s[12];strcpy(s,e[o].str);
    int len=strlen(s),now=tot;last=root[last];
    for(int i=0;i<len;i++)
    {
        int x=s[i]-'a';
        for(int j=0;j<26;j++)son[now][j]=son[last][j];
        son[now][x]=++tot;c[tot]=1+c[son[last][x]];
        now=son[now][x];last=son[last][x];
    }
}
char ss[12];
void ins(int x,int y){int t=++len;e[t].y=y;strcpy(e[t].str,ss);e[t].next=last[x];last[x]=t;}
int fa[Maxn][19],dep[Maxn];
void dfs(int x,int f)
{
    fa[x][0]=f;dep[x]=dep[f]+1;
    for(int i=1;i<=17;i++)if((1<<i)<=dep[x])fa[x][i]=fa[fa[x][i-1]][i-1];
    for(int i=last[x];i;i=e[i].next)
    {
        int y=e[i].y;
        if(y!=fa[x][0])
        {
            build(x,y,i);
            dfs(y,x);
        }
    }
}
int LCA(int x,int y)
{
    if(dep[x]<dep[y])swap(x,y);
    for(int i=17;i>=0;i--)if((1<<i)<=dep[x]-dep[y])x=fa[x][i];
    if(x==y)return x;
    for(int i=17;i>=0;i--)
    if((1<<i)<=dep[x]&&fa[x][i]!=fa[y][i])x=fa[x][i],y=fa[y][i];
    return fa[x][0];
}
int query(int rt)
{
    int now=rt,len=strlen(ss);
    for(int i=0;i<len;i++)
    {
        int x=ss[i]-'a';
        if(!son[now][x])return 0;
        now=son[now][x];
    }return c[now];
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<n;i++)
    {
        int x,y;
        scanf("%d%d%s",&x,&y,ss);
        ins(x,y);ins(y,x);
    }dep[0]=root[1]=0;dfs(1,0);
    scanf("%d",&q);
    while(q--)
    {
        int x,y;
        scanf("%d%d%s",&x,&y,ss);int lca=LCA(x,y);
        printf("%d\n",query(root[x])+query(root[y])-2*query(root[lca]));
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值