提交时间:2022-07-13 11:53:11

运行 ID: 51570

#include<cstdio> int n,k,type; char s[3005]; int pos[13][3005],npos[13][3005]; int ans; bool used[13]; char ansseq[3005],seq[3005]; inline int comp(char *a,char *b,int len){ for(int i=0;i<len;++i){ if(a[i]>b[i]) return 1; else if(a[i]<b[i]) return -1; } return 0; } inline void dfs(int len,int ch,int now,int rst){ if(rst+len<ans) return; seq[len]=ch+'a'; if(now<pos[ch][0]) dfs(len+1,ch,now+1,rst-1); for(int i=pos[ch][now]+1;i<pos[ch][now+1];++i){ int w=s[i]-'a'; if(npos[w][i]>1&&pos[w][npos[w][i]-1]>pos[ch][now]) continue; if(!used[w]){ used[w]=1; dfs(len+1,w,npos[w][i],rst-pos[ch][0]+now); used[w]=0; } } if(len>ans){ ans=len; if(type) for(int i=0;i<=len;++i) ansseq[i]=seq[i]; } else if(len==ans&&type){ if(comp(ansseq,seq,len)>0) for(int i=0;i<=len;++i) ansseq[i]=seq[i]; } } int main(){ // freopen("seq.in","r",stdin); // freopen("seq.out","w",stdout); scanf("%d%d%d",&n,&k,&type); scanf("%s",s); for(int i=0;i<n;++i){ int w=s[i]-'a'; pos[w][++pos[w][0]]=i; npos[w][i]=pos[w][0]; } for(int i=0;i<k;++i) pos[i][pos[i][0]+1]=n; for(int i=0;i<k;++i){ if(pos[i][0]){ used[i]=1; dfs(0,i,1,n); used[i]=0; } } printf("%d\n",ans+1); if(type) printf("%s\n",ansseq); return 0; }