hdu 3460 字典树

         这道题想了3天,,,,,还是没有想出来。刚开始把题意理解错了,后来明白错在哪里后,还是做不出来,,,,,,,,就这样一直纠结。。。。最后还是没能做出来。上网看了看,才明白自己想得方向都是错得。杯具,稍微有点难度的字典树就做不出来了,看来对字典树的理解还是不够深刻啊。。。。。还需要做更多的题。。题目:

Ancient Printer

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 16   Accepted Submission(s) : 4
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
 

ac代码:

#include <iostream>
#include <algorithm>
#include <string.h>
#include<string>
#include<malloc.h>
using namespace std;
int num=0;
struct Tire{
  int count;
  struct Tire *tire[26];
}*a;
void init(){
  a=(Tire*)malloc(sizeof(Tire));
  for(int i=0;i<26;++i)
	  a->tire[i]=NULL;
}
void insert(char s[]){
  int len=strlen(s);
  Tire *head=a;
  for(int i=0;i<len;++i){
    int k=s[i]-'a';
	if(head->tire[k]==NULL){
		head->tire[k]=new Tire;
		head=head->tire[k];
		for(int j=0;j<26;++j)
			head->tire[j]=NULL;
		num++;
	}
	else
		head=head->tire[k];
  }
}
void del(Tire *root){
	for(int i=0;i<26;++i){
		if(root->tire[i]!=NULL)
			del(root->tire[i]);
		delete(root->tire[i]);
	}
}
int main(){
  int n;
  while(~scanf("%d",&n)){
    init();
	num=0;
	char ss[51];
	int max=0,m=n;
	while(m--){
	  scanf("%s",ss);
	  int len=strlen(ss);
	  if(len>max)
		  max=len;
	  insert(ss);
	}
	//printf("%d\n",num);
	printf("%d\n",2*num-max+n);
	del(a);
  }
  return 0;
}


阅读更多
个人分类: 字典树 数据结构
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭