P3728 曼哈顿序列

· · 题解

前置知识:序列自动机 - OI Wiki。

建立序列自动机,之后 DP,f(i) 表示以 i 处字符开头的本质不同子序列数量。显然有:

f(i)=1+\sum f(\text{next}_{i,c})

过程中对 k 取 \min。

注意到原始的 k 仅计入非空子序列,方便起见可以令 k\gets k+1 转为所有子序列。

最后根据 f(i) 反推出子序列即可。

:::success[曼哈顿序列 - P3728.cpp]

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
int suc[maxn][26],dp[maxn],sta[maxn],n,k;
char str[maxn];
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    cin>>n>>k>>(str+1);
    ++k;
    for(int i=0;i<26;i++) suc[n][i]=n+1;
    for(int i=n-1;i>=0;i--){
        for(int j=0;j<26;j++) suc[i][j]=suc[i+1][j];
        suc[i][str[i+1]-'a']=i+1;
    }
    for(int i=n;i>=0;i--){
        dp[i]=1;
        for(int j=0;j<26;j++){
            dp[i]+=dp[suc[i][j]];
            dp[i]=min(dp[i],k);
        }
    }
    int top=0,p=0,ch;
    while(k>1){
        ch=0,--k;
        while(dp[suc[p][ch]]<k) k-=dp[suc[p][ch++]];
        sta[++top]=ch;
        p=suc[p][ch];
    }
    for(int i=1;i<=top;i++) cout<<char('a'+sta[i]);
    cout<<"\n";
    return 0;
}

:::