hihocoder 1107 Dictionary tree traversal

                              Shortest Proper PrefixHihoCoder - 1107  

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.

Input

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

Output the number of shortest proper prefixes.

Sample Input
12
a
away
abc
abcde
abcde
abcba
bcd
bcde
bcbbd
bcac
bee
bbb
Sample Output
4


The approximate meaning of the title: Find the number of times the prefix appears less than 5
The idea is to traverse the dictionary tree directly, and end the recursion when the number of occurrences of the letters ans++ is less than 5.

code show as below:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<string>
#include<queue>
#include<vector>
#include<stack>
#include<list>
using namespace std;
const int maxn=10000000+10;
int trie[maxn][30];
int f[maxn];
int cnt;
int ans;
void _insert(char *b)
{
    int temp=0;
    int len=strlen(b);
    for(int i=0;i<len;i++)
    {
        f[temp]++;
        if(!trie[temp][b[i]-'a']) trie[temp][b[i]-'a']=++cnt;
        temp=trie[temp][b[i]-'a'];
    }
    f[temp]++;
}
void dfs(int u)
{
    if(u==0) return ;
    if(f[u]>0&&f[u]<=5) {ans++;return ;}
    for(int i=0;i<26;i++)
    {
        if(trie[u][i]>0)
        dfs(trie[u][i]);
    }
}
int main()
{
    int n;
    char a[12];
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",a);
        _insert(a);
    }
    for(int i=0;i<26;i++)
    {
        dfs(trie[0][i]);
    }
    printf("%d\n",ans);
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326281258&siteId=291194637