[USACO08DEC] 秘密消息Secret Message (Trie树)

题目链接


Solution

Trie 树水题。
直接将前面所有字符串压入Trie 中.
在查询统计路上所有有单词的地方和最后一个地方以下的单词数即可.

Code

#include<bits/stdc++.h>
using namespace std;
const int maxn=500005;
int ch[maxn][10];
int num[maxn],pd[maxn];
int n,m,tot;
int c[maxn];
int read()
{
    char ch=getchar(); int f=1,w=0;
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch<='9'&&ch>='0'){w=w*10+ch-'0';ch=getchar();}
    return f*w;
}
void insert()
{
    int u=0,p,len=read();
    for(int i=0;i<len;i++)
    {
        p=read();
        if(!ch[u][p])
        ch[u][p]=++tot;
        u=ch[u][p];
        num[u]++;
    }
    num[u]--;
    pd[u]++;
    return;
}

void query()
{
    int u=0,ans=0,p,len=read(),flag=0;
    for(int i=0;i<len;i++)
    {
        p=read();
        ans+=pd[ch[u][p]];
        if(ch[u][p])
        u=ch[u][p];
        else {if(!flag)
        cout<<ans<<endl;flag=1;}
    }
    ans+=(num[u]);
    if(!flag)
    cout<<ans<<endl;
    return;
}

int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    insert();
    for(int i=1;i<=m;i++)
    query();
}

猜你喜欢

转载自www.cnblogs.com/Kv-Stalin/p/9470831.html