JZOJ 5397. 【NOIP2017提高A组模拟10.6】Biology

11 篇文章 0 订阅
9 篇文章 0 订阅

Description

Description

Input

Input

Output

Output

Sample Input

5 5
zzj
pri
prime
ime
owaski
2 3 1 3 5
2 2 2 3
1 actri
2 2 3 4
2 3 2 6 5

Sample Output

0
0
3
1

Data Constraint

Data Constraint

Hint

zzj,prime,owaski三种基因片段的最长共有有效片段为空
pri,prime两种基因片段的最长共有效片段为空
添加基因片段actri,编号为6
prime,ime两种基因片段的最长共有有效片段为ime
pri,actri,owaski三种基因片段的最长共有有效片段i

Solution

  • 这题是 Trie+Lca 的经典题。

  • 对于加入的每个字符串,倒序放入一个 Trie 中,记录其最终节点、深度、倍增ST表等信息。

  • 那么对于查询的那几个串,只需求出它们在 Trie 上的 Lca 即可,答案即为 Lca 深度。

  • 时间复杂度 O(MTlog Len)

Code

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=1e5+2,M=N*10;
int len,tot;
int s[M],w[N],p[N],g[M][26];
int f[M][20],dep[M],a[10];
inline int read()
{
    int X=0,w=1; char ch=0;
    while(ch<'0' || ch>'9') {if(ch=='-') w=-1;ch=getchar();}
    while(ch>='0' && ch<='9') X=(X<<3)+(X<<1)+ch-'0',ch=getchar();
    return X*w;
}
inline int write(int x)
{
    if(x>9) write(x/10);
    putchar(x%10+'0');
}
inline void insert(int x)
{
    char ch=getchar();
    while(ch<'a' || ch>'z') ch=getchar();
    while(ch>='a' && ch<='z') s[++len]=ch-'a',ch=getchar();
    w[x+1]=len+1;
}
inline void trie(int x)
{
    int num=0;
    for(int i=w[x+1]-1;i>=w[x];i--)
    {
        if(!g[num][s[i]])
        {
            g[num][s[i]]=++tot;
            dep[tot]=dep[num]+1;
            f[tot][0]=num;
            for(int j=1;j<20;j++) f[tot][j]=f[f[tot][j-1]][j-1];
        }
        num=g[num][s[i]];
    }
    p[x]=num;
}
inline int lca(int x,int y)
{
    if(dep[x]<dep[y]) swap(x,y);
    for(int i=log2(dep[x]);i>=0;i--)
        if(dep[f[x][i]]>=dep[y]) x=f[x][i];
    if(x==y) return x;
    for(int i=log2(dep[x]);i>=0;i--)
        if(f[x][i]!=f[y][i]) x=f[x][i],y=f[y][i];
    return f[x][0];
}
int main()
{
    int n=read(),m=read();
    for(int i=w[1]=1;i<=n;i++)
    {
        insert(i);
        trie(i);
    }
    while(m--)
    {
        int op=read();
        if(op==1)
        {
            insert(++n);
            trie(n);
        }else
        {
            int t=read();
            for(int i=0;i<t;i++) a[i]=read();
            sort(a,a+t);
            t=unique(a,a+t)-a;
            int ans=p[a[0]];
            for(int i=1;i<t;i++) ans=lca(ans,p[a[i]]);
            write(dep[ans]),putchar('\n');
        }
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值