计蒜客 阿里巴巴的手机代理商(中等)[字典树]

题意

有四种操作:
1. 插入一个单词,词频为k
2. 删除所有a这个单词
3. 查询以a为后缀的所有单词词频和
4. 将后缀为a的单词全部更改为后缀为b的单词。

题解

建立一颗后缀字典树,每一个节点记录size与End,分别表示以当前后缀为后缀的所有单词的词频与以当前后缀为完整单词的单词数,End只更新单词的第一个字母所在的节点,size要对每个节点都更新。update操作则将整个树节点移动至目标位置即可。
注意要先删除后继节点,再将后继连接到新的节点上,否则对于 insert a 1 update a aaa q aa 操作会出错

AC代码

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<string>
using namespace std;
typedef long long ll;
ll size[1000005],tree[1000005][27],End[1000005],tot,root,n,k;
char op[15],a[1000005],b[1000005];
ll init(ll root)
{
    for(ll i=0;i<27;i++)
        tree[root][i]=-1;
    size[root]=0;
    End[root]=0;
    return root;
}
ll insert(char buf[],ll k,ll k2)
{
    int l=strlen(buf),now=root;
    for(int i=0;i<l;i++)
    {
        if(tree[now][buf[i]-'a']==-1)tree[now][buf[i]-'a']=init(++tot);
        now=tree[now][buf[i]-'a'];
        size[now]+=k;
    }
    End[now]+=k2;
    return now;
}
ll getnum(char buf[],ll flag,ll &now)
{
    now=root;
    int l=strlen(buf);
    for(int i=0;i<l;i++)
    {
        now=tree[now][buf[i]-'a'];
        if(now==-1)return 0;
    }
    if(!flag)return End[now];
    return size[now];
}
void del(char buf[],ll num,ll num2)
{
    int l=strlen(buf),now=root;
    for(int i=0;i<l;i++)
    {
        now=tree[now][buf[i]-'a'];
        size[now]-=num;
    }
    End[now]-=num2;
}
int main()
{
    ll T;
    scanf("%lld",&T);
    while(T--)
    {
        tot=0;
        init(root);
        scanf("%lld",&n);
        while(n--)
        {
            scanf("%s%s",op,a);
            ll l=strlen(a),now;
            reverse(a,a+l);
            if(op[0]=='i')
            {
                scanf("%lld",&k);
                insert(a,k,k);
            }
            if(op[0]=='d')
            {
                ll sum=getnum(a,0,now);
                if(sum==0)
                {
                    printf("Empty\n");
                    continue;
                }
                del(a,End[now],End[now]);
            }
            if(op[0]=='q')
                printf("%lld\n",getnum(a,1,now));
            if(op[0]=='u')
            {
                scanf("%s",b);
                ll l2=strlen(b),now2,tmp[27];
                reverse(b,b+l2);
                ll num=getnum(a,1,now);
                ll E=End[now];
                if(num==0)
                {
                    printf("Empty\n");
                    continue;
                }
                if(getnum(b,1,now2))
                {
                    printf("Conflict\n");
                    continue;
                }
                for(ll i=0;i<27;i++)
                    tmp[i]=tree[now][i],tree[now][i]=-1;
                now2=insert(b,num,E);
                for(ll i=0;i<27;i++)
                    tree[now2][i]=tmp[i];
                del(a,num,E);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/ACTerminate/article/details/80305963
今日推荐