提交时间:2022-07-13 12:30:40

运行 ID: 51671

#include<bits/stdc++.h> #define fst(a,b,c) for(int a=(b);a<=(c);a++) #define pst(a,b,c) for(int a=(b);a>=(c);a--) #define pii pair<int,int> #define mp(x,y) make_pair(x,y) #define fr first #define sc second using namespace std; const int N=3e3+100; int n,K,type,ans; int p[N],f[N][4100][12]; pii rot,pre[N][4100][12]; char s[N]; int read(){ char in=getchar(); int x=0; while(!isdigit(in)) in=getchar(); while(isdigit(in)) x=x*10+(in^48),in=getchar(); return x; } int main(){ n=read(),K=read(),type=read(); scanf("%s",s+1); fst(i,1,n) p[i]=s[i]-'a',f[i][1<<p[i]][p[i]]=1; pst(i,n,2){ fst(s,0,(1<<K)-1){ fst(j,0,K-1){ if(!f[i][s][j]) continue; if(f[i-1][s][j]<f[i][s][j]){ f[i-1][s][j]=f[i][s][j]; pre[i-1][s][j]=mp(s,j); } else if(f[i-1][s][j]==f[i][s][j]&&pre[i-1][s][j].sc>j){ pre[i-1][s][j]=mp(s,j); } if(p[i-1]==j||!((s>>p[i-1])&1)){ if(f[i-1][s|(1<<p[i-1])][p[i-1]]<f[i][s][j]+1){ f[i-1][s|(1<<p[i-1])][p[i-1]]=f[i][s][j]+1; pre[i-1][s|(1<<p[i-1])][p[i-1]]=mp(s,j); } else if(f[i-1][s|(1<<p[i-1])][p[i-1]]==f[i][s][j]+1&&pre[i-1][s|(1<<p[i-1])][p[i-1]].sc>j){ pre[i-1][s|(1<<p[i-1])][p[i-1]]=mp(s,j); } } } } } fst(s,0,(1<<K)-1){ fst(j,0,K-1){ if(ans<f[1][s][j]){ ans=f[1][s][j]; rot=mp(s,j); } else if(ans==f[1][s][j]&&rot.sc>j){ rot=mp(s,j); } } } printf("%d\n",ans); if(type){ fst(i,1,n-1){ if(!rot.fr) break; if(f[i][rot.fr][rot.sc]!=f[i+1][pre[i][rot.fr][rot.sc].fr][pre[i][rot.fr][rot.sc].sc]) printf("%c",s[i]); rot=pre[i][rot.fr][rot.sc]; } if(rot.fr) printf("%c",s[n]); } return 0; }