题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=3460
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
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个字符串,打印机只能进行如下3种操作:
①在缓冲区末尾增加一个字符
②在缓冲区末尾删除一个字符
③打印出缓冲区内容
要求打印出全部n个字符串,求最少的操作步数。
题解:
参考自https://blog.csdn.net/secfly/article/details/50607194,把所有的字符串加到字典树里,算出字典树节点个数num(不含根节点) ,num*2加上n次打印减去最长单词长度就是答案。
原因: 要想结果最少,最后一个单词打印了肯定就不需要再删除掉,
假如把最后一次单词也删除掉,最后完成后缓冲区为空。
那么所有字母肯定是经历了输入到缓冲区再被删除出去的过程。(两个单词有公共前缀的话,那这个前缀不能被分别增加删除1次)
这样增加字符删除字符的操作步数就是字符数*2,这个字符数就是指把所有单词放入字典树统计出来的节点数(不含根节点)。
因为最后一次多删除了一个单词,需要补回来,那该让哪个单词放在最后呢? 当然是最长的那个单词。
这样算出的结果加上n次打印就满足题目要求了。
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
char input[55];
int cnt = 0; // 节点个数
int n;
int maxLen = 0;
struct Node {
char ch;
Node *next[26];// 子节点
Node(char c){
for(int i = 0;i < 26;i++) next[i] = NULL;
ch = c;
}
~Node() {
for(int i = 0;i < 26;i++) {
if(next[i] != NULL) delete next[i];
}
}
} *root;
// 建树
void Build() {
int len = strlen(input);
maxLen = max(maxLen,len);
Node *cur = root;
int index = 0;
while(cur && (index < len)) {
if(cur->next[input[index]-'a'] == NULL) {
cur->next[input[index]-'a'] = new Node(input[index]);
cnt++;
cur = cur->next[input[index]-'a'];
index++;
} else {
cur = cur->next[input[index]-'a'];
index++;
}
}
}
int main()
{
while(scanf("%d",&n) != EOF) {
root = new Node('a');// 任意赋值
cnt = 0;
maxLen = 0;
for(int i = 0;i < n;i++) {
scanf("%s",input);
Build();
}
printf("%d\n",2*cnt - maxLen + n);
delete root;
}
return 0;
}