HDU3460 (字典树)

时间:2022-07-28
本文章向大家介绍HDU3460 (字典树),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意描述

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.

可以进行3个操作,打印a~z,删除字母,输出。给定n个字符串,求能够输出n个字符串能够进行的最少操作

思路

我们可以建一颗trie树来保存所有字母,由于相同的前缀只需要打印1次,也只需要删除一次,要想操作次数最少,肯定要把最长的字符串留在最后,所以可以得到公式ans=(node.size())*2-MAXLEN+n。

AC代码

#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#define x first
#define y second
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=500010;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
int cnt=0;
struct trie{
    int tot,root,child[N][26];
    bool flag[N];
    void init(){
        memset(child[1],0,sizeof child[1]);
        flag[1]=false;
        root=tot=1;
    }
    void Insert(const char*str){
        int *cur=&root;
        for(const char *p=str;*p;p++){
            cur=&child[*cur][*p-'a'];
            if(*cur==0){
                *cur=++tot;
                memset(child[tot],0,sizeof child[tot]);
                flag[tot]=false;
                cnt++;
            }
        }
        flag[*cur]=true;
    }
    bool query(const char*str){
        int *cur=&root;
        for(const char*p=str;*p;p++){
            cur=&child[*cur][*p-'a'];
        }
        return (*cur && flag[*cur]);
    }
};
void solve(){
    int n;
    while(scanf("%d",&n)!=EOF){
        trie tr;
        cnt=0;
        tr.init();
        int MAX=-1;
        string s;
        for(int i=0;i<n;i++){
            cin>>s;
            int nn=s.size();
            MAX=max(MAX,nn);
            tr.Insert(s.c_str());
        }
        int ans=cnt*2-MAX+n;
        printf("%dn",ans);
    }
}
int main(){
    //IOS;
    solve();
    return 0;
}