bzoj4477 [Jsoi2015]字符串树

Description


萌萌买了一颗字符串树的种子,春天种下去以后夏天就能长出一棵很大的字
符串树。字符串树很奇特,树枝上都密密麻麻写满了字符串,看上去很复杂的样
子。

问题描述

字符串树本质上还是一棵树,即N个节点N-1条边的连通无向无环图,节点
从1到N编号。与普通的树不同的是,树上的每条边都对应了一个字符串。萌萌
和JYY在树下玩的时候,萌萌决定考一考JYY。每次萌萌都写出一个字符串S和
两个节点U,V,需要JYY立即回答U和V之间的最短路径(即,之间边数最少的
路径。由于给定的是一棵树,这样的路径是唯一的)上有多少个字符串以为前
缀。
JYY虽然精通编程,但对字符串处理却不在行。所以他请你帮他解决萌萌的难题。

输入中所有字符串只包含a-z的小写字母。
1<=N,Q<=100,000,且输入所有字符串长度不超过10。

Solution


很容易想到求一次lca,令ans[x]为x到根的答案,那么答案为ans[x]+ans[y]-ans[lca]*2
这样dfs一次,每个点以父亲为上一个版本建trie,查询的时候直接找就可以了

空间不太够,那么就可持久化一下

Code


#include <stdio.h>
#include <string.h>
#include <algorithm>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
#define drp(i,st,ed) for (int i=st;i>=ed;--i)

const int N=100505;
const int L=15;

int root[N],count[N*L];
int rec[N*L][26],tot;
int fa[N][21],dep[N];
int ls[N],edCnt;
char str[N*2][L],opt[L];

struct edge {int y,next;} e[N*2];

void addEdge(int x,int y) {
    e[++edCnt]=(edge) {y,ls[x]}; ls[x]=edCnt;
    scanf("%s",str[edCnt]);
    e[++edCnt]=(edge) {x,ls[y]}; ls[y]=edCnt;
    memcpy(str[edCnt],str[edCnt-1],sizeof(str[edCnt]));
}

void insert(int pre,int &y,char *str) {
    int len=strlen(str);
    int now=y=++tot;
    rep(i,0,len-1) {
        memcpy(rec[now],rec[pre],sizeof(rec[now]));
        count[now]=count[pre]+1;
        rec[now][str[i]-'a']=++tot;
        pre=rec[pre][str[i]-'a'];
        now=rec[now][str[i]-'a'];
    }
    count[now]=count[pre]+1;
}

int query(int now,char *str) {
    int len=strlen(str);
    rep(i,0,len-1) {
        now=rec[now][str[i]-'a'];
    }
    return count[now];
}

int get_lca(int x,int y) {
    if (dep[x]<dep[y]) std:: swap(x,y);
    drp(i,20,0) if (dep[fa[x][i]]>=dep[y]) x=fa[x][i];
    if (x==y) return x;
    drp(i,20,0) if (fa[x][i]!=fa[y][i]) {
        x=fa[x][i];
        y=fa[y][i];
    }
    return fa[x][0];
}

void dfs(int now) {
    rep(i,1,20) fa[now][i]=fa[fa[now][i-1]][i-1];
    for (int i=ls[now];i;i=e[i].next) {
        if (e[i].y==fa[now][0]) continue;
        insert(root[now],root[e[i].y],str[i]);
        dep[e[i].y]=dep[now]+1;
        fa[e[i].y][0]=now;
        dfs(e[i].y);
    }
}

int main(void) {
    root[1]=tot=1;
    int n; scanf("%d",&n);
    rep(i,2,n) {
        int x,y; scanf("%d%d",&x,&y);
        addEdge(x,y);
    }
    dep[1]=1; dfs(1);
    int T; scanf("%d",&T);
    while (T--) {
        int x,y; scanf("%d%d",&x,&y);
        scanf("%s",opt);
        int lca=get_lca(x,y);
        int ans=query(root[x],opt)+query(root[y],opt);
        ans-=query(root[lca],opt)*2;
        printf("%d\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值