每日一题之 hiho1107 Shortest Proper Prefix(字典树变形)

These days Little Hi has been working on a way to improve the QAC performance. He collected N high-frequency queries. We say a string s is a proper prefix if there are no more than 5 collected queries have s as a prefix. A string s is a shortest proper prefix if s is a proper prefix and all the prefixes of s(except for s itself) are not proper prefixes. Little Hi wants to know the number of shortest proper prefixes given N collected queries.

Hint: the 4 shortest proper prefixes for Sample Input are “ab”, “bb”, “bc” and “be”. Empty string “” is not counted as a proper prefix even if N <= 5.

输入
The first line contains N(N <= 10000), the number of collected queries.

The following N lines each contain a query.

Each query contains only lowercase letters ‘a’-‘z’.

The total length of all queries are no more than 2000000.

Input may contain identical queries. Count them separately when you calculate the number of queries that have some string as a prefix.

输出
Output the number of shortest proper prefixes.

样例输入
12
a
ab
abc
abcde
abcde
abcba
bcd
bcde
bcbbd
bcac
bee
bbb
样例输出
4

题意:

在字典树中前缀出现次数不超过5的前缀的个数

思路:

用字典树模板,然后遍历这棵树,找到一个满足条件的前缀则++res

#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <cstdlib>

using namespace std;

const int maxn = 30;

typedef struct Trie
{
    Trie *next[maxn];
    int v;
    Trie(){
        v = 0;
        for (int i = 0; i < maxn; ++i)
            next[i] = nullptr;
    }
};

Trie root;

int res = 0;

void creatTrie(string s)
{
    int len = s.length();
    Trie *p = &root, *q;
    for (int i = 0; i < len; ++i) {
        int idx = s[i]-'a';
        if (p->next[idx] == nullptr) {
            q = new Trie();
            q->v = 1;
            p->next[idx] = q;

        }
        else 
            p->next[idx]->v++;

        p = p->next[idx];
    }

}



void visit(Trie *root) 
{
    Trie *tmp = root;
    if (tmp->v <= 5 && tmp->v > 0) {
        ++res;
        return;
    }
    for (int i = 0; i < maxn; ++i) {
        if (tmp->next[i] != nullptr)
            visit(tmp->next[i]);
    }
}



int main()
{
    vector<string>str;
    set<string>prefix;
    int n;
    string s;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> s;
        creatTrie(s);
    }

    visit(&root);

    cout << res << endl;

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值