标签:
Since you crave state-of-the-art technology, you‘ve just purchased a phone with a great new feature: autocomplete! Your phone‘s version of autocomplete has some pros and cons. On the one hand, it‘s very cautious. It only autocompletes a word when it knows exactly what you‘re trying to write. On the other hand, you have to teach it every word you want to use.
You have N distinct words that you‘d like to send in a text message in order. Before sending each word, you add it to your phone‘s dictionary. Then, you write the smallest non-empty prefix of the word necessary for your phone to autocomplete the word. This prefix must either be the whole word, or a prefix which is not a prefix of any other word yet in the dictionary.
What‘s the minimum number of letters you must type to send all N words?
Input begins with an integer T, the number of test cases. For each test case, there is first a line containing the integer N. Then,N lines follow, each containing a word to send in the order you wish to send them.
For the ith test case, print a line containing "Case #i: " followed by the minimum number of characters you need to type in your text message.
1 ≤ T ≤ 100
1 ≤ N ≤ 100,000
The N words will have a total length of no more than 1,000,000 characters.
The words are made up of only lower-case alphabetic characters.
The words are pairwise distinct.
NOTE: The input file is about 10-20MB.
In the first test case, you will write "h", "he", "l", "hil", "hill", for a total of 1 + 2 + 1 + 3 + 4 = 11 characters.
给n个单词,每次添加一个,查找一个,问查找你添加的这个单词,至少需要确定前多少个字母,可以确定这个单词。
求查找每个单词需要确定的字母数的和。
#include<cstdio> #include<string> #include<cstring> #include<iostream> using namespace std; const int maxn=1000100; int dic[maxn][26],val[maxn],cnt; void inst(string s) { int u,v,l,len; u=0,len=s.size(); for(l=0;l<len;l++) { v=s[l]-'a'; if(!dic[u][v]) { dic[u][v]=++cnt; memset(dic[cnt],0,sizeof dic[cnt]); } u=dic[u][v]; val[u]++; } } int get(string s) { int u,v,l,len,ret; u=0,len=s.size(); ret=len; for(l=0;l<len-1;l++) { v=s[l]-'a';; if(val[dic[u][v]]==1)//若这个字母之后都是1,说明没有其他单词了,到这就可以确定 { ret=l+1; break; } u=dic[u][v]; } return ret; } int main() { freopen("autocomplete.txt","r",stdin); freopen("outb.txt","w",stdout); int T,cas=1,i,n; string s; scanf("%d",&T); while(T--) { memset(dic[0],0,sizeof dic[0]); memset(val,0,sizeof val); cnt=0; scanf("%d",&n); int ans=0; for(i=0;i<n;i++) { cin>>s; inst(s); ans+=get(s); } printf("Case #%d: %d\n",cas++,ans); } return 0; }
Facebook Hacker Cup 2015 Round 1 --- Autocomplete
标签:
原文地址:http://blog.csdn.net/u011032846/article/details/42873735