BZOJ4567 [Scoi2016]背单词 【trie树 + 贪心】

题目链接

BZOJ4567

题解

题意真是鬼畜= =
意思就是说我们应先将一个串的所有后缀都插入之后再插入这个串,产生代价为其到上一个后缀的距离

我们翻转一下串,转化为前缀,就可以建\(trie\)树来解决了
建好\(trie\)后单独取出单词节点,贪心先往子树小的节点编号即可

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
using namespace std;
const int maxn = 100005,maxm = 600005,INF = 1000000000;
inline int read(){
    int out = 0,flag = 1; char c = getchar();
    while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
    while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
    return out * flag;
}
char s[maxm];
int n,ch[maxm][26],fail[maxm],last[maxm],tag[maxm],cnt;
void ins(int x){
    int u = 0,len = strlen(s + 1),id;
    reverse(s + 1,s + 1 + len);
    for (int i = 1; i <= len; i++){
        id = s[i] - 'a';
        u = ch[u][id] ? ch[u][id] : (ch[u][id] = ++cnt);
    }
    tag[u] = x;
}
LL ans;
int now,id[maxm],fa[maxm],siz[maxm];
priority_queue<cp,vector<cp>,greater<cp> > son[maxm];
void dfs1(int u){
    siz[u] = tag[u] > 0;
    for (int i = 0; i < 26; i++){
        if (!ch[u][i]) continue;
        fa[ch[u][i]] = tag[u] ? u : fa[u];
        dfs1(ch[u][i]);
        siz[u] += siz[ch[u][i]];
    }
    if (tag[u]) son[fa[u]].push(mp(siz[u],u));
}
void dfs2(int u){
    if (tag[u]){
        id[u] = ++now;
        ans += id[u] - id[fa[u]];
    }
    while (!son[u].empty()){
        int to = son[u].top().second; son[u].pop();
        dfs2(to);
    }
}
int main(){
    n = read();
    REP(i,n){
        scanf("%s",s + 1);
        ins(i);
    }
    dfs1(0);
    dfs2(0);
    printf("%lld\n",ans);
    return 0;
}

转载于:https://www.cnblogs.com/Mychael/p/9081249.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值