Ancient Printer(HDU-3460)(字典树)

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

Sample Output

21

        
  

Hint

The sample's operation is:
f-r-e-e-o-p-e-n-Print-Del-Del-Del-Del-r-a-d-i-a-n-t-Print
        
 

题意:一个人有一台打印机,然后他想打印一些字符串,每一次,他可以在打印机的末端打印字母,或删除最后一个字母,或打印当前的单词。打印后,字母仍然在打印机中,你可以删除一些字母来打印下一个,但你不必删除最后一个单词的字母。问最少多少次操作能够输出n个字符串。

思路:这道题的话,算每个字符的出现次数,每个字符都会出现两次,一次删除一次添加。但是最后一格输出的单词只出现一次,因此把n个字符串插入字典树中,节点个数就是字符个数。然后我们找最长串,因为最长串不会被重复打印,再加上打印的次数所以最后答案就是:节点个数*2-最长串长度+n。很坑的是没看清题里给的数据范围,RE了4发。。说多都是泪。。

AC代码:

#include <bits/stdc++.h>
typedef long long ll;
const int maxx=10010;
const int maxn=26;
const int inf=0x3f3f3f3f;
using namespace std;
int Trie[maxx][maxn];
char s[55];
int k;
void init()
{
    memset(Trie,0,sizeof(Trie));
    k=0;
}
void insert(char *w)
{
    int p=0;
    int len=strlen(w);
    for(int i=0; i<len; i++)
    {
        int c=w[i]-'a';
        if(!Trie[p][c])
        {
            Trie[p][c]=++k;
        }
        p=Trie[p][c];
    }
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        init();
        int ans=0;
        for(int i=0; i<n; i++)
        {
            scanf("%s",s);
            insert(s);
            int len=strlen(s);
            ans=max(ans,len);
        }
        printf("%d\n",k*2-ans+n);
    }
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值