Shortest Proper Prefix---Trie树

46 篇文章 0 订阅

Query auto-completion(QAC) is widely used in many search applications. The basic idea is that when you type some string s in the search box several high-frequency queries which have s as a prefix are suggested. We say string s1 has string s2 as a prefix if and only if the first |s2| characters of s1 are the same as s2 where |s2| is the length of s2.

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

#include "iostream"
#include "cmath"
#include "cstring"
#include "fstream"

using namespace std;

struct Trie
{
    int cnt;   //该前缀对应的单词数量
    struct Trie *child[26];  //分支
};

Trie *create()
{
    Trie *node = (Trie *)malloc(sizeof(Trie));
    node->cnt = 0;
    memset(node->child, 0, sizeof(node->child));  //初始化为空指针
    return node;
}

void insert(Trie *root, char *s)
{
    int i = 0;
    Trie *p = root;
    while(s[i] != '\0')
    {
        root->cnt++;
        int x = s[i] - 'a';
        if(p->child[x] == NULL)  //如果不存在,则建立新结点
            p->child[x] = create();

        p = p->child[x];  //转入分支
        p->cnt++;
        i++;
    }
}

int trval(Trie *root)
{
    if(root->cnt <=5)
        return 1;

    int total = 0;
    for(int i=0; i<26; i++)
        if(root->child[i] != NULL)
            total += trval(root->child[i]);
    return total;
}

int main()
{
    //ifstream cin("1.txt");
    int n;
    cin >> n;
    char str[2000001];
    Trie *root = create();

    while(n--)
    {
        cin >> str;
        insert(root, str);
    }

    cout << trval(root) << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值