提交时间:2022-07-13 11:53:20
运行 ID: 51571
#include<iostream> #include<cstdio> #define inf -114514 #define ll long long using namespace std; int n,k,tp; char st[3005]; int a[3005]; int pc[1<<12]; ll pw[12]; int f[3005][1<<12],lst[3005][1<<12][2]; int g[1<<12],h[12][1<<12]; ll dic[3005][1<<12]; ll mdic,mi,ms,mf; void show(int i,int s){ if(lst[i][s][0]) show(lst[i][s][0],lst[i][s][1]); printf("%c",st[i]); return; } int main(){ scanf("%d%d%d",&n,&k,&tp); scanf("%s",st+1); pw[0]=1; for(int i=1;i<(1<<k);i+=1){ pc[i]=pc[i>>1]+(i&1); } for(int i=1;i<k;i+=1){ pw[i]=12ll*pw[i-1]; } for(int i=1;i<=n;i+=1) a[i]=st[i]-'a'; for(int j=1;j<(1<<k);j+=1) f[0][j]=inf; for(int i=1;i<=n;i+=1){ for(int j=0;j<(1<<k);j+=1) f[i][j]=inf; for(int j=0;j<(1<<k);j+=1){ int id; if((j>>a[i]&1)&&(h[a[i]][j])){ id=h[a[i]][j]; if(f[i][j]<f[id][j]+1){ f[i][j]=f[id][j]+1; lst[i][j][0]=id; lst[i][j][1]=j; dic[i][j]=dic[id][j]; } else if(f[i][j]==f[id][j]+1){ if(dic[i][j]>dic[id][j]){ lst[i][j][0]=id; lst[i][j][1]=j; dic[i][j]=dic[id][j]; } } } else{ id=g[j]; if(f[i][j|(1<<a[i])]<f[id][j]+1){ f[i][j|(1<<a[i])]=f[id][j]+1; lst[i][j|(1<<a[i])][0]=id; lst[i][j|(1<<a[i])][1]=j; dic[i][j|(1<<a[i])]=dic[id][j]+pw[k-pc[j]-1]*a[i]; } else if(f[i][j|(1<<a[i])]==f[id][j]+1){ if(dic[i][j|(1<<a[i])]>dic[id][j]+pw[k-pc[j]-1]*a[i]){ lst[i][j|(1<<a[i])][0]=id; lst[i][j|(1<<a[i])][1]=j; dic[i][j|(1<<a[i])]=dic[id][j]+pw[k-pc[j]-1]*a[i]; } } } } for(int j=0;j<(1<<k);j+=1){ if(f[g[j]][j]<f[i][j]) g[j]=i; else if(f[g[j]][j]==f[i][j]){ if(dic[g[j]][j]>dic[i][j]) g[j]=i; } if(f[h[a[i]][j]][j]<f[i][j]) h[a[i]][j]=i; else if(f[h[a[i]][j]][j]==f[i][j]){ if(dic[h[a[i]][j]][j]>dic[i][j]) h[a[i]][j]=i; } if(f[i][j]>mf){ mf=f[i][j]; mi=i; ms=j; mdic=dic[i][j]; } else if(f[i][j]==mf){ if(dic[i][j]<mdic){ mi=i; ms=j; mdic=dic[i][j]; } } } } printf("%d\n",mf); if(tp) show(mi,ms),printf("\n"); return 0; }