半回文 51Nod - 1464

https://www.51nod.com/Challenge/Problem.html#!#problemId=1464

求字典序第k大 且数据量比较小 应该想到字典树

但如果将每一个半回文串都插到树上 复杂度是n^3的 看了题解 其实可以预处理一下 找出以s为起点的所有半回文串中最大的终点值e 每次只插入[s,e]这一段 最后每个节点都“pushup”即可 这样复杂度就是n^2

 

#include <bits/stdc++.h>
using namespace std;
const int maxm=2e6+10;
const int maxn=5e3+10;

struct node
{
    int ch[2];
    int flag,val;
};

node tree[maxm];
bool dp[maxn][maxn];
int ary[maxn],dis[maxn];
int n,k,num;
char ch[maxn];

void init()
{
    int i,j;
    for(i=1;i<=n;i++){
        dp[i][i]=1;
    }
    for(i=2;i<=n;i++){
        for(j=1;j+i-1<=n;j++){
            if(ary[j]==ary[j+i-1]&&(i<=5||dp[j+2][j+i-3])){
                dp[j][j+i-1]=1;
            }
        }
    }
    for(i=1;i<=n;i++){
        for(j=i;j<=n;j++){
            if(dp[i][j]){
                dis[i]=max(dis[i],j);
            }
        }
    }
}

void update(int cur,int step,int s,int e)
{
    if(step>e) return;
    if(tree[cur].ch[ary[step]]==0) tree[cur].ch[ary[step]]=++num;
    tree[tree[cur].ch[ary[step]]].flag+=dp[s][step];
    tree[tree[cur].ch[ary[step]]].val+=dp[s][step];
    update(tree[cur].ch[ary[step]],step+1,s,e);
}

void safari(int cur)
{
    if(tree[cur].ch[0]>0){
        safari(tree[cur].ch[0]);
        tree[cur].val+=tree[tree[cur].ch[0]].val;
    }
    if(tree[cur].ch[1]>0){
        safari(tree[cur].ch[1]);
        tree[cur].val+=tree[tree[cur].ch[1]].val;
    }
}

void dfs(int cur,int k)
{
    //printf("*%d %d*\n",k,tree[cur].flag);
    k-=tree[cur].flag;
    if(k<=0) return;
    if(tree[cur].ch[0]>0&&tree[tree[cur].ch[0]].val>=k){
        //printf("a\n");
        printf("a");
        dfs(tree[cur].ch[0],k);
    }
    else if(tree[cur].ch[1]>0){
        //printf("b\n");
        printf("b");
        if(tree[cur].ch[0]>0) dfs(tree[cur].ch[1],k-tree[tree[cur].ch[0]].val);
        else dfs(tree[cur].ch[1],k);
    }
}

int main()
{
    int i;
    scanf("%s%d",ch,&k);
    n=strlen(ch);
    for(i=1;i<=n;i++){
        ary[i]=ch[i-1]-'a';
    }
    init();
    for(i=1;i<=n;i++){
        update(0,i,i,dis[i]);
    }
    safari(0);
    dfs(0,k);
    printf("\n");
    return 0;
}

/*
abbabaab
17
*/

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值