BZOJ 3439 Kpm的MC密码 Trie+可持久化线段树

题目大意:定义一种串,如果一个串是另一个串的后缀,那么这个串称作kpm串。问一个串的标号第k大的kpm串是多少。


思路:将所有的串翻转之后变成前缀,全都插进一个Trie树中。每个节点维护一个last指针,表示最后一次更新的可持久化线段树的指针,如果再有串经过这里,就继续更新last指针。最后只需要查询last指针中的东西就可以了。


CODE:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 300010
using namespace std;
#define P(a) ((a) - 'a')
 
struct SegTree{
    SegTree *son[2];
    int cnt;
     
    SegTree(SegTree *_,SegTree *__,int ___) {
        son[0] = _;
        son[1] = __;
        cnt = ___;
    }
    SegTree() {}
}none,*nil = &none;
 
SegTree *BuildTree(SegTree *last,int l,int r,int x)
{
    if(l == r)  return new SegTree(NULL,NULL,last->cnt + 1);
    int mid = (l + r) >> 1;
    if(x <= mid) return new SegTree(BuildTree(last->son[0],l,mid,x),last->son[1],last->cnt + 1);
    return new SegTree(last->son[0],BuildTree(last->son[1],mid + 1,r,x),last->cnt + 1);
}
 
struct Trie{
    Trie *son[26];
    SegTree *last;
     
    Trie() {
        memset(son,0,sizeof(son));
        last = nil;
    }
}*root = new Trie(),*end_pos[MAX];
 
int cnt;
char s[MAX];
 
inline void Insert(char *s,int p)
{
    Trie *now = root;
    while(*s != '\0') {
        if(now->son[P(*s)] == NULL)
            now->son[P(*s)] = new Trie();
        now = now->son[P(*s)];
        now->last = BuildTree(now->last,1,MAX,p);
        ++s;
    }
    end_pos[p] = now;
}
 
int Ask(SegTree *now,int l,int r,int k)
{
    if(now->cnt < k)  return -1;
    if(l == r)  return l;
    int mid = (l + r) >> 1;
    if(k <= now->son[0]->cnt)  return Ask(now->son[0],l,mid,k);
    return Ask(now->son[1],mid + 1,r,k - now->son[0]->cnt);
}
 
int main()
{
    cin >> cnt;
    nil->son[0] = nil->son[1] = nil;
    for(int i = 1; i <= cnt; ++i) {
        scanf("%s",s);
        reverse(s,s + strlen(s));
        Insert(s,i);
    }
    for(int k,i = 1; i <= cnt; ++i) {
        scanf("%d",&k);
        printf("%d\n",Ask(end_pos[i]->last,1,MAX,k));
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值