hdu3460(字典树)

Ancient Printer

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 1017    Accepted Submission(s): 476


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
 

Author
iSea @ WHU
 

Source
2010 ACM-ICPC Multi-University Training Contest(3)——Host by WHU
 
一种比较容易想到的方法就是建立一棵带前缀字典树即tries图(AC自动机),然后深搜一遍,看了一下题目,最多有10000*50个结点,可能超时而且自动机实现复杂。
于是想到找规律,本题的规律还是比较明显的:
 
首先建立一棵字典树
最终答案等于=单词数+2*结点总数-最长单词字符数
其中的道理为单词数对应Print次数,每个单词都在字典树上对应一个分支,字典树上的所有节点都要输入一次删一次,最长的那个分支只输入一次不删
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;

typedef struct node
{
	node *next[26];
	node()
	{
		for(int i=0;i<26;i++)
			next[i]=NULL;
	}
}Trie;
Trie *root;
int num_node;

//将str插入以root为根节点的字典树中
void insert(char *str)
{
    int len = strlen(str);
    Trie *s = root;
    for (int i = 0; i < len; i++)
	{
		if (s->next[str[i] - 'a'])
            s = s->next[str[i] - 'a'];
        else
		{
            Trie* t = new Trie;
			num_node++;
            s->next[str[i] - 'a'] = t;
            s = t;
        }
	}
}



int main()
{
	int n,i,mlen;
	char str[55];
	while(~scanf("%d",&n))
	{
		root=new Trie;
		mlen=0;
		num_node=0;
		for(i=0;i<n;i++)
		{
			scanf("%s",str);
			int len=strlen(str);
			if(len>mlen)mlen=len;
			insert(str);
		}

		printf("%d\n",n+num_node*2-mlen);
	}
	return 0;
}

 

你可能感兴趣的:(数据结构,字典树,找规律)