1. 程式人生 > >HDU-3460 Ancient Printer 字典樹

HDU-3460 Ancient Printer 字典樹

The contest is beginning! While preparing the contest, iSea wanted to print the teams' names separately on a single paper.  Unfortunately, what iSea could find was only an ancient printer: so ancient that you can't believe it, it only had three kinds of operations:  ● 'a'-'z': twenty-six letters you can type  ● 'Del': delete the last letter if it exists  ● 'Print': print the word you have typed in the printer  The printer was empty in the beginning, iSea must use the three operations to print all the teams' name, not necessarily in the order in the input. Each time, he can type letters at the end of printer, or delete the last letter, or print the current word. After printing, the letters are stilling in the printer, you may delete some letters to print the next one, but you needn't delete the last word's letters.  iSea wanted to minimize the total number of operations, help him, please.

Input

There are several test cases in the input.  Each test case begin with one integer N (1 ≤ N ≤ 10000), indicating the number of team names.  Then N strings follow, each string only contains lowercases, not empty, and its length is no more than 50.  The input terminates by end of file marker. 

Output

For each test case, output one integer, indicating minimum number of operations.

#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> using namespace std; int nex[500005][26]; //int sum[1000005]; int tot,p,t,len; int summ; char s[60]; void init() {     memset(nex,0,sizeof(nex));    // memset(sum,0,sizeof(sum));     tot=0;summ=0; } void insert() {     len=strlen(s);     p=0;     for(int i=0;i<len;i++)     {         t=s[i]-'a';         if(!nex[p][t])             nex[p][t]=++tot;//節點         p=nex[p][t];        // sum[p]++;     } } void Find(int p)//查有多少節點,有點蠢,tot就是節點數,竟然沒直接用 {

    for(int i=0;i<26;i++)     {         if(nex[p][i]!=0)         {             summ++;             Find(nex[p][i]);             summ++;         }     } } int main() {     int t;     while(~scanf("%d",&t))     {         init();         int m=0;         for(int i=0;i<t;i++)         {             scanf("%s",s);             int l=strlen(s);             insert();             if(m<l)                 m=l;         }         //Find(0);         //printf("%d %d %d %d\n",summ-m+t,summ,m,t);         printf("%d\n",tot*2-m+t);//直接用節點數乘二,        // printf("%d\n",summ-m-t);//這個是從新查節點     }      return 0; }