HDU 3460 Ancient Printer

Problem Description
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.
 

Sample Input
   
   
   
   
2 freeradiant freeopen


分析:字典树。对字符串建立字典树,统计字典树的节点数(ans),最长字符串的长度(maxlen),以及字符串个数(n)。则答案就是:ans*2-maxlen+n。ans*2指对于字符串的每个字符都要进行一次Typet和Del,+n指每个字符串都要Print,而-maxlen则是因为最后的字符串不许Del,所以选择最长的一个在最后打印。


Code:

#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <vector>
#include <queue>
#include <cmath>
#include <map>
#include <set>
#define eps 1e-7
#define LL long long
#define pb push_back
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;

struct Trie{
    Trie *Next[26];
    Trie(){
        for(int i=0;i<26;i++) Next[i]=NULL;
    }
}root;
char str[55];
int ans,maxlen;

void InsertTrie(int len){
    if(len>maxlen) maxlen=len;
    Trie *p=&root;
    for(int i=0;i<len;i++){
        int id=str[i]-'a';
        if(p->Next[id]==NULL){
            ans++;
            p->Next[id]=new Trie;
        }
        p=p->Next[id];
    }
}

int main()
{
    int n;
    while(scanf("%d",&n)==1){
        ans=maxlen=0;
        for(int i=0;i<26;i++) root.Next[i]=NULL;
        for(int i=0;i<n;i++){
            scanf("%s",str);
            InsertTrie(strlen(str));
        }
        printf("%d\n",ans*2-maxlen+n);
    }
    return 0;
}


你可能感兴趣的:(HDU 3460 Ancient Printer)