计蒜客 后缀字符串(字典树)

一天蒜头君得到n个字符串Si,每个字符串的长度都不超过 10。
蒜头君在想,在这 nnn 个字符串中,以 sis_isi​ 为后缀的字符串有多少个呢?
输入格式
第一行输入一个整数 n。
接下来 n 行,每行输入一个字符串 Si​。
输出格式
输出 n 个整数,第 i 个整数表示以 Si​ 为后缀的字符串的个数。

参考题解

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
//The template of trie tree
const int maxn = 1e5+5;
int trie[maxn<<3][26], sum[maxn<<3];
int tot, n;
string str[maxn];

void insert(string str)
{
    int root = 0, len = str.length();
    for(int i = len-1; i >= 0; i--)
    {
        int id = str[i]-'a';
        if(trie[root][id] == 0) trie[root][id] = ++tot;
        root = trie[root][id];
        sum[root]++;
    }
}

int find(string str)
{
    int root = 0, len = str.length();
    bool ok = true;
    for(int i = len-1; i >= 0; i--)
    {
        int id = str[i]-'a';
        if(trie[root][id] == 0)
        {
            ok = false;
            break ;
        }
        root = trie[root][id]; 
    }
    if(ok)  return sum[root];
    return 0;   //Not Found
}

int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
    {
        cin >> str[i];
        insert(str[i]);
    }
    for(int i = 1; i <= n; i++) printf("%d\n", find(str[i]));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40788897/article/details/100176484
今日推荐