题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3460
题意:给出N个单词,求出打印出所有单词所需的最少操作。我们可以这样量解,需要往打印机里依次入一个单词的字母,具体有三种操 作:1、打印出打印机里的单词,2、往打印里入进一个字母,3、删除打印机里的最后一个字母。
解析:有多种解法,这里说一下用字典树处理的方法吧。处理单词的时候,就是尽可能地保留前缀,就可使操作次数最小,所以要输出一个单词后,要删除打印机里字母数最少,来与剩下的所有单词能匹配的长度最长,这不就是字典树的遍历吗?我们假设打印机里最后不剩单词,都全部删除,每个结点都进出打印机一次,最后再减去所有单词中最长的长度,因为最后打印机里可以留一个单词不用删除。 (题中没说有没有重复单词,代码没考虑,考虑的话 结构体中的num值存每种单词的个数,改着也很简单)。
参考代码:
#include<string>
using namespace std;
struct Node{
int index,num;
struct Node *next[27];
Node(){
num = index = 0;
memset(next,NULL,sizeof(next));
}
};
template<int MAXW>
class Trie{
public:
Trie(){}
void clear(){index = 0;root = new Node;}
int insert(string str){
rot = root;
for(int i = 0;i < str.size();++i){
if(!rot->next[str[i] - 'a'])
rot->next[str[i] - 'a'] = new Node;
rot = rot->next[str[i] - 'a'];
if(i == str.size() - 1){
if(!rot->index) rot->index = ++index;
rot->num++;
}
}
return rot->index;
}
void Search(Node *root1,int &res){
for(int i = 0;i < 26;++i)
{
if(root1->next[i])
{
res += 2;
Search(root1->next[i],res);
}
}
}
int result(){
int res = 0;
Search(root,res);
return res;
}
void Deletes(Node * root1)
{
if(!root1){
delete root1;
return ;
}
for(int i = 0;i < 26;++i)
if(root1->next[i])
Deletes(root1->next[i]);
}
void Delete(){
Deletes(root);
}
private:
int index;
struct Node *root,*rot;
};
Trie<10005> t;
int main()
{
int n;
while(scanf("%d",&n) != EOF)
{
char str[55];
int len,max_len = 0;
t.clear();
for(int i = 0;i < n;++i)
{
scanf("%s",str);
len = strlen(str);
max_len = max(len,max_len);
t.insert(str);
}
printf("%d\n",t.result()+n-max_len);
t.Delete();
}
return 0;
}