首页 / 软件开发 / 数据结构与算法 / 算法题:HDU 3460 Ancient Printer
算法题:HDU 3460 Ancient Printer2014-03-17 csdn博客 shuangde800链接:http://acm.hdu.edu.cn/showproblem.php?pid=3460题目:Ancient PrinterTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)Total Submission(s): 955 Accepted Submission (s): 441Problem DescriptionThe 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 printerThe 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.InputThere 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.OutputFor each test case, output one integer, indicating minimum number of operations.Sample Input2 freeradiant freeopenSample Output21HintThe 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分析与总结:这题是昨晚睡觉前1小时做的,初看时觉得挺水的,直接遍历一遍,根据所走的路径进行计数,回溯 时也要计数(如果已经全部打印完了,那么回溯时就不再计数了)。样例得出来后很开心地提交了,结果WA得一塌糊涂。改了几个地方后还是WA, 然后就先睡觉了。第二天醒来再想这道题,发现那样计数是不可以的。因为那样子遍历,遍历到的最后一个单词一定是 字典序最大的,但是字典序最大的不一定是最短的,应该选择最长的那个单词在最后一次打印,这样子 才能节省最短的步数。所以,直接遍历统计Trie树上的字母个数cnt, 设最长的单词长度为maxLen,那么答案便是 2*cnt+n-maxLen.cnt要乘2, 是因为打印后还要一个一个删除掉,相当于每个单词走了两次。加上n, 就是打印的次数。减去maxLen,是因为最后一个单词不需要删除。