您的位置:首页 > 其它

hdu 3460 Ancient Printer

2015-12-04 09:29 423 查看
[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each test case, output one integer, indicating minimum number of operations.

[align=left]Sample Input[/align]

2

freeradiant

freeopen

[align=left]Sample Output[/align]

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

[align=left]Author[/align]
iSea @ WHU

[align=left]Source[/align]
2010 ACM-ICPC Multi-University Training Contest(3)——Host by WHU

题解:刚开始没理解题意,看了题解才知道要干嘛..... 知道题意之后,感觉真的挺水的.....

选择最长的那个单词在最后一次打印,这样子才能节省最短的步数。

所以,直接遍历统计Trie树上的字母个数ans, 设最长的单词长度为max,那么答案便是 2*ans+n-max.

ans要乘2, 是因为打印后还要一个一个删除掉,相当于每个单词走了两次。

加上n, 就是打印的次数。

减去maxLen,是因为最后一个单词不需要删除。

代码:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <ctype.h>
#include <iomanip>
#include <queue>
#include <stdlib.h>
using namespace std;

struct node
{
int count;
node *next[26];
node(){          //构造函数
count=0;
memset(next,0,sizeof(next));
}
};
node *root;
int ans;
char s[55];
void insert(char *s)
{
node *p;
p=root;
int len=strlen(s);
for(int i=0;i<len;i++){
int id=s[i]-'a';
if(!p->next[id]){
ans++;
p->next[id]=new node;
}
p=p->next[id];
}
}
int main()
{
int n,i;
while(scanf("%d",&n)!=EOF)
{
root=new node;
ans=0;
int max=0;
for(i=1;i<=n;i++)
{
scanf("%s",s);
insert(s);
int len=strlen(s);
if(len>max) max=len;
}
printf("%d\n",2*ans-max+n);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: