HDU3460 (字典树)

15 篇文章 1 订阅
2 篇文章 0 订阅

题意描述

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("%d\n",ans);
    }
}
int main(){
    //IOS;
    solve();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值