博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Ancient Printer
阅读量:6690 次
发布时间:2019-06-25

本文共 2379 字,大约阅读时间需要 7 分钟。

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

题解:要想得到最少就要操作最少,所以对于有公共前缀的字符串,前缀仅仅打印一次。

首先我们把全部字符串用字典树保存。此时这棵树的每个节点都要打印,除了根(不包括字母),如今全部节点都要打印和删除。可是最后一个字符串不删除,该字符串肯定是最长的了。所以公式=res=2 * (n (节点数)- 1) + m(打印次数) - maxlen(最长字符串)。

#include 
#include
#include
using namespace std;struct Node{ Node* next[26]; Node() { for(int i = 0;i < 26;i++) { next[i] = NULL; } }};int res = 0;Node* root;int max(int a,int b){ return a > b ?

a : b; } void insert(char* s) { Node* p = root; int len = strlen(s); for(int i = 0; i < len;i++) { int x = s[i] - 'a'; if(p->next[x] == NULL) { Node* q = new Node(); p->next[x] = q; res++; } p = p->next[x]; } } void del(Node*& root) { for(int i = 0; i < 26;i++) { if(root->next[i] != NULL) { del(root->next[i]); } } delete root; } int main() { int n; while(scanf("%d",&n) != EOF) { root = new Node(); char s[100]; res = 0; int maxlen = 0; for(int i = 0;i < n;i++) { scanf("%s",s); maxlen = max(maxlen,strlen(s)); insert(s); } res = 2 * res + n - maxlen; printf("%d\n",res); del(root); } return 0; }

转载地址:http://ynhao.baihongyu.com/

你可能感兴趣的文章
linux解压war包的命令
查看>>
MyQThread new
查看>>
js的继承
查看>>
SOCKET用法详解
查看>>
C++11的新特性:右值引用
查看>>
memcache和redis的区别
查看>>
NodeJS、NPM安装配置步骤(windows版本)
查看>>
spring xml配置文件根元素(文件头文件)说明
查看>>
windows ssh RPi 2B
查看>>
Git常用命令
查看>>
异常,File,递归,IO流
查看>>
百度地图、ECharts整合HT for Web网络拓扑图应用
查看>>
大数据学习系列之三 ----- HBase Java Api 图文详解
查看>>
cookie和session
查看>>
小白的正则表达式学习之旅-02
查看>>
学习C语言必须知道的理论知识(第三章-数据类型的分类)
查看>>
hdu 素数环
查看>>
H3C CAS 介绍 & 基本概念
查看>>
xxx
查看>>
openSUSE 安装 Caffe
查看>>