1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| #include<bits/stdc++.h> using namespace std; #ifdef LOCAL #define debug(...) fprintf(stdout, ##__VA_ARGS__) #else #define debug(...) void(0) #endif
inline int read(){int x=0,f=1;char ch=getchar(); while(ch<'0'|| ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){ x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}return x*f;} #define Z(x) (x)*(x) #define pb push_back #define fi first #define se second
#define N 1010 #define M 22 int n, m, i, j, k, T; struct PPPP { int a, b, c; }; struct node { int pos, v[M]; void mem() { memset(v, 0, sizeof(v)); pos=0; } node operator +(const PPPP &p) const { node A; A=(*this); A.v[p.a]+=p.b; A.pos=p.c; return A; } void print() { for(int i=0; i<m; ++i) debug("%d ", v[i]); debug("\n"); } }dp[1<<M]; unordered_map<int, node>mp; int g[M][N], pre[N][M], nxt[N][M]; int f[1<<M], s, t, tot; char str[N];
node max(node A, node B) { for(int k=m; k>=1; --k) if(A.v[k]>B.v[k]) return A; else if(B.v[k]>A.v[k]) return B; if(A.pos<B.pos) return A; return B; }
signed main() { #ifdef LOCALd freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif
int c[M]; memset(c, 0, sizeof(c)); n=read(); scanf("%s", str+1); for(i=1; i<=n; ++i) str[i]-='a'; for(i=1, k=0; i<=n; ++i) if(!c[str[i]]) c[str[i]]=++k; m=k; for(i=1; i<=n; ++i) str[i]=c[str[i]]-1; for(i=1; i<=n; ++i) g[str[i]][i]++; for(k=0; k<m; ++k) partial_sum(g[k]+1, g[k]+n+1, g[k]+1); memset(c, 0, sizeof(c)); for(i=n; i>=0; --i) { c[str[i]]=i; memcpy(nxt[i], c, sizeof(c)); } memset(c, 0, sizeof(c)); for(i=1; i<=n+1; ++i) { memcpy(pre[i], c, sizeof(c)); c[str[i]]=i; } f[0]=n+1; for(s=0; s<(1<<m); ++s) { for(k=0; k<m; ++k) if((s>>k)&1) { t=s-(1<<k); if(!pre[f[t]][k]) continue; f[s]=max(f[s], pre[f[t]][k]); }
} dp[0].mem(); for(s=1; s<(1<<m); ++s) { int cnt=__builtin_popcount(s); dp[s].mem(); for(k=0; k<m; ++k) if((s>>k)&1) { int t=s-(1<<k), cs=(1<<m)-1-s; int l=dp[t].pos+1, r=f[cs]-1;
if(r<l) continue; int count=g[k][r]-g[k][l-1], lst=pre[r+1][k]; if(!cnt) continue; dp[s]=max(dp[s], dp[t]+(PPPP){m-cnt+1, count, lst}); }
} auto t=dp[(1<<m)-1]; for(i=m; i>=1; --i) { for(j=1; j<=t.v[i]; ++j) printf("%c", 'a'+i-1); } return 0; }
|