hdu 3460 Ancient Printer (字典树)

来源:互联网 发布:练字软件app 编辑:程序博客网 时间:2024/05/21 17:00

题意:

给出n个单词,现在模拟键盘输入,输入字母和删除以及发送都要算操作数。现在给出的n个单词不管顺序如何,将所有单词输出的最小操作数。

题解:

没想可以这样做,我们把这些单词存入字典树,然后把字典树画出来,很容易得出这个结论:假设字典树节点的个数为m,最长单词长度为maxl,那么最小操作数=2*m-maxl+n

#include<iostream>#include<math.h>#include<stdio.h>#include<algorithm>#include<string.h>#include<vector>#include<map>using namespace std;typedef long long lld;const int oo=0x3f3f3f3f;const lld OO=1e18;const int Mod=1000000007;const int maxn=5000+5;const int maxm=12;int n,m,T;char word[55];void output(char str[],int s,int e){    for(int i=s;i<=e;i++)        printf("%c",str[i]);}struct Trie{    struct TrieNode    {        TrieNode* child[26];        TrieNode()        {            memset(child,NULL,sizeof child);        }    }*root;    Trie()    {        root=new TrieNode();    }    void Insert(char str[])    {        TrieNode* p=root;        for(int i=0,k;str[i];i++)        {            k=str[i]-'a';            if(!p->child[k])                p->child[k]=new TrieNode();            p=p->child[k];        }    }    int dfs(TrieNode* p)    {        int res=0;        for(int i=0;i<26;i++)            if(p->child[i])                res+=dfs(p->child[i])+1;        return res;    }    int Search()    {        return dfs(root);    }    void Free(TrieNode* Root)    {        TrieNode* p=Root;        for(int i=0;i<26;i++)            if(p->child[i])                Free(p->child[i]);        delete p;    }    ~Trie()    {        Free(root);    }};///字典树数据结构到此为止int main(){    int n,maxl;    while(scanf("%d",&n)!=EOF)    {        Trie tree;        maxl=0;        for(int i=1;i<=n;i++)        {            scanf("%s",word);            tree.Insert(word);            maxl=max(maxl,(int)strlen(word));        }        printf("%d\n",2*tree.Search()+n-maxl);    }    return 0;}/**2freeradiantfreeopen*/




0 0