Problem:
Score : 1600 points

Problem Statement

You are given a string S of length 2N, containing N occurrences of a and N occurrences of b.

You will choose some of the characters in S. Here, for each i = 1,2,...,N, it is not allowed to choose exactly one of the following two: the i-th occurrence of a and the i-th occurrence of b. (That is, you can only choose both or neither.) Then, you will concatenate the chosen characters (without changing the order).

Find the lexicographically largest string that can be obtained in this way.

Constraints

1 \leq N \leq 3000

S is a string of length 2N containing N occurrences of a and N occurrences of b.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the lexicographically largest string that satisfies the condition.

Sample Input 1

3
aababb

Sample Output 1

abab

A subsequence of T obtained from taking the first, third, fourth and sixth characters in S, satisfies the condition.

Sample Input 2

3
bbabaa

Sample Output 2

bbabaa

You can choose all the characters.

Sample Input 3

6
bbbaabbabaaa

Sample Output 3

bbbabaaa

Sample Input 4

9
abbbaababaababbaba

Sample Output 4

bbaababababa

Solution in C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include <bits/stdc++.h>
using namespace std;

int main()
{
  int n;
  scanf("%d",&n);
  static char s[10000];
  scanf("%s",s);
  static int a[3000],b[3000],c[10000];
  int na=0,nb=0;
  for(int i=0;i<2*n;i++){
    if(s[i]=='a'){
      a[na]=i;
      c[i]=na++;
    }
    else{
      b[nb]=i;
      c[i]=nb++;
    }
  }
  vector<int> bg,ed;
  for(int i=0;i<n;){
    if(a[i]>b[i]){
      bg.push_back(i);
      int t=a[i];
      while(b[i]<t){
	t=a[i];
	i++;
      }
      ed.push_back(i);
    }
    else{
      i++;
    }
  }
  string ans;
  for(int t=bg.size()-1;t>=0;t--){
    int x=bg[t],y=ed[t];
    string p="";
    for(int i=x;i<y;i++){
      string q;
      for(int j=0;j<2*n;j++){
	if(c[j]>=i&&c[j]<y){
	  q+=s[j];
	}
      }
      if(p<q){
	p=q;
      }
    }
    if(p+ans>ans){
      ans=p+ans;
    }
  }
  for(int i=n-1;i>=0&&a[i]<b[i];){
    ans+="ab";
    int t=a[i];
    while(i>=0&&b[i]>t)i--;
  }
  printf("%s\n",ans.c_str());
  return 0;
}