#include "bits/stdc++.h"
using namespace std;
///////////////////////////////////////////
const long long int INF = 1LL<<60;
const long long int Mod = 1000000007;
using ll = long long int; using ci = const int;
using vi = vector<int>;  using Vi = vector<long long int>;
using P = pair<int, int>;  using PLL = pair<ll, ll>;
using matrix = vector<vector<ll>>;
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define all(x) (x).begin(),(x).end()
#define rep(i,N) for(ll i = 0; i < (ll)N; i++)
#define repi(i,a,b) for(ll i = ll(a); i < ll(b); ++i)
template<class T>bool chmax(T &former, const T &b) { if (former<b) { former=b; return true; } return false; }
template<class T>bool chmin(T &former, const T &b) { if (b<former) { former=b; return true; } return false; }
template<class T>T sqar(T x){ return x*x; }//sqrt(x)は平方根;
#define Sort(v) std::sort(v.begin(), v.end(), std::greater<decltype(v[0])>()) //降順でVをソート
#define p_queue(v) priority_queue<v, vector<v>, greater<v> >
template<class T> inline void princ(T x){cout<<x<<" ";};
template<class T> inline void print(T x){cout<<x<<"\n";};
template<class T> inline void Yes(T condition){ if(condition) cout << "Yes" << endl; else cout << "No" << endl; }
template<class T> inline void YES(T condition){ if(condition) cout << "YES" << endl; else cout << "NO" << endl; }
///////////////////////////////////////////////////////////////////////////////////

ll n,m;
Vi a;
ll cal(ll n){
	switch(n){
		case 1:
			return 2;
			break;
		case 2:
		case 3:
		case 5:
			return 5;
			break;
		case 4:
			return 4;
			break;
		case 6:
			return 6;
			break;
		case 7:
			return 3;
			break;
		case 8:
			return 7;
			break;
		case 9:
			return 6;
			break;
		default:
			return 0;
			break;
	}
}

vector<string> dp;

int main(){
	cin.tie(0);ios::sync_with_stdio(false);
	std::cout<<std::fixed<<std::setprecision(30);
	cin>>n>>m;
	a.resize(m);
	rep(i,m){
		cin>>a[i];
	}
	dp.resize(n+10,"-1");
	dp[0]="";
	rep(i,n){
		if(dp[i]=="-1")continue;
		rep(j,a.size()){
			ll tmp = i+cal(a[j]);
			string fig = dp[i]+(char)('0'+a[j]);
			string now = dp[tmp];
			if(now=="-1" || now.size()<fig.size()){
				dp[tmp] = fig;
			}else if(now.size()>fig.size()){

			}else{
				chmax(dp[tmp],fig);
			}
		}
	}
	print(dp[n]);
	return 0;
}

#include<iostream>
#include<iomanip>
#include<algorithm>
#include<bitset>
#include<cstdio>
#include<cmath>
#include<deque>
#include<map>
#include<numeric>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<string>
#include<tuple>
#include<utility>
#include<vector>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector<vector<long long>> vvll;
typedef vector<vector<int>> vvi;

#define rep(i, a, n)  for(int i=a; i<n; i++)
#define REP(i, n)  for(int i=0; i<(int)(n); i++)
#define REPS(i, n)  for(int i=1; i<=(int)(n); i++)
#define PER(i, n) for(int i=(int)(n)-1; i>= 0; i--)
#define PERS(i, n)  for(int i=(int)(n); i>0; i--)
#define FOR(i, c) for(__typeof((c).begin()) i = (c).begin(); i!=(c).end(); i++)
#define RFOR(i, c)  for(__typeof((c).rbegin()) i=(c).rbegin(); i!=(c).end(); i++)
#define ALL(container)  (container).begin(), (container).end()
#define RALL(container) (container).rbegin(), (container).rend()
#define SZ(container) (container).size()
#define FILL0(n)  setfill('0') << right << setw(n)
#define mp(a, b)  make_pair(a, b)
#define toLower(c)  c+0x20
#define toUpper(c)  c-0x20
#define pb  push_back
#define eb  emplace_back

const int INF = 1e9;
const long long LLINF = 1e18;
const ull MOD = 998244353;
const int MSIZE = 100007;
const double Pi = 3.14159265358979323146;

int main(){
  int match[10] = {6,2,5,5,4,5,6,3,7,6};
  int n, m; cin >> n >> m;
  vector<int> num(m), dp(n+100, -INF);
  REP(i, m){
    cin >> num[i];
  }
  dp[0]=0;
  sort(RALL(num));
  string ans = "";
  for(int i=1; i<=n; i++){
    REP(j, m){
      if(i-match[num[j]]<0) continue;
      dp[i] = max(dp[i], dp[i-match[num[j]]]+1);
    }
  }
  //cout << n << ":" << ans << endl;

  while(n>0){
    REP(j, m){
      if(n-match[num[j]]<0) continue;
      if(dp[n-match[num[j]]]==dp[n]-1){
        ans += ('0'+num[j]);
        n-=match[num[j]];
        //cout << n << ":" << ans << endl;
        break;
      }
    }
  }
  cout << ans << endl;
}


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
#define N 100002
using namespace std;
struct node{
	int u,v,w;
}e[200002];
vector<int> id[N];
int head[2000002],ver[2000002],nxt[2000002],edge[2000002],l;
int n,m,i,j,cnt[N],now[N],dis[2000002],num;
bool in[2000002];
int read()
{
	char c=getchar();
	int w=0;
	while(c<'0'||c>'9') c=getchar();
	while(c<='9'&&c>='0'){
		w=w*10+c-'0';
		c=getchar();
	}
	return w;
}
int my_comp(const node &x,const node &y)
{
	return x.w<y.w;
}
void insert(int x,int y,double z)
{
	l++;
	ver[l]=y;
	edge[l]=z;
	nxt[l]=head[x];
	head[x]=l;
}
void SPFA(int s)
{
	queue<int> q;
	memset(dis,0x3f,sizeof(dis));
	q.push(s);
	dis[s]=0;in[s]=1;
	while(!q.empty()){
		int x=q.front();
		q.pop();
		for(int i=head[x];i;i=nxt[i]){
			int y=ver[i];
			if(dis[y]>dis[x]+edge[i]){
				dis[y]=dis[x]+edge[i];
				if(!in[y]){
					in[y]=1;
					q.push(y);
				}
			}
		}
		in[x]=0;
	}
}
int main()
{
	n=read(),m=read();
	for(i=1;i<=m;i++) e[i].u=read(),e[i].v=read(),e[i].w=read();
	sort(e+1,e+m+1,my_comp);
	for(i=1;i<=m;i++){
		int u=e[i].u,v=e[i].v,w=e[i].w;
		if(now[u]!=w) cnt[u]++,now[u]=w,id[u].push_back(++num);
		if(now[v]!=w) cnt[v]++,now[v]=w,id[v].push_back(++num);
		insert(id[u][cnt[u]-1],id[v][cnt[v]-1],0);
		insert(id[v][cnt[v]-1],id[u][cnt[u]-1],0);
	}
	for(i=1;i<=n;i++){
		for(j=0;j<cnt[i];j++){
			insert(num+i,id[i][j],1);
			insert(id[i][j],num+i,1);
		}
	}
	SPFA(num+1);
	if(dis[num+n]==dis[0]) cout<<"-1"<<endl;
	else cout<<dis[num+n]/2<<endl;
	return 0;
}

#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,no-stack-protector,fast-math")
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define IO ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
const int N = 1e5 + 5, M = 4 * N + 5;

int head[N], nxt[M], to[M], typ[M], ne, n;

void init(){
    ne = 0;
    memset(head, -1, n * sizeof head[0]);
}

void addEdge(int f, int t, int ty){
    to[ne] = t;
    typ[ne] = ty;
    nxt[ne] = head[f];
    head[f] = ne++;
}

void addBiEdge(int a, int b, int ty){
    addEdge(a, b, ty);
    addEdge(b, a, ty);
}

struct state{
    int dis;
    set<int> typs;
};

state node[N];

bool inQ[N];

int dij(){
    priority_queue<pair<int, int> , vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.emplace(0, 0);

    for(int i = 0 ; i < n ; ++i)
        node[i].dis = (int)1e9;

    node[0].dis = 0;
    inQ[0] = true;

    int cst, v;

    while(pq.size()){
        auto top = pq.top();
        pq.pop();

        int u = top.second;
        int d = top.first;
        inQ[u] = false;

        if(node[u].dis < d)continue;

        for(int e = head[u] ; ~e ; e = nxt[e]){
            v = to[e];
            cst = (node[u].typs.find(typ[e]) == node[u].typs.end());

            if(node[u].dis + cst < node[v].dis){
                inQ[v] = true;
                node[v] = {node[u].dis + cst, {typ[e]}};
                pq.emplace(node[v].dis, v);
            }

            else if(node[u].dis + cst == node[v].dis){
                if(node[v].typs.find(typ[e]) != node[v].typs.end())continue;
                node[v].typs.emplace(typ[e]);
                if(!inQ[v])
                    pq.emplace(node[v].dis, v), inQ[v] = true;
            }
        }

    }

    if(node[n - 1].dis > n)
        node[n - 1].dis = -1;
    return node[n - 1].dis;
}

int main(){
    IO;
    int m;
    scanf("%d %d", &n, &m);
    init();
    while(m--){
        int u, v, ty;
        scanf("%d %d %d", &u, &v, &ty);
        addBiEdge(--u, --v, ty);
    }
    printf("%d\n", dij());
}


#include <iostream>
using namespace std;
typedef struct {
    int top;
    int S;
    int E;
    int W;
    int N;
    int bottom;
} dice;
void swap4(int *a, int *b, int *c, int *d) {
    int tmp = *a;
    *a = *b;
    *b = *c;
    *c = *d;
    *d = tmp;
}
void roll(dice *dp, char dir) {
    if (dir == 'E') {
        swap4(&(dp->top), &(dp->W), &(dp->bottom), &(dp->E));
    } else if (dir == 'N') {
        swap4(&(dp->top), &(dp->S), &(dp->bottom), &(dp->N));
    } else if (dir == 'S') {
        swap4(&(dp->top), &(dp->N), &(dp->bottom), &(dp->S));
    } else {
        swap4(&(dp->top), &(dp->E), &(dp->bottom), &(dp->W));
    }
}
int main(void){
    dice d;
    dice *dp = &d;
    cin >> dp->top >> dp->S >> dp->E >> dp->W >> dp->N >> dp->bottom;
    string str;
    cin >> str;
    for (int i = 0; i < str.size(); i++) {
        roll(dp, str[i]);
    }
    cout << dp->top << endl;
}

#include <bits/stdc++.h>
using namespace std;
int main(){
    long long n, ans=0, i;
    map<long long, long long> mp;
    cin >> n;
    for(i=0;i<n;i++){
        long long a;
        cin >> a;
        mp[a]++;
    }

    for(auto x : mp){
        if(x.second%2!=0) ans++;
    }

    cout << ans <<endl;
    return 0;
}


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

int main()
{
    int n,x,y;
    scanf("%d%d%d",&n,&x,&y);
    printf("%d",(n+x-1)/x*y);
}

#include <iostream>
using namespace std;

int main(){
  int n,x,t;
  cin>>n>>x>>t;

  int ans = n/x * t;
  ans += (n%x != 0)? t:0;
  cout<<ans<<endl;
  return 0;
}


#include<bits/stdc++.h>
#define lowbit(i) ((i)&(-(i)))
#define lson(i) ((i)<<1)
#define rson(i) ((i)<<1|1)
#define sqr(x) ((x)*(x))
#define fi first
#define se second
#define mp(x,y) make_pair((x),(y))
#define pb push_back
using namespace std;

typedef long long ll;
typedef unsigned long long ul;
typedef pair<int,int> pii;
typedef vector<int> vii;
typedef vector<pii> vpi;
typedef queue<int> qii;

const int inf=0x3f3f3f3f;
const int maxn=100007;

ll n,s;
struct node{
	ll x,p;void init(){scanf("%lld%lld",&x,&p);}
}a[maxn];

pair<ll,ll> solve(ll l,ll r){
	if(a[r].x<s) {
		return mp(-1,s-a[l].x);
  	}else if(a[l].x>s) {
  		return mp(1,a[r].x-s);
    }
  	if(l==r){
		if(a[l].x<s) return mp(-1,s-a[l].x);
		else return mp(1,a[l].x-s);
	}
	if(a[l].p<a[r].p){
		a[r].p+=a[l].p;
		pair<ll,ll> t=solve(l+1,r);
		// cout<<l<<' '<<r<<' '<<a[l].p<<' '<<a[r].p-a[l].p<<' ';
		// cout<<t.fi<<' '<<t.se<<'\n';
		if(t.fi==-1) return mp(-1,t.se+a[l+1].x-a[l].x);
		else return mp(-1,t.se+a[r].x-a[l].x);
	}else{
		a[l].p+=a[r].p;
		pair<ll,ll> t=solve(l,r-1);
		// cout<<l<<' '<<r<<' '<<a[l].p-a[r].p<<' '<<a[r].p<<' ';
		// cout<<t.fi<<' '<<t.se<<'\n';
		if(t.fi==1) return mp(1,t.se+a[r].x-a[r-1].x);
		else return mp(1,t.se+a[r].x-a[l].x);
	}
}

int main(){
// 	freopen("","r",stdin);5
// 	freopen("","w",stdout);
	scanf("%lld%lld",&n,&s);
	for(int i=1;i<=n;i++) a[i].init();
	// for(int i=1;i<=n;i++) cout<<a[i].p<<' ';cout<<'\n';
	printf("%lld\n",solve(1,n).se);
	return 0;
}
/*
3 2
1 3
3 4
4 2
*/

#include <iostream>
using namespace std;
long long p[100001],x[100001],ans=0;
int n,s,l,r;
int main(){
	cin>>n>>s;
	for (int i=1;i<=n;i++)
		cin>>x[i]>>p[i];
	l=1;r=n;
	while (l<=r){
	if (s<=x[l]){
		cout<<x[r]-s+ans;
		return 0;
	}
	else if (s>=x[r]){
		cout<<ans+s-x[l];
		return 0;
	}  //所有住处都在s的一侧，可以直接开过去
	if (p[l]>=p[r]){
		ans+=x[r]-x[l];
		while (l<r&&p[l]>=p[r]) p[l]+=p[r--];
	}
	else{
		ans+=x[r]-x[l];
		while (l<r&&p[l]<p[r]) p[r]+=p[l++];
	}
	}
	return 0;
}


#include <bits/stdc++.h>

using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> Vi;
typedef tuple<int, int, int> T;
#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)
#define REP(i,x) FOR(i,0,x)
#define ALL(c) c.begin(), c.end()
#define DUMP( x ) cerr << #x << " = " << ( x ) << endl

const int dr[4] = {-1, 0, 1, 0};
const int dc[4] = {0, 1, 0, -1};

int mat[110][2], dp[110][110];
const int INF = 1<<29;

int main() {
  // use scanf in CodeForces!
  cin.tie(0);
  ios_base::sync_with_stdio(false);

  int N;
  cin >> N;
  REP(i, N) REP(j, 2) cin >> mat[i][j];
  REP(i, N) REP(j, N) dp[i][j] = INF;
  REP(i, N) dp[i][i] = 0;
  for (int w = 1; w < N; w++) {
    for (int L = 0; L + w < N; L++) {
      int R = L + w;
      for (int i = L; i < R; i++)
	dp[L][R] = min(dp[L][R], dp[L][i] + dp[i+1][R] + mat[L][0] * mat[i][1] * mat[R][1]);
    }
  }
  cout << dp[0][N-1] << endl;
  return 0;
}

#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
#include <climits>

using namespace std;

int main() {
	int i, j, k, to, min, temp_result;
	int n;
	int r[100], c[100];
	int result[100][100];
	cin >> n;
	for (i = 0; i < n; i++) {
		cin >> r[i] >> c[i];
		result[i][i] = 0;
	}

	i = 0;
	j = 1;
	to = n - 2;
	while (j <= n - 1) {
		while (i <= to) {
			//computation of result[i][i+j]
			min = INT_MAX;
			k = i;
			while (k <= i + j - 1) {
				temp_result = c[k] * r[i] * c[i + j] + result[i][k] + result[k + 1][i + j];
				if (temp_result < min) {
					min = temp_result;
				}
				k++;
			}
			result[i][i + j] = min;
			i++;
		}
		i = 0;
		j++;
		to--;
	}
	printf("%d\n", result[0][n - 1]);
}


#include<bits/stdc++.h>
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
#define rep(i,n) for(int i = 0;  i < n ; ++i)
#define REP(i,a,b) for(int i = a ; i <= b ; ++i)
#define filei freopen("input.txt", "r", stdin);
#define fileo freopen("output.txt", "w", stdout);
#define gooi cout<<"Case #"<<i+1<<" :";
#define s(n) scanf("%d",&n)
#define rev(i,n) for(int i = n ; i >= 0 ; --i)
#define REV(i,a,b) for(int i = a ; i >= b ; --i)
#define miN(a,b) (((a)<(b))?(a):(b))
#define sc(n) scanf("%c",&n)
#define tr(c,i) for(typeof((c).begin()) i=(c).begin();i!=(c).end();i++)
#define INF 1000000000
#define pii pair<long long int,long long int>
#define pb(a) push_back(a)
#define F first
#define S second
typedef long long ll;
using namespace std;
void pre(){}
void solve(){
    ll n;cin>>n;
    ll arr[n];
    for(int i=0;i<n;i++){
        cin>>arr[n-i-1];
    }
    string s;cin>>s;
    set<ll,greater<ll>>basis;
    reverse(s.begin(),s.end());
    for(int i=0;i<n;i++){
        for(auto j:basis){
            arr[i]=min(arr[i],arr[i]^j);
        }
        if(arr[i]==0){
            continue;
        }
        if( s[i]=='0' )
            basis.insert(arr[i]);
        if( s[i]=='1' ){
            cout<<1<<"\n";
            return;
        }
    }
    cout<<0<<"\n";
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    pre();
    long long int num = 1;
    cin>>num;
    for(long long int i=0;i<num;i++){
       	solve();
    }
}


#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <cfloat>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <functional>
#include <utility>
#include <numeric>
#include <iterator>

using namespace std;

typedef unsigned int UI;
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int,int> PII;
typedef istringstream ISS;
typedef ostringstream OSS;

#define REP( i, m, n ) for ( int i = (int)( m ); i < (int)( n ); ++i )
#define FOR( v, c ) for ( auto &v : c )

#define EACH( it, c ) for ( auto it = c.begin(); it != c.end(); ++it )
#define ALL( c ) (c).begin(), (c).end()

#define PB( n ) push_back( n )
#define MP( a, b ) make_pair( ( a ), ( b ) )
#define EXIST( c, e ) ( (c).find( e ) != (c).end() )

#define fst first
#define snd second

#define DUMP( x ) cerr << #x << " = " << ( x ) << endl
#define DEBUG( x ) cerr << __FILE__ << ":" << __LINE__ << ": " << #x << " = " << ( x ) << endl

VI solve( int a, int b, int c )
{
	const int N = a + b + c;
	VI parts( N, 2 );

	int m;
	cin >> m;

	VVI nums( m, VI( 3 ) );
	VI rs( m );

	REP( i, 0, m )
	{
		REP( j, 0, 3 )
		{
			cin >> nums[i][j];
			nums[i][j]--;
		}
		cin >> rs[i];

		if ( !rs[i] )
		{
			continue;
		}

		REP( j, 0, 3 )
		{
			parts[ nums[i][j] ] = 1;
		}
	}

	REP( i, 0, m )
	{
		if ( rs[i] )
		{
			continue;
		}

		int count = 0;
		REP( j, 0, 3 )
		{
			count += parts[ nums[i][j] ] == 1;
		}

		if ( count != 2 )
		{
			continue;
		}

		REP( j, 0, 3 )
		{
			if ( parts[ nums[i][j] ] == 1 )
			{
				continue;
			}
			parts[ nums[i][j] ] = 0;
		}
	}

	return parts;
}

int main()
{
	cin.tie( 0 );
	ios::sync_with_stdio( false );

	while ( true )
	{
		int a, b, c;
		cin >> a >> b >> c;

		if ( !( a | b | c ) )
		{
			break;
		}

		VI res( solve( a, b, c ) );
		FOR( r, res )
		{
			cout << r << endl;
		}
	}

	return 0;
}

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

struct parts{int power; int motor; int cable; int pass;};

int main(){
	int a, b, c;
	int N;
	int is_disorder[300];
	parts result[1000];
	for(;;){
		cin >> a >> b >> c;
		if(a == 0 && b == 0 && c == 0) break;
		for(int i = 0; i < a + b + c; i++) is_disorder[i] = 2;
		cin >> N;
		for(int i = 0; i < N; i++){
			cin >> result[i].power >> result[i].motor >> result[i].cable >> result[i].pass;
			result[i].power--; result[i].motor--; result[i].cable--;
			if(result[i].pass == 1){
				is_disorder[result[i].power] = 1;
				is_disorder[result[i].motor] = 1;
				is_disorder[result[i].cable] = 1;
			}
		}
		for(int i = 0; i < N; i++){
			if(result[i].pass == 0){
				if(is_disorder[result[i].power] == 1 && is_disorder[result[i].motor] == 1) is_disorder[result[i].cable] = 0;
				if(is_disorder[result[i].power] == 1 && is_disorder[result[i].cable] == 1) is_disorder[result[i].motor] = 0;
				if(is_disorder[result[i].motor] == 1 && is_disorder[result[i].cable] == 1) is_disorder[result[i].power] = 0;
			}
		}
		for(int i = 0; i < a + b + c; i++){
			cout << is_disorder[i] << endl;
		}
	}
	return 0;
}


#include<set>
#include<queue>
#include<vector>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define inf 0x7fffffff
#define lli long long int
int n,len;
char c[50];

vector<set<pair<int,int> > > trie;
vector<lli> s;

inline int fd(int now,int k){
	if(trie[now].empty()) return 0;
	set<pair<int,int> >::iterator it=trie[now].lower_bound(make_pair(k,0));
	if(it==trie[now].end()) return 0;
	if(it->first!=k) return 0;
	return it->second;
}
inline int upd(){
	set<pair<int,int> > sss;
	sss.clear();
	trie.push_back(sss);
	s.push_back(0);
	return trie.size()-1;
}

int t[50],cnt;
inline void add(){
	int now=0,temp=0;
	for(int i=1;i<=n;i++){
		int pos=t[i],nxt=fd(now,pos);
		if(!nxt) nxt=upd(),trie[now].insert(make_pair(pos,nxt));
		now=nxt;
	}
	s[now]++;
	return;
}
inline unsigned lli query(){
	int now=0;
	for(int i=1;i<=n;i++){
		int pos=t[i],nxt=fd(now,pos);
		if(!nxt) return 0;
		now=nxt;
	}
	return s[now];
}

unsigned lli ans=0;
const lli vl[20]={0,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144};

int main(){
	scanf("%d",&n);
	len=n<<1;
	cin>>c+1;
	upd();
	for(int i=0;i<=vl[n+1]-1;i++){
		cnt=0;
		for(int j=1;j<=n;j++) if((i&vl[j])==vl[j]) t[++cnt]=c[j]-'a';
		for(int j=1;j<=n;j++) if((i&vl[j])==0) t[++cnt]=c[j]-'a'+26;
		add();
	}
	for(int i=0;i<=vl[n+1]-1;i++){
		cnt=0;
		for(int j=1;j<=n;j++) if((i&vl[j])==0) t[++cnt]=c[len-j+1]-'a';
		for(int j=1;j<=n;j++) if((i&vl[j])==vl[j]) t[++cnt]=c[len-j+1]-'a'+26;
		ans+=query();
	}
	cout<<ans<<endl;
	return 0;
}

#include <bits/stdc++.h>

#include <iostream>
//#include <algorithm>
// #include <iomanip>
#define ll long long
#define map unordered_map
#define set unordered_set
#define l_l pair<ll, ll>
#define vll vector<ll>
#define mll map<ll, ll>

using namespace std;

const ll MOD = 1000000007LL;
const ll INF = (1LL << 60LL);

int main() {
  // std::cout << std::fixed << std::setprecision(10);
  ll N;
  scanf("%lld", &N);

  ll ans = -INF;

  for (ll i = N; i <= 999; i++) {
    string s = to_string(i);
    if (s[0] == s[1] && s[1] == s[2]) {
      ans = i;
      break;
    }
  }

  cout << ans << endl;
}


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

int main(){
  int N,X,T;
  cin>>N>>X>>T;
  if(N%X==0) cout<<N/X*T;
  else cout<<(int(N/X)+1)*T<<endl;
}

#include <iostream>
#include <vector>
using namespace std;
const int MOD = 1000000007;
int main(){
	int H, W, K;
	cin >> H >> W >> K;
	vector<vector<int>> dp(H + 1, vector<int>(W, 0));
	dp[0][0] = 1;
	for (int i = 0; i < H; i++){
		for (int j = 0; j < (1 << (W - 1)); j++){
			bool ok = true;
			for (int k = 0; k < W - 2; k++){
				if ((j >> k & 1) && (j >> (k + 1) & 1)){
					ok = false;
				}
			}
			if (ok){
				vector<int> p(W);
				for (int k = 0; k < W; k++){
					p[k] = k;
				}
				for (int k = 0; k < W - 1; k++){
					if (j >> k & 1){
						swap(p[k], p[k + 1]);
					}
				}
				for (int k = 0; k < W; k++){
					dp[i + 1][p[k]] += dp[i][k];
					dp[i + 1][p[k]] %= MOD;
				}
			}
		}
	}
	cout << dp[H][K - 1] << endl;
}


#include <iostream>
#include<cmath>
#include<vector>
using namespace std;
#define ll long long
#define ld long double

int main(void){
string s;
cin>>s;
string ans="2018";
ans+=s.substr(4);
cout<<ans;
}

// B - Around Square
#include <bits/stdc++.h>
using namespace std;

int main(){
	int N; cin>>N;
	int64_t ans = 0;
	for(int i=1; i*i<=N; ++i) ans = i*i;
	cout<<ans<<endl;
}


#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cmath>
#include <stdio.h>
#include <queue>
#include <deque>
#include <cstdio>
#include <set>
#include <map>
#include <bitset>
#include <stack>
#include <cctype>
using namespace std;
vector<vector<int>> vec(100010);
int co[100010] = { 0 };
int main() {
	int n, m;
	cin >> n >> m;
	for (int i = 0; i < n - 1 + m; i++) {
		int a, b;
		cin >> a >> b;
		co[b]++;
		vec[a].emplace_back(b);
	}
	queue<int>que;
	for (int i = 1; i <= n; i++) {
		if (co[i]==0) {
			que.push(i);
			break;
		}
	}
	int ans[100010] = { 0 };
	while (!que.empty()) {
		int k = que.front();
		for (int l = 0; l < vec[k].size(); l++) {
			co[vec[k][l]]--;
			if (co[vec[k][l]] == 0) {
				que.push(vec[k][l]);
			}
			ans[vec[k][l]] = k;
		}
		que.pop();
	}
	for (int i = 1; i <= n; i++) {
		cout << ans[i] << endl;
	}
	return 0;
}

#include <iostream>
#include <algorithm>
using namespace std;

int straight(int card[])
{
	for(int i=1; i<9; i++){
		if(((card[0]==i)&&(card[1]==i+1)&&(card[2]==i+2)&&(card[3]==i+3)&&(card[4]==i+4)) ||
			(card[0]==1&&card[1]==10&&card[2]==11&&card[3]==12&&card[4]==13))
			return 1;
	}
	return 0;
}

int main(){
	int c[5], n;
	char k;

	while(1){
		cin>>c[0]>>k>>c[1]>>k>>c[2]>>k>>c[3]>>k>>c[4];
		if(cin.eof())break;
		n=0;
		sort(c, c+5);

		for(int i=0; i<4; i++){
			for(int j=i+1; j<5; j++){
				if(c[i]==c[j])
					n++;
			}
		}
		switch(n){
			case 1:
				cout<<"one pair\n";
				break;
			case 2:
				cout<<"two pair\n";
				break;
			case 3:
				cout<<"three card\n";
				break;
			case 4:
				cout<<"full house\n";
				break;
			case 6:
				cout<<"four card\n";
				break;
			case 10:
				cout<<"four card\n";
				break;
			default:
				if(straight(c))
					cout<<"straight\n";
				else
					cout<<"null\n";
				break;
		}
	}

	return 0;
}


#include <iostream>
#include <vector>
using namespace std;

int main(){
  int n, q;
  while(true){
    cin >> n >> q;
    if(n == 0)
      break;

    int m;
    vector< vector<int> > sch(n, vector<int>(101, 0));
    for(int i=0; i<n; i++){
      cin >> m;
      for(int j=0; j<m; j++){
        int temp;
        cin >> temp;
        sch[i][temp] = 1;
      }
    }

    int ans, nmax = 0;
    for(int i=0; i<101; i++){
      int sum = 0;
      for(int j=0; j<n; j++){
        sum += sch[j][i];
          }
      if(sum > nmax){
        ans = i;
        nmax = sum;
      }
    }

    if(nmax < q)
      ans = 0;
    cout << ans << endl;
  }

  return 0;
}

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

int main() {
	int n, q;
	while(cin >> n  >> q && (n || q)){
		int cnt[1000] = {0}, m, d;
		for(int i = 0; i < n; ++i){
			cin >> m;
			for(int j = 0; j < m; ++j){
				cin >> d;
				cnt[d]++;
			}
		}
		int maxium = 0, day = 0;
		for(int i = 1; i <= 100; ++i){
			if(maxium < cnt[i]){
				day = i;
				maxium = cnt[i];
			}
		}
		if(maxium >= q)
			cout << day << endl;
		else
			cout << "0" << endl;
	}
	return 0;
}


#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<utility>
#include<tuple>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>

using namespace std;

using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

#define BIL ((ll)1e9)
#define MOD ((ll)1e9+7)
#define INF (1LL<<60)           //1LL<<63でオーバーフロー
#define inf (1<<29)             //1<<29でオーバーフロー

int main(int argc,char* argv[]){
    int n;
    ll x;
    cin >> n >> x;

    vector<ll> a(n);
    for(auto &x:a)cin >> x;

    sort(a.begin(),a.end());

    if(a[0]>x){
        cout << 0 << endl;
        return 0;
    }

    vector<ll> asum(n);
    asum[0]=a[0];
    int ans=-1;
    for(int i=1;i<a.size();i++){
        asum[i]=asum[i-1]+a[i];
        if(asum[i]==x){
            ans=i+1;
            break;
        }else if(asum[i]>x){
            ans=i;
            break;
        }
    }

    if(ans==-1){
        ans=n-1;
    }

    cout << ans << endl;

    return 0;
}

#include <bits/stdc++.h>
#define ll long long
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
#define rrep(i, n) for (int i = 1; i <= n; i++)
ll gcd(ll a, ll b) { return b ? gcd(b, a%b) : a; }
ll lcm(ll a, ll b) { return (a * b) / gcd(a,b); }
using P = pair <int, int>;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

ll MOD = 1000000007;
ll INF =1<<30;

int main(){
   int n,x;
   cin >> n >>x;
   vector<int>a(n);
   rep(i,n)cin >> a[i];
   sort(a.begin(),a.end());
   int cnt=0;
   rep(i,n-1){
       if(x<a[i]) break;
       x-=a[i];
       cnt++;
   }
   if(a[n-1]==x) cnt++;
   cout << cnt <<endl;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=3e5+5;
const ll mod=1e9+7;
ll power(ll a,ll b){return b?power(a*a%mod,b/2)*(b%2?a:1)%mod:1;}
ll n,ans=0,mx=0,a[N],num[100]={0},cnt[100]={0};
void split(ll x){
    ll p=0;
    while(x){
        if(x%2) cnt[p]++;
        p++;
        x/=2;
    }
    mx=max(mx,p);
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i],split(a[i]);
    for(int i=1;i<=n;i++){
        for(ll j=0;j<mx;j++){
            if(a[i]&(1LL<<j)) num[j]+=n-cnt[j];
            else num[j]+=cnt[j];
        }
    }
    for(ll i=0;i<100;i++){
        num[i+1]+=num[i]/2;
        if(num[i]%2) ans=(ans+power(2,i))%mod;
    }
    cout<<ans*power(2,mod-2)%mod;
    return 0;
}

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef tree <int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> Set;

const int RLEN=1<<18|1;
inline char nc() {
    static char ibuf[RLEN],*ib,*ob;
    (ib==ob) && (ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
    return (ib==ob) ? -1 : *ib++;
}
inline int rd() {
    char ch=nc(); int i=0,f=1;
    while(!isdigit(ch)) {if(ch=='-')f=-1; ch=nc();}
    while(isdigit(ch)) {i=(i<<1)+(i<<3)+ch-'0'; ch=nc();}
    return i*f;
}

const int N=3e5+50;
int n,a[N][3],inv0,inv1,flip0,flip1;
int p0[N],p1[N];
inline void calc(int &inv,int *p,int nn) {
    Set S;
    static int pos[N];
    for(int i=1;i<=nn;i++) pos[p[i]]=i;
    for(int i=1;i<=nn;i++) S.insert(i);
    for(int i=1;i<=nn;i++) {
        inv+=S.order_of_key(pos[i]+1)-1;
        inv%=2; S.erase(pos[i]);
    } return;
}
int main() {
    n=rd();
    for(int j=0;j<3;j++) for(int i=1;i<=n;i++) a[i][j]=rd()-1;
    for(int i=1;i<=n;i+=2) {
      //  cerr<<i<<'\n';
        if(a[i][0]/6!=a[i][1]/6 || a[i][0]/6!=a[i][2]/6) {puts("No"); return 0;}
        else if(a[i][1]%6!=1) {puts("No"); return 0;}
        else if(a[i][0]%6+a[i][2]%6!=2) {puts("No"); return 0;}
        if(a[i][0]%6) ++flip1;
        p1[(i+1)/2]=a[i][0]/6+1;
    }
    for(int i=2;i<=n;i+=2) {
        if(a[i][0]/6!=a[i][1]/6 || a[i][0]/6!=a[i][2]/6) {puts("No"); return 0;}
        else if(a[i][1]%6!=4) {puts("No"); return 0;}
        if(a[i][0]%6==5) ++flip0;
        p0[i/2]=a[i][0]/6+1;
    }
    calc(inv0,p0,n/2); calc(inv1,p1,(n+1)/2);
    if((inv0^flip1)&1) {puts("No"); return 0;}
    if((inv1^flip0)&1) {puts("No"); return 0;}
    puts("Yes"); return 0;
}


#include <iostream>
using namespace std;
int main(){
    int a, b, c, d, e, f;
    cin >> a >> b >> c >> d >> e >> f;
    if(e - a > f){
        cout << ":(" << endl;
        return 0;
    }
    cout << "Yay!" << endl;
}

#include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using vii = vector<vi>;
using vs = vector<string>;
using in6 = int64_t;
using ind = double;
using pii = pair<int,int>;
using psi = pair<string,int>;
using vpi = vector<pii>;
using vps = vector<psi>;
#define rep(i, n) for (in6 i = 0; i < (in6)(n); i++)
#define repa(i,a,n) for(in6 i = a; i < (in6)(n); i++)
#define repdown(i,n) for(in6 i = n; i > 0; i--)
#define kyun ios::sync_with_stdio(false)
#define hinata cout << "\n"
#define all(c) (c).begin(), (c).end()
#define pb push_back
#define inf 2147483647

int main() {
  kyun;
  int a,b,c;
  cin >> a >> b >> c;
  if(a < c && c < b) cout << "Yes";
  else if(b < c && c < a) cout << "Yes";
  else cout << "No";
  hinata;
}


#include <cstdio>
#include <iostream>
#include <string>

using namespace std;

const int COUNT = 6;

#define size_array(x) ((sizeof(x)) / (sizeof(x[0])

class Dice
{
private:
	int num[6];

public:
	Dice();
	void play_dice(string);
	void play(int, int, int, int);
	void print_() {printf("%d\n", num[0]);}
};

Dice::Dice()
{
	for (int i = 0; i < COUNT; ++i)
	{
		cin >> num[i];

	}
}

void Dice::play_dice(string s)
{
	if(s == "E") {play(0, 2, 5, 3); }

	if(s == "N") {play(0, 4, 5, 1); }

	if(s == "S") {play(0, 1, 5, 4); }

	if(s == "W") {play(0, 3, 5, 2); }
}

void Dice::play(int a, int b, int c, int d)
{
	int temp;
	temp = num[d]; num[d] = num[c]; num[c] = num[b]; num[b] = num[a]; num[a] = temp;
}

int main(int argc, char const *argv[])
{
	Dice c;
	string cmd;
	cin >> cmd;
	for (int i = 0; i < (int)cmd.size(); ++i)
	{
		c.play_dice(cmd.substr(i, 1));
	}
	c.print_();
	return 0;
}

#include <iostream>
#include <bits/stdc++.h>
#include <string>
#include <ctype.h>
#include <algorithm>
#include <cmath>

#define REP(i, n) for(int i=0;i<(int)(n);i++)
#define ALL(x) (x).begin(),(x).end()
#define square(x) (x) * (x)
#define cube(x) (x) * (x) * (x)

const int INF = 1e9;

using namespace std;

class dice{
    private:
    int s[6];
    int top;
    int bottom;
    int r_side;
    int l_side;
    int face;
    int rev;

    public:
    dice(){
        top = 0;
        bottom = 5;
        r_side = 2;
        l_side = 3;
        face = 1;
        rev = 4;
        s[0] = 1;
        s[1] = 2;
        s[2] = 3;
        s[3] = 4;
        s[4] = 5;
        s[5] = 6;
    }

    dice(int a[5]){
        top = 0;
        bottom = 5;
        r_side = 2;
        l_side = 3;
        face = 1;
        rev = 4;
        REP(i, 6) s[i] = a[i];
    }

    dice(int x, int y, int z, int u, int v, int w){
        top = 0;
        bottom = 5;
        r_side = 2;
        l_side = 3;
        face = 1;
        rev = 4;
        s[0] = x;
        s[1] = y;
        s[2] = z;
        s[3] = u;
        s[4] = v;
        s[5] = w;
    }

    int get_top() {
        return s[top];
    }

    int get_bottom(){
        return s[bottom];
    }

    int get_r_side(){
        return s[r_side];
    }

    int get_l_side(){
        return s[l_side];
    }

    int get_face(){
        return s[face];
    }

    int get_rev(){
        return s[rev];
    }

    int set_top(int i) {
        top = i;
        bottom = 5 - top;
        r_side = (i+1)%5;
        l_side = 5 - r_side;
        face = (i+2)%5;
        rev = 5 - face;
        return s[top];
    }

    int rotate_r(int i) {
        while(i<0)
            i+=4;
        i %= 4;
        REP(j, i){
            int temp = face;
            face = r_side;
            r_side = rev;
            rev = l_side;
            l_side = temp;
        }
        return s[top];
    }

    int roll_r(int i) {
        while(i<0)
            i+=4;
        i %= 4;
        REP(j, i){
            int temp = top;
            top = l_side;
            l_side = bottom;
            bottom = r_side;
            r_side = temp;
        }
        return s[top];
    }

    int roll_f(int i){
        while(i<0)
            i+=4;
        i %= 4;
        REP(j, i){
            int temp = top;
            top = face;
            face = bottom;
            bottom = rev;
            rev = temp;
        }
        return s[top];
    }

};

int main() {
    int in[6];
    REP(i, 6) cin >> in[i];
    dice d = dice(in);
    string roll;
    cin >> roll;
    while(roll.size() != 0){
        string order = roll.substr(0, 1);
        if(order == "E")
            d.roll_r(1);
        else if(order == "S")
            d.roll_f(-1);
        else if(order == "N")
            d.roll_f(1);
        else if(order == "W")
            d.roll_r(-1);
        roll = roll.substr(1);
    }
    cout << d.get_top() << endl;
    return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <unordered_map>
typedef long long ll;
using namespace std;
const int mod=1e9+7;
const ll inf=(1e14);

ll solve(){
	ll n,ans=0;
	string s;
	cin>>n>>s;
	int r[n],g[n],b[n];
	g[n-1]=r[n-1]=b[n-1]=r[0]=g[0]=b[0]=0;
	unordered_map<char,int*> m;
	m['R']=r,m['G']=g,m['B']=b;
	for(const char c:{'R','G','B'}){
		for(int i=n-2;i>=0;i--) m[c][i]=m[c][i+1]+(s[i+1]==c);
	}
	for(int i=0;i<n;i++){
		for(int j=i+1;j<n;j++){
			for(const char c:{'R','G','B'}){
				if(s[i]!=c && s[j]!=c && s[i]!=s[j]){
					ans+=(m[c][j]);
					if(j+(j-i) < n && s[j+(j-i)] == c) ans--;
				}
			}
		}
	}
	return ans;
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
#endif
    int t=1;
    //cin>>t;
    while(t--) cout<<solve()<<'\n';
    //while(t--) solve(),cout<<'\n';
    return 0;
}


#include <bits/stdc++.h>

#define rep(i, n) for (int i = 0; i < (n); ++i)
#define all(obj) (obj).begin(), (obj).end()
#define bit(n) (1LL << (n))

using namespace std;

typedef long long ll;

template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  string A;
  string B;
  string C;

  rep(i,3) {
    string s; cin>>s;

    if (i==0) A=s;
    if (i==1) B=s;
    if (i==2) C=s;
  }

  char next = 'a';

  while(true) {
    if(next == 'a') {
      if (A.length() == 0) {
        cout<<"A";
        return 0;
      }
      next = A[0];
      A.erase(0,1);
    } else if(next == 'b') {
      if (B.length() == 0) {
        cout<<"B";
        return 0;
      }
      next = B[0];
      B.erase(0,1);
    } else if(next == 'c') {
      if (C.length() == 0) {
        cout<<"C";
        return 0;
      }
      next = C[0];
      C.erase(0,1);
    }
  }

  return 0;
}

#include<iostream>
#include<cstdio>
#include<cmath>

using namespace std;

int main() {
    double a, b, c, d, x, y, ans;
    cin >> a >> b >> c >> d;
    x = a - c;
    y = b - d;
    ans = sqrt(x*x + y*y);
    printf("%f", ans);
    return 0;
}


/*

Code for problem D by cookiedoth
Generated 22 Mar 2020 at 06.57 PM

   ,##.                   ,==.
 ,#    #.                 \ o ',
#        #     _     _     \    \
#        #    (_)   (_)    /    ;
 `#    #'                 /   .'
   `##'                   "=="

=_=
>_<
o_O

*/

#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <map>
#include <bitset>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <functional>
#include <unordered_set>
#include <unordered_map>
#include <string>
#include <queue>
#include <deque>
#include <stack>
#include <complex>
#include <cassert>
#include <random>
#include <cstring>
#include <numeric>
#define ll long long
#define ld long double
#define null NULL
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define debug(a) cerr << #a << " = " << a << endl
#define forn(i, n) for (int i = 0; i < n; ++i)
#define sz(a) (int)a.size()

using namespace std;

template<class T> int chkmax(T &a, T b) {
	if (b > a) {
		a = b;
		return 1;
	}
	return 0;
}

template<class T> int chkmin(T &a, T b) {
	if (b < a) {
		a = b;
		return 1;
	}
	return 0;
}

template<class iterator> void output(iterator begin, iterator end, ostream& out = cerr) {
	while (begin != end) {
		out << (*begin) << " ";
		begin++;
	}
	out << endl;
}

template<class T> void output(T x, ostream& out = cerr) {
	output(x.begin(), x.end(), out);
}

void fast_io() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
}

int MOD;

int mul(int a, int b) {
	return (1LL * a * b) % MOD;
}

void add(int &a, int b) {
	a = (a + b) % MOD;
}

int power(int a, int deg) {
	int res = 1;
	while (deg) {
		if (deg & 1) {
			res = mul(res, a);
		}
		a = mul(a, a);
		deg >>= 1;
	}
	return res;
}

int inverse(int a) {
	return power(a, MOD - 2);
}

const int mx = 6010;
int n, dp[mx][2 * mx], inv[2 * mx], dim2_zero;

signed main() {
	fast_io();
	vector<int> delta = {0, 1, -1, 0};
	cin >> n >> MOD;
	dim2_zero = 3 * n;
	inv[1] = 1;
	for (int i = 2; i <= 3 * n; ++i) {
		inv[i] = mul(MOD - MOD / i, inv[MOD % i]);
	}
	dp[0][dim2_zero] = 1;
	for (int s = 0; s < 3 * n; ++s) {
		for (int d = 0; d <= 2 * dim2_zero; ++d) {
			for (int bl = 1; bl <= 3; ++bl) {
				int s1 = s + bl;
				int d1 = d + delta[bl];
				if (s1 <= 3 * n && d1 >= 0 && d1 <= 2 * dim2_zero) {
					add(dp[s1][d1], mul(dp[s][d], inv[s1]));
				}
			}
		}
	}
	int ans = 0;
	for (int bal = dim2_zero; bal <= 2 * dim2_zero; ++bal) {
		add(ans, dp[3 * n][bal]);
	}
	for (int i = 1; i <= 3 * n; ++i) {
		ans = mul(ans, i);
	}
	cout << ans << endl;
}

#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0; i<n; i++)
#define REP(i,m,n) for(ll i=(ll)(m);i<(ll)(n);i++)
#define fi first
#define se second
long long mo = 1000000007;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> Pii;
typedef pair<ll,ll> Pll;
typedef pair<ll,Pll> PlP;
template<class T, class S> void cmin(T &a, const S &b) { if (a > b)a = b; }
template<class T, class S> void cmax(T &a, const S &b) { if (a < b)a = b; }
template<class A>void PR(A a,ll n){rep(i,n){if(i)cout<<' ';cout<<a[i];}cout << "\n";}
ld PI=3.14159265358979323846;

int main(){
	#ifndef ONLINE_JUDGE
        // for getting input from input.txt
        freopen("input.txt", "r", stdin);
        // for writing output to output.txt
        freopen("output.txt", "w", stdout);
    #endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll N,T;
    cin >> N >> T;
    vector<ll> A(N), B(N), C(N+1);
    rep(i,N){
        cin >> A[i] >> B[i];
    }
    vector<vector<ll>> dp(N+1, vector<ll>(T+1)), dp2(N+1, vector<ll>(T+1));
    rep(i,N){
        rep(j,T){
            if(j+A[i] <= T){
                dp[i+1][j+A[i]]=max(dp[i+1][j+A[i]], dp[i][j]+B[i]);
            }
            dp[i+1][j+1]=max(dp[i+1][j+1], dp[i+1][j]);
            dp[i+1][j+1]=max(dp[i+1][j+1], dp[i][j+1]);
        }
    }
    for(ll i=N;i>0;i--){
        rep(j,T){
            if(j+A[i-1] <= T){
            	dp2[i-1][j+A[i-1]]=max(dp2[i-1][j+A[i-1]], dp2[i][j]+B[i-1]);
            }
            dp2[i-1][j+1]=max({dp2[i-1][j+1], dp2[i][j+1], dp2[i-1][j]});
        }
    }
    ll ans = 0;
    REP(i,0,N){
        rep(j,T){
            cmax(ans, dp[i][j] + B[i] + dp2[i+1][T-1-j]);
        }
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>
#define fi first
#define se second
#define mp make_pair
using namespace std;

typedef pair <int, int> pii;

char buf[1000010];

bool cmp(pii a, pii b) {
	return max(-a.se, -a.fi - b.se) < max(-b.se, -b.fi - a.se);
}

int main () {
	int n; scanf("%d", &n);
	int tot = 0;
	vector <pii> p, q;
	for (int i = 0; i < n; i++) {
		scanf("%s", buf);
		int len = strlen(buf);
		int sum = 0, minj = 0;
		for (int i = 0; i < len; i++) {
			sum += buf[i] == '(' ? 1 : -1;
			minj = min(minj, sum);
		}
		tot += sum;
		if (sum >= 0) p.push_back(mp(minj, sum));
		else q.push_back(mp(sum, minj));
	}
	if (tot != 0) {
		printf("No\n");
		return 0;
	}
	sort(p.begin(), p.end());
	int sum = 0;
	while (p.size() && p.back().fi + sum >= 0) {
		sum += p.back().se;
		p.pop_back();
	}
	if (p.size()) {
		printf("No\n");
		return 0;
	}
	sort(q.begin(), q.end(), cmp);
	for (int i = 0; i < q.size(); i++) {
		if (sum + q[i].se < 0) {
			printf("No\n");
			return 0;
		}
		sum += q[i].fi;
	}
	printf("Yes\n");
	return 0;
}

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

using ll = long long;
using vi = vector<int>;
using vll = vector<long long>;

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

constexpr long long mod = 1000000007;

#define rep(i, n) for (int i = 0; i < n; i++)

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    ll n;
    cin >> n;

    string s;

    while (n!=0) {
        n -= 1;

        ll k = n % 26;

        s += 'a' + k;

        n /= 26;
    }
    reverse(s.begin(), s.end());
    cout << s << endl;
}


#include <iostream>
#include <string>
#include <math.h>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
  int N;
  cin>>N;
  int A[200000],B[200000];
  for(int i=0;i<N;i++) cin>>A[i];
  for(int i=0;i<N;i++) cin>>B[i];
  sort(B,B+N,greater<int>());
  vector<int> same;
  for(int i=0;i<N;i++){
    if(A[i]==B[i]) same.push_back(i);
  }
  int j=0;
  int judge=0;
  for(int i=0;i<same.size();i++){
    while(A[same[i]]==B[same[i]]){
      if(j==N){
        judge++; break;
      }
      if(A[j]!=B[same[i]]&&B[j]!=B[same[i]]) swap(B[same[i]],B[j]);
      j++;
    }
    if(judge==1) break;
  }
  if(judge==0){
    cout<<"Yes"<<endl;
    for(int i=0;i<N-1;i++) cout<<B[i]<<' ';
    cout<<B[N-1]<<endl;
  }
  else cout<<"No"<<endl;

  return 0;
}

#include <iostream>
#include <algorithm>
#include <utility>
#include <vector>
#include <string>
#include <map>

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define REP(i, n) for (int i = 0; i < (n); i++)
#define RREP(i, n) for (int i = (n) - 1; i >= 0; i--)
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define RFOR(i, a, b) for (int i = (a); i > (b); i--)
#define ALL(a) (a).begin(), (a).end()

int main() {
    int N, A[200000], B[200000];
    cin >> N;
    map<int, int> mii;
    REP(i, N) {
        cin >> A[i];
        mii[A[i]]++;
    }
    REP(i, N) {
        cin >> B[i];
        mii[B[i]]++;
    }
    for (auto p : mii) {
        if (p.second > N) {
            cout << "No" << endl;
            return 0;
        }
    }

    int C[200001] = {}, D[200001] = {};
    REP(i, N) {
        C[A[i]]++;
        D[B[i]]++;
    }
    REP(i, N) {
        C[i + 1] += C[i];
        D[i + 1] += D[i];
    }

    int offset = 0;
    REP(i, N) {
        offset = max(D[i + 1] - C[i], offset);
    }
    cout << "Yes" << endl;
    REP(i, N) {
        cout << B[(i + offset) % N] << " ";
    }
    cout << endl;
}


#include <bits/stdc++.h>
#define ALL(v) v.begin(), v.end()
#define MOD 1000000007
#define MAX 510000
#define rrep(i, n) for(ll i = 0; i < (ll)(n); i++)
#define rep(i, n) for(ll i = 1; i <= (ll)(n); i++)
#define dcout cout<<fixed<<setprecision(15);

using namespace std;
typedef long long int  ll;
typedef pair<int, int> P;

//lcm//
ll gcd(ll x, ll y) {
	if (x == 0) return y;
	return gcd(y%x, x);
}
ll lcm(ll x, ll y) { return x * y / gcd(x, y); }

//a^n mod p//
ll modpow(ll a, ll n, ll p) {
  if (n == 1) return a % p;
  if (n % 2 == 1) return (a * modpow(a, n - 1, p)) % p;
  ll t = modpow(a, n / 2, p);
  return (t * t) % p;
}

//inversemod//
long long modinv(long long a, long long m) {
	long long b = m, u = 1, v = 0;
	while (b) {
		long long t = a / b;
		a -= t * b; swap(a, b);
		u -= t * v; swap(u, v);
	}
	u %= m;
	if (u < 0) u += m;
	return u;
}

//Cmonp//
ll fac[MAX], finv[MAX], inv[MAX];
//
void COMinit() {
	fac[0] = fac[1] = 1;
	finv[0] = finv[1] = 1;
	inv[1] = 1;
	for (int i = 2; i < MAX; i++) {
		fac[i] = fac[i - 1] * i % MOD;
		inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
		finv[i] = finv[i - 1] * inv[i] % MOD;
	}
}

//
ll COM(ll n, ll k) {
	if (n < k) return 0;
	if (n < 0 || k < 0) return 0;
	return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

//LARGE n
ll com(ll n,ll m){
    if(n<m || n<=0 ||m<0){
		return 0;
	}
	if( m==0 || n==m){
		return 1;
	}
	ll k=1;
	for(ll i=1;i<=m;i++){
       k*=(n-i+1);
	   k%=MOD;
	   k*=modinv(i,MOD);
	   k%=MOD;
	}
	return k;
}

////////////////////////////////////////////////////////////////////

ll rad(ll u, ll p){
ll cnt=0;
	while(u%p==0){
		u/=p;
		cnt++;
	}
	return cnt;
}

int main() {
int n;
cin>>n;

string st;

cout<<0<<endl;
cout<<flush;
cin>>st;
if(st=="Vacant"){
	return 0;
}

int pre=0;
int small=0;
int large=n;
rep(z,19){
	string u;
	int mid=(small+large)/2;
	cout<<mid<<endl;
	cout<<flush;

	cin>>u;
	if(u=="Vacant"){
		return 0;
	}
	if(pre>mid){
		if((pre-mid)%2==0 && u!=st){small=mid;}
		if((pre-mid)%2==0 && u==st){large=mid;}
		if((pre-mid)%2==1 && u!=st){large=mid;}
		if((pre-mid)%2==1 && u==st){small=mid;}
	}
	if(pre<mid){
		if((mid-pre)%2==0 && u!=st){large=mid;}
		if((mid-pre)%2==0 && u==st){small=mid;}
		if((mid-pre)%2==1 && u!=st){small=mid;}
		if((mid-pre)%2==1 && u==st){large=mid;}
	}
	st=u;
	pre=mid;
	}

return 0;

}

#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef vector<pair<int, int> > vpii;
typedef pair<int, int> pii;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<double, double> pdd;
typedef vector<ll> vll;
#define INF 0x3f3f3f3f
#define MOD 1000000007LL
#define EPSILON 0.00001
#define f first
#define s second
#define pb push_back
#define mp make_pair

#define FOR(i, a, b) for (ll i=(a); i<=(signed)(b); i++)
#define F0R(i, a) for (ll i=0; i<(signed)(a); i++)
#define RFOR(i, a, b) for (ll i=(a); i >= b; i--)

#define MN 200005
int n;
string s;
bool op[MN];

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    cin >> n >> s;
    F0R(i, 2*n){
        if(s[i] == 'B'){
            op[i] = (i+1)%2;
        } else{
            op[i] = i%2;
        }
        //cout << op[i] << " ";
    }
    //cout << "\n";
    ll amt = 1;
    int cnt = 0;
    F0R(i, 2*n){
        if(op[i]) ++cnt;
        else{
            amt = (amt*cnt)%MOD;
            --cnt;
        }
        if(cnt < 0){
            cout << "0\n";
            return 0;
        }
    }
    if(cnt != 0){
        cout << "0\n";
        return 0;
    }
    FOR(i, 1, n) amt = (amt*i)%MOD;
    cout << amt << "\n";

    return 0;
}


#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <stack>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;

int main(){
	vector<int> v(5000);
	int n , sum=0 , max=-2000000000;
	while(cin>>n,n){
		sum=0;
		max=-2000000000;
		for(int i=0;i<n;++i){
			cin >> v[i];
		}
		for(int i=n;i>=0;--i){
			for(int j=i;j<n;++j){
			sum+=v[j];
			if(sum>max) max=sum;
			}
			sum=0;
		}
		cout << max << endl;
	}
	return 0;
}

#include <iostream>
#include <climits>
#include <set>
#include <string>
#include <algorithm>
#include <vector>
#define MAX 1000000001

using namespace std;
#define ll long long
#define dbg if(0)

int main(){
    while(true){
        int n;
        ll ans= LLONG_MIN;
        cin>>n;
        if (n==0)break;

        ll rui[n+1];
        rui[0]=0;
        ll lowmax=LLONG_MIN;
        for(int i=1;i<=n;i++){
            cin >>rui[i];
            if(rui[i]<=0)lowmax=max(lowmax,rui[i]);
            rui[i]+=rui[i-1];
            dbg cout <<rui[i]<<" ";
        }
        dbg cout <<endl;
        //次を見る
        //今までの最小値を更新したか？
        //したなら暫定解を確定しansと比較。最大値=最小値=発見した最小値にする
        //してなければ最大値の更新をする
        //見る場所が一番後ろまで行ったら終了。
        rui[0]=min(rui[0],rui[1]);
        ll nmin=rui[0],nmax=rui[0];
        bool nmflag=false;
/*        for(int i=1;i<=n;i++){
            for(int j=i;j<=n;j++){
                ans=max(rui[j]-rui[i-1],ans);
            }
        }*/
        for(int i=0;i<=n;i++){
            if (rui[i]<nmin){
                ans=max(nmax-nmin,ans);
                nmax=rui[i];
                nmin=rui[i];
            }else{
                if(rui[i]>nmax){
                    nmax=rui[i];
                    nmflag=true;
                }
            }
            dbg cout <<nmax<<" "<<nmin<<" "<<endl;
        }
        ans=max(nmax-nmin,ans);
        dbg cout << endl;
        if(nmflag)cout<<ans<<endl;
        else cout<<lowmax<<endl;
        //cout <<ans<<endl;
    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define fori(x,y)   for(ll i=x;i<y;i++)
#define forj(x,y)   for(ll j=x;j<y;j++)
#define rfori(a,b)   for(int i=a;i>=b;i--)
#define for_it(a)     for(auto it: a)
#define pb          push_back
#define pf          push_front
#define ff          first
#define ss          second
#define all(x)      x.begin(),x.end()
#define mp          make_pair
#define mod         1000000007
#define mem(a,b)    memset(a,b,sizeof(a))
#define ld          long double
#define endl        "\n"
#define ll          long long
#define llu         unsigned long long
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define vl          vector<ll>
#define vi          vector<int>
#define vc          vector<char>
#define vs          vector<string>
#define si          set<int>
#define spii        set<pii>
#define usi         unordered_set<int>
#define usl         unordered_set<ll>
#define uspii       unordered_set<pii>
#define mii         map<int,int>
#define umii        unordered_map<int,int>
#define pqmx        priority_queue<int>
#define pqmn        priority_queue<int,vi,greater<int>>
#define setbits(x)  __builtin_popcountll(x)
#define fast        ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define testcase    int test;cin>>test;for(ll tst=0;tst<test;tst++)
int xx[4]={0,0,1,-1};
int yy[4]={-1,1,0,0};

/*-----------------------------------------------------------------------------------------------------------------*/

int main()
{
	#ifndef ONLINE_JUDGE
	freopen("C_IN.txt","r",stdin);
	freopen("C_Out.txt","w",stdout);
	#endif
	fast;

	ll n,m;
	cin>>n>>m;
	vl v(11,0);
	fori(0,m)
	{
		int x;
		cin>>x;
		v[x]++;
	}
	ll res=0,b=n;
	while(1)
	{
		int temp=b;
		bool flag=true;
		while(temp>0)
		{
			int rem=temp%10;
			temp=temp/10;
			if(v[rem])
			{
				flag=false;
				break;
			}
		}
		if(flag)
		{
			cout<<b;
			break;
		}
		b++;
	}
	return 0;
}

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int mxn = 11;
vector<bool> val(mxn, 1);

bool valid(string s){
	bool ok = 1;
	int n = int(s.size());
	for(int i = 0; i < n && ok; ++i){
		ok &= (val[s[i] - '0']);
	}
	return ok;
}

int main(){
	ios_base::sync_with_stdio(false); cin.tie(0);
	int n, k;
	cin >> n >> k;
	for(int i = 0, x; i < k; ++i){
		cin >> x;
		val[x] = 0;
	}
	while(1){
		string s = to_string(n);
		if(valid(s)){
			break;
		}
		++n;
	}
	cout << n << '\n';
	return 0;
}


#include<iostream>
using namespace std;

int main(){
	int n;
	cin >>n;

	long long a,min=0,max=0,sum=0;

	for (int i=1; i<=n; i++){
		cin>> a;
		if (i==1)min=a, max=a;
		if (a<min)min=a;
		if (a>max)max=a;
		sum +=a;
	}

	cout<< min <<" "<< max <<" "<< sum <<"\n";

	return 0;
}

#include<iostream>
#define LL long long
using namespace std;
int main() {
	LL sum, min, max, n, d;
	cin >> n;
	cin >> d;
	sum = d;
	min = d;
	max = d;
	n--;
	while (n--) {
		cin >> d;
		sum += d;
		if (min > d)min = d;
		if (max < d)max = d;
	}
	cout << min << ' ' << max << ' ' << sum << endl;
	return 0;
}


/*
Though leaves are many , the root is one.
Through all the lying days of my youth
I swayed my leaves and flowers in the sun.
Now I may wither into the truth.
	  	  	- William Butler Yeats
*/
//#pragma GCC optimize("Ofast,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx")
//#pragma GCC target("avx,tune=native")
#include<bits/stdc++.h>
#pragma comment("-Wl,--stack=1024000000")
//#include<ext/pb_ds/assoc_container.hpp>
using namespace std;
//using namespace __gnu_pbds;
const int inf=0x3f3f3f3f;
const double eps=1e-6;
const int mod=1000000007;
typedef long long ll;
#ifndef LOCAL
#define cerr if(0)cout
#define eprintf(...) 0
#else
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#endif
inline string getstr(string &s,int l,int r){string ret="";for(int i=l;i<=r;i++)ret.push_back(s[i]);return ret;}
int modpow(int x,int y,int md=mod){int ret=1;do{if(y&1)ret=(ll)ret*x%md;x=(ll)x*x%md;}while(y>>=1);return ret;}
inline int Rand(){return rand()*32768+rand();}
int n,k,a[100005],ans;
vector<int>g[100005];
int dfs(int x,int par){
	int mx=0;
	for(auto to:g[x]){
		mx=max(dfs(to,x),mx);
	}
	if(mx==k-1&&a[x]!=1)ans++;
	return (mx+1)%k;
}
int main(){
	cin>>n>>k;
	for(int i=1;i<=n;i++)cin>>a[i];
	for(int i=2;i<=n;i++){
		g[a[i]].push_back(i);
	}
	if(a[1]!=1)ans++,a[1]=1;
	dfs(1,-1);
	cout<<ans<<endl;
	return 0;
}

#include <iostream>
#include <iomanip>
#include <string>
#include <stack>
#include <vector>
#include <complex>
#include <math.h>
#include <stdio.h>
#include <algorithm>
#include <utility>
#include <functional>
#include <iterator>
#include <map>
#include <set>
#include <queue>
#include <list>
#include <regex>
#include <limits>
#include <time.h>
#include <cstdint>
using namespace std;
using pii  = pair<int,int>;
using ll=long long;
using ld=long double;
#define pb push_back
#define mp make_pair
#define sc second
#define fr first
#define stpr setprecision
#define cYES cout<<"YES"<<endl
#define cNO cout<<"NO"<<endl
#define cYes cout<<"Yes"<<endl
#define cNo cout<<"No"<<endl
#define rep(i,n) for(ll i=0;i<(n);++i)
#define Rep(i,a,b) for(ll i=(a);i<(b);++i)
#define rrep(i,n) for(ll i=n-1;i>=0;i--)
#define rRep(i,a,b) for(ll i=a;i>=b;i--)
#define crep(i) for(char i='a';i<='z';++i)
#define psortsecond(A,N) sort(A,A+N,[](const pii &a, const pii &b){return a.second<b.second;});
#define ALL(x) (x).begin(),(x).end()
#define debug(v) cout<<#v<<":";for(auto x:v){cout<<x<<' ';}cout<<endl;
#define endl '\n'
int ctoi(const char c){
  if('0' <= c && c <= '9') return (c-'0');
  return -1;
}
ll gcd(ll a,ll b){return (b == 0 ? a : gcd(b, a%b));}
ll lcm(ll a,ll b){return a*b/gcd(a,b);}
constexpr ll MOD=1000000007;
constexpr ll INF=1000000011;
constexpr ll MOD2=998244353;
constexpr ll LINF = 1001002003004005006ll;
constexpr ld EPS=10e-8;
template <class T, class U> inline bool chmax(T& lhs, const U& rhs) { if (lhs < rhs) { lhs = rhs; return 1; } return 0; }
template <class T, class U> inline bool chmin(T& lhs, const U& rhs) { if (lhs > rhs) { lhs = rhs; return 1; } return 0; }
template<typename T> istream& operator>>(istream& is,vector<T>& v){for(auto&& x:v)is >> x;return is;}
template<typename T,typename U> istream& operator>>(istream& is, pair<T,U>& p){ is >> p.first; is >> p.second; return is;}
template<typename T,typename U> ostream& operator>>(ostream& os, const pair<T,U>& p){ os << p.first << ' ' << p.second; return os;}
template<class T> ostream& operator<<(ostream& os, vector<T>& v){
  for(auto i=begin(v); i != end(v); ++i){
    if(i !=begin(v)) os << ' ';
    os << *i;
  }
  return os;
}

const int MAX = 4000003;

long long fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

// 二項係数計算
long long COM(int n, int k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

int main(){
  COMinit();
  ll N,M,K,ANS=0;
  cin >> N >> M >> K;
  ll com = COM(N*M-2,K-2);
  Rep(i,1,N){
    ll Z=1;
    Z*=M*M*(N-i);
    Z%=MOD;
    Z=(Z*com)%MOD;
    Z=(Z*i)%MOD;
    ANS=(ANS+Z)%MOD;
  }
  Rep(i,1,M){
    ll Z=1;
    Z*=N*N*(M-i);
    Z%=MOD;
    Z=(Z*com)%MOD;
    Z=(Z*i)%MOD;
    ANS=(ANS+Z)%MOD;
  }
  cout << ANS << endl;
}


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

int main(){

    char a[11], b[11], c[11];

    cin >> a >> b >> c;

    if(a[strlen(a)-1] == b[0] && b[strlen(b)-1] == c[0]){
        cout << "YES" << endl;
    }
    else{
        cout << "NO" << endl;
    }

    return 0;

}

#include <bits/stdc++.h>
#include<iostream>
#include<vector>
using namespace std;
typedef long long ll;

#define MOD (long long)(998244353)
#define INF (1LL<<60)
#define rep(i,n) for(ll i = 0; i < (n); i++)
#define rep1(i,n) for(ll i = 1; i <= (n); i++)

template<class T> inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
template<class T> inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}

// 最大公約数
ll gcd(ll a, ll b)
{
  if(b == 0) return a;
  return gcd(b, a % b);
}

// mod m におけるa の逆元
ll modinv(ll a, ll m) {
  ll b = m, u = 1, v = 0;
  while (b) {
    ll t = a / b;
    a -= t * b; swap(a, b);
    u -= t * v; swap(u, v);
  }
  u %= m;
  if (u < 0) u += m;
  return u;
}

// 素因数分解
vector<pair<ll, ll>> prim;
void pf(ll n)
{
  ll s = sqrt(n);
  ll r = 0;
  for(ll i = 2; i <= s; i++) {
    if((n % i) == 0) {
      r = 0;
      do {
	r++;
	n = n / i;
      } while((n % i) == 0);
      prim.push_back({i, r});
    }
  }
  if(n > s) {
    prim.push_back({n, 1});
  }
}

void solve()
{
  ll N; cin >> N;
  // ll x, y, z; cin >> x >> y >> z;
  // ll a, b, c; cin >> a >> b >> c;
  // string s; cin >> s;
  vector<ll> a(N); rep(i, N) cin >> a[i];
  vector<ll> c(100100, 0);
  rep(i,N) {
    c[a[i]]++;
  }
  if(a[0]!=0 || c[0]!=1) {
    cout << 0 << endl;
    return;
  }

  ll ans = 1;
  rep(i,N-1) {
    rep(j, c[i+1]) {
      ans*= c[i];
      ans%=MOD;
    }
  }
  // bool ok = false;

  cout << ans << endl;
  // cout << (ok?"Yes":"No") << endl;
}

int main(void)
{
  // ll t; cin >> t; rep(i, t)
  solve();
}


#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<ll,ll>;
using vl = vector<ll>;
using Map = map<ll,ll>;
using T = tuple<ll,ll,ll>;
using vvl = vector<vector<ll>>;
#define all(v) v.begin(), v.end()
#define prt(v) cout<<(v)<<"\n";
#define fi(v) get<0>(v)
#define se(v) get<1>(v)
#define th(v) get<2>(v)
#define endl "\n"
template <typename T> bool chmax(T &a, const T &b){if (a<b){a=b;return 1;}return 0;}
template <typename T> bool chmin(T &a, const T &b){if (a>b){a=b;return 1;}return 0;}
const ll INF=1LL<<60;
const ll MOD=1000000007;

//dp[i][j]はそれぞれiグラム、jグラム買うときの最小価格
vector<vector<ll>> dp(500, vector<ll>(500, INF));

signed main(void){
    cin.tie(0);cout.tie(0);ios::sync_with_stdio(false);
    ll N;
    cin >> N;
    ll A;
    cin >> A;
    ll B;
    cin >> B;
    vector<ll> X(N,0);
    for(ll i=0;i<N;++i)cin>>X[i];
    ll ans=0;
    for(ll i=1;i<N;++i){
        ans+=min(A*(X[i]-X[i-1]),B);
    }
    prt(ans)

    return 0;
}

#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define IO(i, o) freopen(i, "r", stdin), freopen(o, "w", stdout)

using namespace std;
using namespace __gnu_pbds;
typedef tree<long long, null_type, less<long long>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;
mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());

int n, a, b, x[100000];

int main(){
	//IO("input.txt", "output.txt");
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cin >> n >> a >> b >> x[0];
	long long cnt = 0;
	for(int i = 1; i < n; i++){
		cin >> x[i];
		cnt += min((long long)b, a * (long long)(x[i] - x[i - 1]));
	}
	cout << cnt << "\n";
	return 0;
}


#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
using namespace std;
using ll = long long ;
using P = pair<int,int> ;
using pll = pair<long long,long long>;
constexpr int INF = 1e9;
constexpr long long LINF = 1e17;
constexpr int MOD = 1000000007;
constexpr double PI = 3.14159265358979323846;

using pv = pair<P,vector<int>>;
vector<int> graph[1005];

int main(){
    int n,m;
    cin >> n >> m;
    vector<P> edge(m);
    rep(i,m){
        cin >> edge[i].first >> edge[i].second;
        --edge[i].first;--edge[i].second;
        graph[edge[i].first].push_back(edge[i].second);
    }
    int id = -1;
    int mn = INF;
    vector<int> ans;
    rep(i,m){
        vector<bool> seen(n,false);
        queue<pv> q;
        q.push(pv(P(edge[i].second,0),{}));
        while(!q.empty()){
            int now = q.front().first.first;
            int c = q.front().first.second;
            vector<int> way = q.front().second;
            q.pop();
            if(now==edge[i].first){
                if(c < mn){
                    id = i;
                    mn = c;
                    way.push_back(now);
                    ans = way;
                    break;
                }else{
                    break;
                }
            }
            if(seen[now]) continue;
            seen[now] = true;
            way.push_back(now);
            for(int j:graph[now]){
                if(seen[j]) continue;
                q.push(pv(P(j,c+1),way));
            }
        }
    }
    if(mn==INF){
        cout << -1 << endl;
    }else{
        cout << (int)ans.size() << endl;
        rep(i,ans.size()) cout << ans[i]+1 << endl;
    }
    return 0;
}

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int N = 1e5 + 7;
const int L = 17;

int go[N][L];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n;
    cin >> n;
    vector <int> x(n);
    for (int i = 0; i < n; i++) {
        cin >> x[i];
    }
    int l;
    cin >> l;
    vector <int> who(n);
    int ptr = n - 1;
    for (int i = n - 1; i >= 0; i--) {
        while (ptr > i && x[ptr] - x[i] > l) ptr--;
        who[i] = ptr;
    }
    for (int i = n - 1; i >= 0; i--) {
        go[i][0] = who[i];
        for (int j = 1; j < L; j++) {
            go[i][j] = go[go[i][j - 1]][j - 1];
        }
    }
    int q;
    cin >> q;
    while (q--) {
        int a, b;
        cin >> a >> b;
        a--, b--;
        if (a > b) swap(a, b);
        int pos = a;
        int res = 0;
        for (int i = L - 1; i >= 0; i--) {
            if (go[pos][i] < b) {
                pos = go[pos][i];
                res += (1 << i);
            }
        }
        cout << res + 1 << '\n';
    }
    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Wavelet {
public:
    explicit Wavelet(const vector<unsigned int>& a) : N(a.size()), vb(getDigits_(a), BitVector(a.size())){
        vector<unsigned int> v = a;
        vector<unsigned int> v0(N), v1(N);
        for(int i=vb.size()-1;i>=0;i--){
            maxVal = 2 * maxVal + 1;
            int idx0 = 0, idx1 = 0;
            for(int j=0;j<N;j++){
                if(v[j]&(1<<i)){
                    v1[idx1++] = v[j];
                    vb[i].set(j);
                } else {
                    v0[idx0++] = v[j];
                }
            }
            for(int j=0;j<idx0;j++) v[j]      = v0[j];
            for(int j=0;j<idx1;j++) v[j+idx0] = v1[j];
            vb[i].build();
        }
    }
    int getLeqNum(int val, int end){
        if(end <= 0) return 0;
        if(val < 0) return 0;
        val = min(val, maxVal);
        int res = 0;
        int offset = 0, num = end-1;
        for(int i=vb.size()-1;i>=0;i--){
            if(num < offset) break;
            int rank1 = vb[i].rank(num) - vb[i].rank(offset-1);
            int rank0 = num-offset+1-rank1;
            if(val&(1<<i)){
                if(i == 0) return res + num-offset+1;
                res += rank0;
                offset = N - vb[i].rank(N) + vb[i].rank(offset-1);
                num = offset + rank1 - 1;
            } else {
                if(i == 0) return res + rank0;
                offset = offset - vb[i].rank(offset-1);
                num = offset + rank0 - 1;
            }
        }
        return res;
    }
private:
    int getDigits_(const vector<unsigned int>& a){
        int m = *max_element(a.begin(), a.end());
        int res = 0;
        while(m){ ++res; m /= 2; }
        return max(1, res);
    }
    class BitVector{
    public:
        explicit BitVector(int n=0) : bit((n+63)/64) {}
        void set(int p){
            while(p/64 >= bit.size()) bit.emplace_back(0ULL, 0);
            bit[p/64].first |= 1ULL << (p%64);
        }
        bool get(int p) const {
            if(p/64 >= bit.size()) return false;
            return bit[p/64].first & (1ULL << p%64);
        }
        void build(){
            for(int i=1;i<bit.size();i++)
                bit[i].second = bit[i-1].second + bitCount_(bit[i-1].first);
        }
        int rank(int p) const {
            if(p < 0 || bit.size() == 0) return 0;
            if(p/64 >= bit.size()) return bit.back().second + bitCount_(bit.back().first);
            if(p%64 == 63) return bit[p/64].second + bitCount_(bit[p/64].first);
            return bit[p/64].second + bitCount_(bit[p/64].first & (1ULL << p%64+1)-1);
        }
    private:
        vector<pair<unsigned long long, int>> bit;
        int bitCount_(unsigned long long t) const {
            t = (t&0x5555555555555555ULL)+((t>>1)&0x5555555555555555ULL);
            t = (t&0x3333333333333333ULL)+((t>>2)&0x3333333333333333ULL);
            t = (t&0x0f0f0f0f0f0f0f0fULL)+((t>>4)&0x0f0f0f0f0f0f0f0fULL);
            t = (t&0x00ff00ff00ff00ffULL)+((t>>8)&0x00ff00ff00ff00ffULL);
            t = (t&0x0000ffff0000ffffULL)+((t>>16)&0x0000ffff0000ffffULL);
            t = (t&0x00000000ffffffffULL)+((t>>32)&0x00000000ffffffffULL);
            return t;
        }
    };
private:
    const int N;
    int maxVal = 0;
    vector<BitVector> vb;
};

int main(){
    int N, Q; cin >> N >> Q;
    vector<int> last(N, -1);
    vector<unsigned int> a(N, 0);
    for(int i=0;i<N;i++){
        int t; cin >> t;
        --t;
        if(last[t] != -1) a[i] = last[t] + 1;
        last[t] = i;
    }
    Wavelet wav(a);
    for(int i=0;i<Q;i++){
        int l, r; cin >> l >> r;
        --l;
        cout << r - l - (wav.getLeqNum(r, r) - wav.getLeqNum(l, r)) << endl;
    }
}

#include <bits/stdc++.h>

struct FastIO {
  FastIO() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(NULL);
  }
} fast_io;

#if DEBUG
template <typename T>
void debug(const T& value) {
  std::cerr << value;
}
template <typename T, typename... Ts>
void debug(const T& value, const Ts&... args) {
  std::cerr << value << ", ";
  debug(args...);
}
#define dbg(...)                        \
  do {                                  \
    cerr << #__VA_ARGS__ << ": ";       \
    debug(__VA_ARGS__);                 \
    cerr << " (L" << __LINE__ << ")\n"; \
  } while (0)
#else
#define dbg(...)
#endif

void read_from_cin() {}
template <typename T, typename... Ts>
void read_from_cin(T& value, Ts&... args) {
  std::cin >> value;
  read_from_cin(args...);
}
#define rd(type, ...) \
  type __VA_ARGS__;   \
  read_from_cin(__VA_ARGS__);

template <typename T>
void write_to_cout(const T& value) {
  std::cout << value << '\n';
}
template <typename T, typename... Ts>
void write_to_cout(const T& value, const Ts&... args) {
  std::cout << value << ' ';
  write_to_cout(args...);
}
#define wt(...) write_to_cout(__VA_ARGS__);

#define all(x) (x).begin(), (x).end()
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)

using ll = long long;

template <typename T>
using V = std::vector<T>;
template <typename T>
using VV = V<V<T>>;
#include <math.h>

template <typename T, class DS>
class Mo {
 public:
  Mo(DS& ds) : ds_(ds) {}
  void AddQuery(int begin, int end) {
    int index = queries_.size();
    queries_.push_back({begin, end, index});
  }
  std::vector<T> ProcessQueries() {
    int bin = sqrt(queries_.size());
    sort(queries_.begin(), queries_.end(),
         [&bin](const Query& a, const Query& b) {
           int c = a.begin / bin, d = b.begin / bin;
           if (c != d) return c < d;
           if (c % 2 == 0) {
             return a.end < b.end;
           }
           return a.end > b.end;
         });
    std::vector<T> ret(queries_.size());
    Query p = {0, 0, 0};
    for (std::size_t i = 0; i < queries_.size(); ++i) {
      const Query& c = queries_[i];
      Add(c.begin, p.begin);
      Del(p.begin, c.begin);
      Add(p.end, c.end);
      Del(c.end, p.end);
      ret[c.index] = ds_.Get();
      p = c;
    }
    return ret;
  }

 private:
  struct Query {
    int begin, end, index;
  };
  void Add(int begin, int end) {
    for (int i = begin; i < end; ++i) {
      ds_.Add(i);
    }
  }
  void Del(int begin, int end) {
    for (int i = begin; i < end; ++i) {
      ds_.Del(i);
    }
  }
  DS& ds_;
  std::vector<Query> queries_;
};

using namespace std;

struct DS {
  DS(int n) : c(n), kinds(n), unique_kinds(0) {}
  void Add(int i) {
    if (kinds[c[i] - 1]++ == 0) {
      ++unique_kinds;
    }
  }
  void Del(int i) {
    if (--kinds[c[i] - 1] == 0) {
      --unique_kinds;
    }
  }
  int Get() const { return unique_kinds; }
  V<int> c;
  V<int> kinds;
  int unique_kinds;
};

int main() {
  rd(int, n, q);
  DS ds(n);
  rep(i, n) cin >> ds.c[i];

  Mo<int, DS> mo(ds);
  rep(i, q) {
    rd(int, l, r);
    mo.AddQuery(l - 1, r);
  }

  for (int ans : mo.ProcessQueries()) {
    wt(ans);
  }
}


#include <bits/stdc++.h>
using namespace std;
// define
#define int long long
#define UNIQUE(v) v.erase(unique(all(v)), v.end());
#define ZIP(v) sort(all(v)),UNIQUE(v)
#define ADD(a, b) a = (a + b) % mod
#define SUB(a, b) a = (a+mod-b)%mod
#define MUL(a, b) a = (((a)%mod) * ((b)%mod)) % mod
#define rollcall cout << "I'm Sucu." << endl;
#define repi(i,m,n) for(int i = m;i < n;i++)
#define drep(i,n,m) for(int i = n;i >= m;i--)
#define rep(i,n) repi(i,0,n)
#define rrep(i,n) repi(i,1,n+1)
#define chmin(x,y) x = min(x,y)
#define chmax(x,y) x = max(x,y)
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(), v.rend()
#define dmp(x,y) make_pair(x,y)
#define pb(x) push_back(x)
#define pf(x) push_front(x)
#define fi first
#define se second
// typedef
typedef complex<double> Point;
typedef pair<int, int> P;
typedef pair<int, P> PP;
typedef pair<P, int> Pi;
typedef vector<int> vi;
typedef deque<int> dq;
const int inf = 1e9+7;
const int INF = 1e18+7;
const int mod = 1e9+7;
// int sum = accumulate(a, a+n, 0LL);
// int mx = max_element(a, a+n);
// int mn = min_element(a, a+n);
// int cnt = count(a, a+n, k);

int N;

signed main()
{
    cin >> N;
    vi A(N), B(N), C(N);
    rep(i, N) cin >> A[i];
    rep(i, N) cin >> B[i];
    rep(i, N) cin >> C[i];

    sort(all(A));
    sort(all(C));

    int ans = 0;

    rep(i,N)
    {
        auto low = lower_bound(all(A), B[i]);
        int ac = low - A.begin();
        auto high = upper_bound(all(C), B[i]);
        int cc = C.end() - high;
        ans += ac * cc;
    }

    cout << ans << endl;

    return 0;
}

#include<bits/stdc++.h>
using namespace std;
int main(){
    int n;
    cin >> n;
    long a[n];
    for(int i=0;i<n;i++)cin >> a[i];
    long dai = 0;
    for(int i=1;i<n;i++){
        if(a[i] >= a[i-1]){
            continue;
        }else{
            dai += a[i-1] - a[i];
            a[i] = a[i-1];
        }
    }
    cout << dai << endl;
}


#include<bits/stdc++.h>
using namespace std;
int main(){
    int n, m;
    cin >> n >> m;
    vector<vector<pair<int, int> > >edge(n + 3);
    vector<vector<int> >rails(n + 3);
    for(int i = 1; i <= m; i++){
        int u, v, c;
        cin >> u >> v >> c;
        edge[u].push_back({c, v});
        edge[v].push_back({c, u});
        rails[u].push_back(c);
        rails[v].push_back(c);
    }
    for(int i = 1; i <= n; i++){
        sort(edge[i].begin(), edge[i].end());
    }
    deque<pair<int, pair<int, int> > >dq;
    vector<map<int, int> >mp(n + 3);
    mp[1][0] = 0;
    dq.push_back({0, {1, 0}});
    while(!dq.empty()){
        int d = dq.front().first;
        int now = dq.front().second.first;
        int rail = dq.front().second.second;
        dq.pop_front();
        if(rail == 0){
            for(int i = 0; i < rails[now].size(); i++){
                int nrail = rails[now][i];
                if(mp[now].find(nrail) != mp[now].end() && mp[now][nrail] <= d + 1){
                    continue;
                }
                mp[now][nrail] = d + 1;
                dq.push_back({d + 1, {now, nrail}});
            }
        }
        else{
            pair<int, int>p = make_pair(rail, 0);
            int x = lower_bound(edge[now].begin(), edge[now].end(), p) - edge[now].begin();
            while(x != edge[now].size() && edge[now][x].first == rail){
                int nxt = edge[now][x].second;
                if(mp[nxt].find(rail) != mp[nxt].end() && mp[nxt][rail] <= d){
                    x++;
                    continue;
                }
                mp[nxt][rail] = d;
                dq.push_front({d, {nxt, rail}});
                x++;
            }
            if(mp[now].find(0) != mp[now].end() && mp[now][0] <= d){
                continue;
            }
            mp[now][0] = d;
            dq.push_front({d, {now, 0}});
        }
    }
    if(mp[n].empty()){
        cout << "-1";
        return 0;
    }
    int ans = 1e8;
    for(int i = 0; i < rails[n].size(); i++){
        int x = rails[n][i];
        ans = min(ans, mp[n][x]);
    }
    cout << ans;
    return 0;
}

#include <bits/stdc++.h>
#define INF 1023456789
#define sacnf scanf
#define scnf scanf
#define scnaf scanf
#define CRLF <<'\n';
#define ALL(v) v.begin,v.end()
#define SIZE(v) (int)v.size()
#define PRPAIR(x) x.first << x.second
#define DEBUG(x) do { std::cerr <<(x)<<'\n'; } while (0)
#define rep(i,a,b) for(int i=(a);i!=(int)b-((a)>(b));(a)>(b)?--i:++i)
using namespace std;
typedef pair<int,int> ii;
typedef pair<ii,int> pip;
typedef vector<int> vi;
typedef long long ll;
#define BLK 707

int main(){
    int n,q;
    scanf("%d%d",&n,&q);
    int arr[n];
    pip que[q];
    rep(i,0,n)
        scanf("%d",&arr[i]),arr[i]--;
    rep(i,0,q){
        int a,b;
        scanf("%d%d",&a,&b);
        a--,b--;
        que[i] = pip(ii(a,b),i);
    }
    sort(que,que+q,[](pip a,pip b){
                     if (a.first.first/BLK==b.first.first/BLK)
                         return (a.first.first/BLK & 1) ? (a.first.second < b.first.second) : (a.first.second > b.first.second);
                     else
                         return a.first.first/BLK<b.first.first/BLK;
                 });
    int ans[q];
    int L=0,R=-1;
    int cnt[n];
    memset(cnt,0,sizeof cnt);
    int num=0;
    rep(i,0,q){
        int l=que[i].first.first,r=que[i].first.second;
        while(L < l){
            if (--cnt[arr[L]] == 0)
                num--;
            L++;
        }
        while(L > l){
            --L;
            if (cnt[arr[L]]++ == 0)
                num++;
        }
        while(R<r){
            ++R;
            if (cnt[arr[R]]++ == 0)
                num++;
        }
        while(R>r){
            if (--cnt[arr[R]]==0)
                num--;
            R--;
        }
        ans[que[i].second] = num;
    }
    rep(i,0,q)
        printf("%d\n",ans[i]);

}


#include <bits/stdc++.h>

using namespace std;

#define REP(i, n)   for(int i = 0; i < (n); i++)
#define REPS(i, n)  for(int i = 1; i <= (n); i++)
#define RREP(i, n)  for(int i = (n)-1; i >= 0; i--)
#define RREPS(i, n) for(int i = (n); i > 0; i--)
#define ALL(v) v.begin(), v.end()
#define RALL(v) v.rbegin(), v.rend()
#define UNIQUE(v) v.erase(unique(v.begin(), v.end()), v.end())
#define mp make_pair
#define mt make_tuple
#define pb push_back

using ll  = long long;
using pi  = pair<int, int>;
using pl  = pair<ll, ll>;
using vi  = vector<int>;
using vl  = vector<ll>;
using vs  = vector<string>;
using vb  = vector<bool>;
using vvi = vector<vi>;
using vvl = vector<vl>;

const int MOD = 1e9 + 7;
const int INF = 1e9 + 7;
const ll  INFL = 1e18;
const double PI = 3.141592653589793;
const double EPS = 1e-9;

template<class T> bool chmax(T &a, const T &b) { if(a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, const T &b) { if(a > b) { a = b; return true; } return false; }

signed main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(20);

    ll N; cin >> N;

    vl factor(N+1);
    for(ll i = 2; i <= N; i++)
    {
        ll tmp = i;
        for(ll j = 2; j * j <= i; j++)
        {
            while(tmp % j == 0)
            {
                factor[j]++;
                tmp /= j;
            }
        }
        if(tmp != 1) factor[tmp]++;
    }

    ll ans = 1;
    REP(i, (int)factor.size())
    {
        ans *= factor[i] + 1;
        ans %= MOD;
    }
    cout << ans << endl;
}

#include <iostream>
#include <bits/stdc++.h>
#include <math.h>

using namespace std;

int main(){
    string s;
    cin>>s;
    string ans="Yes";
    for(int i=0;i<s.size();i+=2){
        if(s.size()%2==1){
            ans="No";
            break;
        }
        if(s.at(i)!='h' || s.at(i+1)!='i'){
            ans="No";
            break;
        }
    }

    cout<<ans<<endl;

    return 0;
}


#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <utility>
#include <set>
#include <cctype>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
#define MAXN 5010
int main(void) {
    while (1) {
        int n;
        cin >> n;
        if (n == 0) break;
        int a[MAXN], sum[MAXN];
        for (int i = 0; i < n; i++) {
            a[i] = 0;
            sum[i] = 0;
        }
        sum[0] = 0;
        for (int i = 1; i <= n; i++) {
            cin >> a[i];
            sum[i] = sum[i-1] + a[i];
        }
        int ret = a[1];
        for (int i = 0; i <= n; i++) {
            for (int j = i+1; j <= n; j++) {
                ret = max(sum[j]-sum[i], ret);
            }
        }
        cout << ret << endl;
    }
    return 0;
}

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

int main() {
	int n, a;
	vector<int> an;
	vector<vector<int>> AN;
	while (cin >> n) {
		if (n == 0)break;
		for (int i = 0; i < n; i++) {
			cin >> a;
			an.push_back(a);
		}
		AN.push_back(an); an.clear();
	}

	for (int i = 0; i < AN.size(); i++) {
		long long int max = 0, min = INT_MAX, MAX = 0, MIN = 0 , counter = 0, negative = 0;
		for (int j = 0; j < AN[i].size(); j++) {
			if (AN[i][j] >= 0) {
				max += AN[i][j];
				if (MAX < max)MAX = max;
				counter = 1;
				negative = 1;
			}

			else {
				if (negative == 0) {
						if(min > abs(AN[i][j]))min=abs(AN[i][j]);
					}
				else if (counter==1){
					if (AN[i][j] + max >= 0)max += AN[i][j];
					else {
						max = 0;
						counter = 0;
					}
				}
			}
		}
		if (negative == 0)cout << -1*min << endl;
		else cout << MAX << endl;
	}
	return 0;
}


#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

typedef pair<int , int> ii;
typedef long long ll;
const ll mod = 1e9 + 7;
const int maxn = 1e5 + 10;
int N;
string S;
ll fac[maxn];

int main(){
  cin >> N;
  cin >> S;
  fac[0] = 1;
  for(int i = 1; i < maxn; ++i)fac[i] = fac[i - 1] * i % mod;
  ll ret = 1;
  ll cnt = 0;
  for(int i = 0; i < 2 * N; ++i){
    char cc;
    if(cnt & 1){
      if(S[i] == 'W'){
        cc = 'L';
      }
      else{
        cc = 'R';
      }
    }
    else{
      if(S[i] == 'W'){
        cc = 'R';
      }
      else{
        cc = 'L';
      }
    }
    if(cc == 'R'){
      ret = (ret * cnt) % mod;
      --cnt;
    }
    else ++cnt;
    if(cnt < 0){
      cout << 0 << endl;
      return 0;
    }
  }
  if(cnt)cout << 0 << endl;
  else cout << (ret * fac[N] % mod + mod) % mod << endl;
  return 0;
}

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

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    int n;
    cin>>n;
    int remainder;
    bool vqrno=false;
    while(n!=0){
        remainder=n%10;
        if(remainder==7){
            vqrno=true;
            break;
        }
        else
            n/=10;
    }
    if(vqrno==true)
        puts("Yes");
    else
        puts("No");
}


#include <iostream>
#include <fstream>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <functional>
#include <algorithm>
#include <climits>
#include <cmath>
#include <iomanip>
using namespace std;
#define ll long long int
#define rep(i,n) for( int i = 0; i < n; i++ )
#define rrep(i,n) for( int i = n; i >= 0; i-- )
#define REP(i,s,t) for( int i = s; i <= t; i++ )
#define RREP(i,s,t) for( int i = s; i >= t; i-- )
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define INF 2000000000
#define mod 1000000007
#define INF2 10000000000000000
#define int long long

int dp[200010][3];
int A[200010];
int N;
int calc(int x, int remain_skip) {
    //cout << x << " " << remain_skip << endl;
    if(dp[x][remain_skip] != -INF2) return dp[x][remain_skip];
    if(x >= N) {
        if(remain_skip == 2) return -INF2;
        return 0;
    }
    int ret = -INF2;
    if(remain_skip > 0) ret = calc(x + 1, remain_skip - 1);
    ret = max(ret, calc(x + 2, remain_skip) + A[x]);
    return dp[x][remain_skip] = ret;
}

signed main(void)
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> N;
    rep(i, N) cin >> A[i];
    rep(i, 200010) rep(j, 3) dp[i][j] = -INF2;
    cout << calc(0, 1 + (N % 2 == 1)) << endl;

    return 0;
}
// 1 2 3 4

#include <stdio.h>
#include <cstdio>
#include <iostream>
#include <iomanip>
#include <queue>
#include <set>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <complex>

using ll = long long int;
using namespace std;

int main(){

  ll N, tmp;
  vector<ll> A;
  cin >> N;
  for(ll i = 0; i < N; i++){
    cin >> tmp;
    A.push_back(tmp);
  }

  // if N is even
  if(N%2 == 0){
    cerr << "N is even." << endl;
    vector<ll> accum(N);
    accum[0] = A[0];
    for(ll i = 2; i < N; i+=2){
      accum[i] = accum[i-2] + A[i];
    }
    accum[N-1] = A[N-1];
    for(ll i = N-3; i >= 1; i-=2){
      accum[i] = accum[i+2] + A[i];
    }
    ll ans = max(accum[N-2], accum[1]);
    for(ll i = 0; i<=N-4; i+=2){
      ans = max(ans, accum[i]+accum[i+3]);
    }

    cerr << "Answer:" << endl;
    cout << ans << endl;

    return 0;
  }
  // N is odd
  else{
    cerr << "N is odd." << endl;
    vector<ll> accum(N);
    accum[0] = A[0];
    for(ll i = 2; i < N; i++){
      accum[i] = accum[i-2] + A[i];
    }
    accum[N-2] = A[N-2];
    for(ll i = N-4; i >= 1; i-=2){
      accum[i] = accum[i+2] + A[i];
    }
    vector<ll> diff(N);
    for(ll i = 1; i <= N-4; i+=2){
      diff[i] = accum[i-1] + accum[i+2] - accum[1];
    }
    for(ll i = 2; i <= N-3; i+=2){
      diff[i] = accum[N-1]-accum[i] + accum[1] - accum[i+1] - accum[1];
    }
    diff[N-2] = accum[N-3] - accum[1];
    diff[0] = accum[2] - accum[1];

    vector<ll> eomax(N);
    eomax[N-3] = diff[N-3];
    for(ll i = N-5; i >= 0; i-=2){
      eomax[i] = max(eomax[i+2], diff[i]);
    }

    ll ans = max(max(accum[N-1]-accum[0], accum[N-3]), accum[1]);
    for(ll oe = 1; oe < N-2; oe+=2){
        ans = max(ans, accum[1]+diff[oe]+eomax[oe+1]);
    }

    cerr << "Answer:" << endl;
    cout << ans << endl;

    return 0;
  }

}


#include<bits/stdc++.h>
typedef long long ll;
ll gi(){
	ll x=0,f=1;
	char ch=getchar();
	while(!isdigit(ch))f^=ch=='-',ch=getchar();
	while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
	return f?x:-x;
}
std::mt19937 rnd(time(NULL));
#define rand rnd
#define pr std::pair<int,int>
#define fi first
#define se second
template<class T>void cxk(T&a,T b){a=a>b?a:b;}
template<class T>void cnk(T&a,T b){a=a<b?a:b;}
#ifdef mod
int pow(int x,int y){
	int ret=1;
	while(y){
		if(y&1)ret=1ll*ret*x%mod;
		x=1ll*x*x%mod;y>>=1;
	}
	return ret;
}
template<class Ta,class Tb>void inc(Ta&a,Tb b){a=a+b>=mod?a+b-mod:a+b;}
template<class Ta,class Tb>void dec(Ta&a,Tb b){a=a>=b?a-b:a+mod-b;}
#endif
int n,D1,D2,N,x[360001],y[360001],c[2][360001];
std::vector<int>vec[4];
void getcol(int D,int*c){
	int A=1;
	while(D%4==0)D>>=2,A<<=1;
	for(int i=1;i<=N;++i)
		if(D%4==1)c[i]=((x[i]/A)+(y[i]/A))&1;
		else c[i]=(x[i]/A)&1;
}
int main(){
#ifdef LOCAL
	freopen("in.in","r",stdin);
	//freopen("out.out","w",stdout);
#endif
	n=gi(),D1=gi(),D2=gi(),N=n*n*4;
	for(int i=1;i<=N;++i)x[i]=(i-1)/(2*n),y[i]=(i-1)%(2*n);
	getcol(D1,c[0]),getcol(D2,c[1]);
	for(int i=1;i<=N;++i)vec[(c[0][i]<<1)|c[1][i]].push_back(i);
	for(int i=0;i<4;++i)
		if(vec[i].size()>=n*n){
			N=n*n;
			for(int j:vec[i]){
				printf("%d %d\n",x[j],y[j]);
				if(!--N)break;
			}
			exit(0);
		}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;using ll=int_fast64_t;using ld=long double;using pll=pair<ll,ll>;using pld=pair<ld,ld>;
const ll INF=1LL<<60;void solve();int main(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(10);solve();}
#define foreach(i,a) for(auto &i:a)
#define SELECTOR(_1,_2,_3,_4,SELECT,...) SELECT
#define rep(...) SELECTOR(__VA_ARGS__,_rep2,_rep1,_rep0)(__VA_ARGS__)
#define _rep0(i,n) for(ll i=0;i<n;++i)
#define _rep1(i,k,n) for(ll i=k;i<n;++i)
#define _rep2(i,k,n,d) for(ll i=k;d!=0&&d>0?i<n:i>n;i+=d)
template<class T> vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
template<class... Ts> auto make_v(size_t a,Ts... ts){return vector<decltype(make_v(ts...))>(a,make_v(ts...));}
template<class T> inline bool chmax(T &a,const T &b){if(a<b){a=b; return 1;} return 0;}
template<class T> inline bool chmin(T &a,const T &b){if(a>b){a=b; return 1;} return 0;}

void solve(){
  ll n; cin>>n;
  string S; cin>>S;
  ll q; cin>>q;
  rep(_,q){
    ll k; cin>>k;
    vector<ll> DMC(3);
    ll cnt=0;
    ll ans=0;
    queue<char> Q;
    foreach(s,S){
      // push
      if(s=='D'){
        DMC[0]++;
      }else if(s=='M'){
        DMC[1]++;
        cnt+=DMC[0];
      }else if(s=='C'){
        DMC[2]++;
        ans+=cnt;
      }
      Q.push(s);

      // pop
      if(Q.size()<k) continue;
      char t=Q.front(); Q.pop();
      if(t=='D'){
        DMC[0]--;
        cnt-=DMC[1];
      }else if(t=='M'){
        DMC[1]--;
      }else if(t=='C'){
        DMC[2]--;
      }
    }
    cout<<ans<<"\n";
  }
}

#include <cstdio>
#include <iostream>
#include <vector>
#include <set>
using namespace std;

#define M 100000

vector<int> G[M];
int N;
bool visited[M];
int prenum[M], parent[M], lowest[M], timer;

void dfs(int current, int prev){
  //?????????current????¨???????????????¨?????????
  prenum[current] = lowest[current] = timer;
  timer++;

  visited[current] = true;

  int next;
  for(int i=0; i<G[current].size(); ++i){
    next = G[current][i];

    if( !visited[next] ){
      //?????????current???????????????next????¨????????????´????????????
      parent[next] = current;

      dfs(next, current);

      //?????????next?????¢?´¢????????????????????¨?????????
      lowest[current] = min(lowest[current], lowest[next]);
    }
    else if( next != prev){ //??¨??????current --> next ???Back-Edge?????´???
      lowest[current] = min(lowest[current], prenum[next]);
    }

  }
  //?????????current ?????¢?´¢????????????????????¨?????????
}

void art_points(){
  for(int i=0; i<N; ++i) visited[i] = false;
  timer=1;

  //lowest????¨????
  dfs(0, -1); //0 == root

  set<int> ap;
  int np=0;
  for(int i=1; i<N; ++i){
    int p = parent[i];
    if(p==0) np++;
    else if(prenum[p] <= lowest[i]) ap.insert(p);
  }

  if(np>1) ap.insert(0);
  for(set<int>::iterator it = ap.begin(); it!=ap.end(); ++it) cout << *it << endl;
}

int main(){
  int m;
  scanf(" %d %d", &N, &m);

  for(int i=0; i<m; ++i){
    int s, t;
    scanf(" %d %d", &s, &t);
    G[s].push_back(t);
    G[t].push_back(s);
  }

  art_points();

}


#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using vec = vector<ll>;
using mat = vector<vec>;
using pll = pair<ll,ll>;

#define INF (1LL << 60)
#define MOD 1000000007
#define PI 3.14159265358979323846

#define REP(i,m,n) for(ll (i)=(m),(i_len)=(n);(i)<(i_len);++(i))
#define FORR(i,v) for(auto (i):v)
#define ALL(x) (x).begin(), (x).end()
#define PR(x) cout << (x) << endl
#define PS(x) cout << (x) << " "
#define SZ(x) ((ll)(x).size())
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MIN(a,b) (((a)<(b))?(a):(b))
#define REV(x) reverse(ALL((x)))
#define ASC(x) sort(ALL((x)))
#define DESC(x) ASC((x)); REV((x))
#define pb push_back
#define eb emplace_back

int main()
{
    ll H, W;
    cin >> H >> W;
    mat A(H, vec(W, 0));
    REP(i,0,H) {
        REP(j,0,W) {
            cin >> A[i][j];
            A[i][j] %= 2;
        }
    }

    mat Z;
    REP(i,0,H) {
        bool f = false;
        REP(j,0,W-1) {
            vec z = {i+1, j+1, i+1, j+2};
            if(A[i][j] == 1) {
                if(!f) {
                    A[i][j] = 0;
                    f = true;
                }
                else {
                    A[i][j] = 0;
                    f = false;
                }
            }
            if(f) Z.pb(z);
        }
        if(f) A[i][W-1] = 1 - A[i][W-1];
    }

    bool f = false;
    REP(i,0,H-1) {
        vec z = {i+1, W, i+2, W};
        if(A[i][W-1] == 1) {
            if(!f) {
                A[i][W-1] = 0;
                f = true;
            }
            else {
                A[i][W-1] = 0;
                f = false;
            }
        }
        if(f) Z.pb(z);
    }
    if(f) A[H-1][W-1] = 1 - A[H-1][W-1];

    PR(SZ(Z));
    REP(i,0,SZ(Z)) {
        PS(Z[i][0]); PS(Z[i][1]); PS(Z[i][2]); PR(Z[i][3]);
    }

    return 0;
}

/*

*/

#include<bits/stdc++.h>
using namespace std;
#define int long long
signed main(){
  int H,W;
  cin>>H>>W;
  vector<vector<int>> A(H,vector<int>(W));
  for(vector<int> &v:A)
    for(int &i:v)
      cin>>i;
  int k=0;
  vector<vector<int>> B(0);
  for(int i=0;i<H;i++){
    for(int j=0;j<W-1;j++){
      if(A[i][j]%2==1){
        k++;
        A[i][j+1]+=A[i][j];
        B.push_back({i+1,j+1,i+1,j+2});
      }
    }
    if(A[i][W-1]%2==1 && i!=H-1){
      k++;
      A[i+1][W-1]+=A[i][W-1];
      B.push_back({i+1,W,i+2,W});
    }
  }
  cout<<k<<endl;
  for(vector<int> v:B)
    cout<<v[0]<<' '<<v[1]<<' '<<v[2]<<' '<<v[3]<<endl;
}


#include<bits/stdc++.h>
#include<unordered_set>
#include<unordered_map>
using namespace std;
#define int long long
#define REP(i,m,n) for(int i=(m);i<(n);i++)
#define rep(i,n) REP(i,0,n)
#define pb push_back
#define all(a) a.begin(),a.end()
#define rall(c) (c).rbegin(),(c).rend()
#define mp make_pair
#define endl '\n'
typedef long long ll;
typedef pair<ll,ll> pll;
typedef long double ld;
const ll inf=1e9+7;
const ll mod=1e9+7;
signed main(){
    ll n;cin>>n;
    cout<<0<<endl;
    string s;cin>>s;
    if(s=="Vacant"){
        return 0;
    }
    cout<<n/2<<endl;
    string t;cin>>t;
    if(t=="Vacant"){
        return 0;
    }
    ll l,r;
    if(n/2%2){
    if(s==t){
        l=0,r=n/2;
    }else{
        l=n/2;
        r=n-1;
        cout<<n-1<<endl;
        cin>>s;
        if(s=="Vacant"){
            return 0;
        }
        swap(s,t);
    }
    }else{
        if(s!=t){
        l=0,r=n/2;
    }else{
        l=n/2;
        r=n-1;
        cout<<n-1<<endl;
        cin>>s;
        if(s=="Vacant"){
            return 0;
        }
        swap(s,t);
    }
    }
    while(1){
        ll mid=(r+l)/2;
        cout<<mid<<endl;
        string d;
        cin>>d;
        if(d=="Vacant"){
            return 0;
        }
        if((mid-l)%2){
            if(d==s){
                r=mid;
                t=d;
            }else{
                l=mid;
                s=d;
            }
        }else{
            if(d==s){
                l=mid;
                s=d;
            }else{
                r=mid;
                t=d;
            }
        }
    }
}

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using Graph = vector<vector<int>>;
const ll mod=1000000007;
const int MAX_N = 1000;         // n の最大値

// nCk を取得
double nCk(int n, int k) {
double res=1.0;
for(int i=0; i<n; i++){
res*=0.5;}
for(int i=0; i<k; i++){
res*=(double)(n-i);
res/=(double)(k-i);
}
return res;}

int main() {
ll h,w,n;
cin>>h>>w>>n;
ll ans=0;
if(h>w){
if(n%h==0){
ans = n/h;}
else{
ans = n/h +1;}}
else{
if(n%w==0){
ans = n/w;}
else{
ans = n/w +1;}}
cout << ans << endl;}


#include <bits/stdc++.h>
#ifdef LOCAL_DEBUG
#define DEBUG 1
#define CERR if(DEBUG) cerr
#define MACRO(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,NAME,...) NAME
#define pr(...) CERR<<MACRO(__VA_ARGS__,pr10,pr9,pr8,pr7,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__)<<endl
#define pr1(a) (#a)<<"="<<(a)<<" "
#define pr2(a,b) pr1(a)<<pr1(b)
#define pr3(a,b,c) pr1(a)<<pr2(b,c)
#define pr4(a,b,c,d) pr1(a)<<pr3(b,c,d)
#define pr5(a,b,c,d,e) pr1(a)<<pr4(b,c,d,e)
#define pr6(a,b,c,d,e,f) pr1(a)<<pr5(b,c,d,e,f)
#define pr7(a,b,c,d,e,f,g) pr1(a)<<pr6(b,c,d,e,f,g)
#define pr8(a,b,c,d,e,f,g,h) pr1(a)<<pr7(b,c,d,e,f,g,h)
#define pr9(a,b,c,d,e,f,g,h,i) pr1(a)<<pr8(b,c,d,e,f,g,h,i)
#define pr10(a,b,c,d,e,f,g,h,i,j) pr1(a)<<pr9(b,c,d,e,f,g,h,i,j)
#define prArr(a){CERR<<(#a)<<"={";int i=0;for(auto t:(a))CERR<<(i++?", ":"")<<t;CERR<<"}"<<endl;}
#else
#define DEBUG 0
#define pr(...)
#define prArr(a)
#endif
using namespace std;
using Int = long long;
using _int = int;
using ll = long long;
using Double = long double;
const Int INF = (1LL<<60)+1e9; // ~ 1.15 * 1e18
const Int mod = (1e9)+7;
const Double EPS = 1e-8;
const Double PI = 6.0 * asin((Double)0.5);
using P = pair<Int,Int>;
template<class T> T Max(T &a,T b){return a=max(a,b);}
template<class T> T Min(T &a,T b){return a=min(a,b);}
template<class T1, class T2> ostream& operator<<(ostream& o,pair<T1,T2> p){return o<<"("<<p.first<<","<<p.second<<")";}
template<class T1, class T2, class T3> ostream& operator<<(ostream& o,tuple<T1,T2,T3> t){return o<<"("<<get<0>(t)<<","<<get<1>(t)<<","<<get<2>(t)<<")";}
template<class T1, class T2> istream& operator>>(istream& i,pair<T1,T2> &p){return i>>p.first>>p.second;}
template<class T> ostream& operator<<(ostream& o,vector<T> a){Int i=0;for(T t:a)o<<(i++?" ":"")<<t;return o;}
template<class T> istream& operator>>(istream& i,vector<T> &a){for(T &t:a)i>>t;return i;}
//INSERT ABOVE HERE

Int sim(vector<Int> A){
  Int N = A.size();
  Int k = 0;
  while(1){
    Int idx = 0;
    for(Int i=0;i<N;i++) if(A[idx] < A[i]) idx = i;
    if(A[idx] < N) return k;
    k++;
    for(Int i=0;i<N;i++) A[i]++;
    A[idx] -= (N + 1);
    pr(k, A);
  }
}

vector<Int> sim(vector<Int> A, Int K){
  Int N = A.size();
  for(Int i=0;i<K;i++){
    Int idx = 0;
    for(Int i=0;i<N;i++) if(A[idx] < A[i]) idx = i;
    for(Int i=0;i<N;i++) A[i]++;
    A[idx] -= (N + 1);
  }
  return A;
}
signed main(){
  srand((unsigned)time(NULL));
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  if(0){
    Int N;
    cin>>N;
    vector<Int> A(N);
    cin>>A;

    sim(A);
  }

  Int K;
  cin>>K;

  Int n = 50;
  vector<Int> ans(n, 0);
  for(Int i=0;i<n;i++){
    ans[i] = ((K-1) / n + 1) + n - 1;
  }
  ans = sim(ans, (n - K % n) % n);
  if(K == 0) ans = vector<Int>(n, 0);
  cout<<n<<endl;
  cout<<ans<<endl;
  //assert(sim(ans) == K);
  return 0;
}

/*First observation is that little numbers should be summed up to go to above 3
 * any number above 3 is better multiplied
 * also given a set of numbers to add, the best pairs to pick are least with most since we will multiply them next
 * also if the number of numbers we are going to add is N
 * then the numbers we will add are the first N numbers given that the array is sorted
 * so we just bruteforce on N
 *
 */

#include <bits/stdc++.h>
#include <complex>

using namespace std;
typedef long long int ll;

const double PI = acos(-1);
const int N = 2e6, MOD = 1e6 + 3, LOG = 21;

ll k, mvup, toAdd;
bool chn = false;
vector<ll> v;

int main() {
	//freopen("input.txt", "r", stdin);
	scanf("%lld", &k);
	while (k % 50 != 0) {
		k++;
		mvup++;
	}
	ll N = 50;
	ll base = N - 1;
	ll needed = k / N;
	printf("%lld\n", N);
	for (int i = 0; i < N; i++) {
		v.push_back(base + needed);
	}
	toAdd = mvup;
	for (int i = 0; i < N; i++) {
		if (mvup) {
			v[i] -= N;
			mvup--;
			v[i] += (toAdd - 1);
		} else {
			v[i] += toAdd;
		}
	}
	for (int i = 0; i < N; i++) {
		printf("%lld ", v[i]);
	}
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

template <typename T>
T random(T lo, T hi) {
  std::random_device rd;
  std::uniform_int_distribution<T> uid(lo, hi);
  return uid(rd);
}

class RollingHash {
 private:
  const uint64_t mod = (UINT64_C(1) << 61) - 1;
  static inline uint64_t base = random(UINT32_C(10007), UINT32_MAX);
  std::vector<uint64_t> hashes, pows;

  inline uint64_t add(uint64_t a, uint64_t b) const {
    a += b;
    if (a >= mod) a -= mod;
    return a;
  }

  inline uint64_t sub(uint64_t a, uint64_t b) const {
    if (a < b) a += mod;
    a -= b;
    return a;
  }

  inline uint64_t mul(uint64_t a, uint64_t b) const {
    uint64_t ah = a >> 31, al = a & ((UINT64_C(1) << 31) - 1), bh = b >> 31,
             bl = b & ((UINT64_C(1) << 31) - 1), m = ah * bl + al * bh,
             v = (ah * bh << 1) + (m >> 30) +
                 ((m & ((UINT64_C(1) << 30) - 1)) << 31) + al * bl;
    v = (v & ((UINT64_C(1) << 61) - 1)) + (v >> 61);
    return v;
  }

 public:
  template <typename T>
  RollingHash(const T &S) : hashes(S.size() + 1, 0), pows(S.size() + 1, 0) {
    pows[0] = 1;
    for (size_t i = 0; i < S.size(); i++) {
      pows[i + 1] = mul(pows[i], base);
      hashes[i + 1] = add(mul(hashes[i], base), S[i]);
    }
    // cout << base << '\n';
  }

  // S[l, r)
  uint64_t slice(int l, int r) const {
    return sub(hashes[r], mul(hashes[l], pows[r - l]));
  }
};

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int N;
  cin >> N;
  vector<int> A(N), B(N);
  for (int i = 0; i < N; i++) {
    cin >> A[i];
  }
  for (int i = 0; i < N; i++) {
    cin >> B[i];
  }
  vector<int> S(N), T(N);
  for (int i = 0; i < N; i++) {
    S[i] = A[i] ^ A[(i + 1) % N];
    T[i] = B[i] ^ B[(i + 1) % N];
  }
  for (int i = 0; i < N; i++) {
    S.emplace_back(S[i]);
  }
  RollingHash rhs(S), rht(T);
  for (int i = 0; i < N; i++) {
    if (rhs.slice(i, i + N) == rht.slice(0, N)) {
      cout << i << ' ' << (A[i] ^ B[0]) << '\n';
    }
  }
  return 0;
}

#include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define INF 2e9
#define MOD 1000000007
#define ALL(v) v.begin(), v.end()
#define sz(x) int(x.size())
using namespace std;
typedef long long ll;
using P = pair<int,int>;

int main()
{
  int N;
  cin >> N;
  vector<int> A(N);
  REP(i, N) cin >> A[i];
  int flag = (A[0]!=0);
  REP(i,N-1){
    if(A[i]+2<=A[i+1]){
      flag=1;
    }
  }
  if(flag==1){
    cout << -1 << endl;
  }else{
    ll ans = 0;
    A.push_back(0);
    REP(i,N){
      if((A[i]>=A[i+1])){
        ans+=A[i];
      }
    }

    cout << ans << endl;
  }
}