#include<iostream>
#include<cctype>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<cctype>
#include<cstring>
#include<utility>
const int inf=0x7fffffff;
typedef long long int ll;
using namespace std;
const int N=100+5;
char s[100+10];
char ans[][10]={
	"No\n",
	"Yes\n"
};
struct DICE{
	int u,s,e,w,n,d;
	DICE (int u=0,int s=0,int e=0,int w=0,int n=0,int d=0):u(u),s(s),e(e),w(w),n(n),d(d){}
	DICE fW(){
		DICE tmp;
		tmp.s=this->s;
		tmp.n=this->n;
		tmp.e=this->d;
		tmp.w=this->u;
		tmp.u=this->e;
		tmp.d=this->w;
		return tmp;
	}
	DICE fS(){
		DICE tmp;
		tmp.s=this->u;
		tmp.n=this->d;
		tmp.e=this->e;
		tmp.w=this->w;
		tmp.d=this->s;
		tmp.u=this->n;
		return tmp;
	}
	DICE fE(){
		DICE tmp;
		tmp.s=this->s;
		tmp.n=this->n;
		tmp.e=this->u;
		tmp.w=this->d;
		tmp.d=this->e;
		tmp.u=this->w;
		return tmp;
	}
	DICE fN(){
		DICE tmp;
		tmp.s=this->d;
		tmp.n=this->u;
		tmp.e=this->e;
		tmp.w=this->w;
		tmp.d=this->n;
		tmp.u=this->s;
		return tmp;
	}
	int right(int t,int f){
		if(t==this->u)
		{
			if(f==this->s)return this->e;
			else if(f==this->e)return this->n;
			else if(f==this->n)return this->w;
			else if(f==this->w)return this->s;
			else return -1;
		}
		else if(t==this->s){
			DICE tmp=(*this).fN();
			return tmp.right(t,f);
		}
		else if(t==this->e){
			DICE tmp=(*this).fW();
			return tmp.right(t,f);
		}
		else if(t==this->n){
			DICE tmp=(*this).fS();
			return tmp.right(t,f);
		}
		else if(t==this->w){
			DICE tmp=(*this).fE();
			return tmp.right(t,f);
		}
		else if(t==this->d){
			DICE tmp=(*this).fE().fE();
			return tmp.right(t,f);
		}
		else return -1;
		}
};
DICE A[N];
bool check(DICE x,DICE y){
	int ax[]={
		x.s,x.e,x.n,x.w
	};
	int ay[]={
		y.s,y.e,y.n,y.w
	};
	if(x.u==y.u){
		if(x.d==y.d){
			int cnt=0;
			while(cnt<=4){
				while(ax[cnt]!=ay[0]&&cnt<=4)
					cnt++;
				int i=0;
				while(ax[(i+cnt)%4]==ay[i]&&i<=4)
					i++;
				if(i==4)return 1;
				cnt++;
			}

		}
	}
	return 0;
}
bool sovle(DICE x,DICE y){
	if(check(x,y))return 1;
	if(check(x.fE(),y))return 1;
	if(check(x.fW(),y))return 1;
	if(check(x.fN(),y))return 1;
	if(check(x.fS(),y))return 1;
	if(check(x.fS().fS(),y))return 1;
	return 0;
}
int main()
{
//#ifdef DEBUG
//	freopen("in", "r", stdin);
////	freopen("out", "w", stdout);
//#endif
	int n;scanf("%d", &n);
	int t=0;
	int a[6];
	bool flag=1;
	for(int i=0;i<6;i++){
		scanf("%d", &a[i]);
	}
	A[0]=DICE(a[0],a[1],a[2],a[3],a[4],a[5]);
	t++;
	while(t<n){
	for(int i=0;i<6;i++){
		scanf("%d", &a[i]);
	}
	A[t]=DICE (a[0],a[1],a[2],a[3],a[4],a[5]);
	for(int i=0;i<t;i++)
	{
		if(sovle(A[i],A[t])){flag=0;
//			cout<<i<<' '<<t<<endl;
		}
	}
	t++;
	}
	printf("%s", ans[flag]);
//	printf("%s", ans[solve(dice,dice2)]);
//	DICE I
//	scanf("%s", s);
//	int len=strlen(s);
//	for(int i=0;i<len;i++){
//		switch(s[i]){
//			case'S':dice=dice.fS();break;
//			case'E':dice=dice.fE();break;
//			case'W':dice=dice.fW();break;
//			case'N':dice=dice.fN();break;
//		}
//	}
//	printf("%d\n", dice.u);
//
	return 0;
}
//aoj1_11_a.cc

//AC

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

class Dice{
	int dn[6];
	int ori[6];
	int up, front;
	string qu;

public:
	Dice(int d1, int d2, int d3, int d4, int d5, int d6){
		dn[0] = d1;
		dn[1] = d2;
		dn[2] = d3;
		dn[3] = d4;
		dn[4] = d5;
		dn[5] = d6;

		ori[0] = d1;
		ori[1] = d2;
		ori[2] = d3;
		ori[3] = d4;
		ori[4] = d5;
		ori[5] = d6;
	}

	void Result(string m){
		int w;
		qu = m;
		for (int i = 0; i < 6; i++){
			dn[i] = ori[i];
		}

		for (int i = 0; i < qu.size(); i++){
			switch (qu[i]){
			case 'E':
				w = dn[0];
				dn[0] = dn[3];
				dn[3] = dn[5];
				dn[5] = dn[2];
				dn[2] = w;
				break;

			case 'N':
				w = dn[5];
				dn[5] = dn[4];
				dn[4] = dn[0];
				dn[0] = dn[1];
				dn[1] = w;
				break;

			case 'S':
				w = dn[0];
				dn[0] = dn[4];
				dn[4] = dn[5];
				dn[5] = dn[1];
				dn[1] = w;
				break;

			case 'W':
				w = dn[0];
				dn[0] = dn[2];
				dn[2] = dn[5];
				dn[5] = dn[3];
				dn[3] = w;
				break;
			}
		}
	}

	int get0(){
		return dn[0];
	}
	int get1(){
		return dn[1];
	}
	int get2(){
		return dn[2];
	}
	int get3(){
		return dn[3];
	}
	int get4(){
		return dn[4];
	}
	int get5(){
		return dn[5];
	}
};

int main()
{
	int n;
	int count = 0;
	int ndice[100][6];
	string flag = "Yes";
	string quu[23] = { "WSE", "ESW", "WSSE", "SWW", "EN", "WN", "N", "SW", "W", "SSW",
		"NW", "SE", "E", "SSE", "NE", "S", "WS", "ES", "WWS", "WW", "SWS", "SES", "SS" };

	cin >> n;
	for (int i = 0; i < n; i++){          // n個のサイコロの入力
		for (int j = 0; j < 6; j++){
			cin >> ndice[i][j];
		}
	}

	for (int i = 0; i < n; i++){                // サイコロを比べる
		for (int j = i + 1; j < n; j++){                      // Dice a()にサイコロを登録し、順次比較していく
			Dice a(ndice[j][0], ndice[j][1], ndice[j][2],
				ndice[j][3], ndice[j][4], ndice[j][5]);

			for (int k = 0; k < 6; k++){            // 転がすこともなく同じサイコロかどうか
				if (ndice[i][k] == ndice[j][k]){
					count = count + 1;
				}
			}
			if (count == 6){     // 6面全てが一致すれば、同じサイコロ
				flag = "No";
			}
			count = 0;

			for (int l = 0; l < 23; l++){     // サイコロが取り得る全ての可能性(面の上下左右)を比較していく
				a.Result(quu[l]);

				ndice[j][0] = a.get0();
				ndice[j][1] = a.get1();
				ndice[j][2] = a.get2();
				ndice[j][3] = a.get3();
				ndice[j][4] = a.get4();
				ndice[j][5] = a.get5();

				for (int k = 0; k < 6; k++){               // 6面全てが一致すれば、同じサイコロ
					if (ndice[i][k] == ndice[j][k]){
						count = count + 1;
					}
				}
				if (count == 6){
					flag = "No";
				}
				count = 0;
			}
		}
	}
	cout << flag << endl;

	return 0;
}


#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#define re(c, b) for(ll c=0;c<b;c++)
using namespace std;

int main() {
  int h, w;scanf("%d %d", &h, &w);
  vector<string> s(h);
  for(int i=0;i<h;i++) std::cin >> s[i];
  vector<set<int>> spl(w);
  for(int i=w-1;i>=1;i--){
    int mode = (s[0][i]==s[0][i-1]);
    for(int j=1;j<h;j++){
      if(mode==(s[j][i]==s[j][i-1])) continue;
      mode = (s[j][i]==s[j][i-1]);
      spl[i].insert(j-1);
    }
  }

  vector<int> las(h, -1);
  int ans = 0;
  for(int j=w-1;j>=0;j--){
    int tmp = h;
    map<int, int> L;
    map<int, int> rev; // 長さ、個数
    L.emplace(0, h);
    rev.emplace(h, 1);

    for(int i=1;i+j<w;i++){
      for(auto t:spl[i+j]){
        auto itr = --L.upper_bound(t);
        int x_len = t - (*itr).first + 1;
        int y_len = (*itr).first + (*itr).second - 1 - t;

        auto x = rev.find((*itr).second);
        if((*x).second==1) rev.erase(x);
        else (*x).second--;

        (*itr).second = x_len;
        L.emplace(t+1, y_len);

        x = rev.find(x_len);
        if(x==rev.end()) rev.emplace(x_len, 1);
        else (*x).second++;

        x = rev.find(y_len);
        if(x==rev.end()) rev.emplace(y_len, 1);
        else (*x).second++;
        //rev.insert(x_len);
        //rev.insert(y_len);
      }
      auto itr = (--rev.end());
      tmp = max((*itr).first*(i+1), tmp);
    }
    ans = max(ans, tmp);
    for(auto i:spl[j]){
      if(las[i]!=-1) spl[las[i]].erase(i);
      las[i] = j;
    }
  }
  std::cout << ans << '\n';
  return 0;
}

#include<bits/stdc++.h>
#define ll int
#define ld long double
#define pb push_back
#define mp make_pair
#define F first
#define S second

using namespace :: std;

const ll maxn=2010;

char jad[maxn][maxn];
ll ava[maxn];
ll l[maxn];
ll r[maxn];

ll finds(ll n){
	stack<ll> stk;
	for(ll i=0;i<n;i++){
		while(!stk.empty() && ava[stk.top()]>=ava[i]){
			stk.pop();
		}
		if(stk.empty()){
			l[i]=-1;
		}else{
			l[i]=stk.top();
		}
		stk.push(i);
	}
	while(!stk.empty()){
		stk.pop();
	}
	for(ll i=n-1;i>=0;i--){
		while(!stk.empty() && ava[stk.top()]>=ava[i]){
			stk.pop();
		}
		if(stk.empty()){
			r[i]=n;
		}else{
			r[i]=stk.top();
		}
		stk.push(i);
	}
	ll ans=0;
	for(ll i=0;i<n;i++){
		ans=max(ans,(ava[i]+1)*(r[i]-l[i]));
	}
	return ans;
}
bool good(ll i,ll j){
	int t=0;
	if(jad[i][j]=='#'){
		t^=1;
	}
	if(jad[i+1][j]=='#'){
		t^=1;
	}
	if(jad[i][j+1]=='#'){
		t^=1;
	}
	if(jad[i+1][j+1]=='#'){
		t^=1;
	}
	if(t&1){
		return 0;
	}
	return 1;
}
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);

	ll w,h;
	cin>>w>>h;
	for(ll i=0;i<w;i++){
		for(ll j=0;j<h;j++){
			cin>>jad[i][j];
		}
	}
	ll ans=w;
	for(ll i=0;i<w-1;i++){
		for(ll j=0;j<h-1;j++){
			if(good(i,j)){
				ava[j]++;
			}else{
				ava[j]=0;
			}
		}
		ans=max(ans,finds(h-1));
	}

	cout<<ans;

}


#include <bits/stdc++.h>
#define Inf 0x3f3f3f3f
#define rg register
using std::cin;
using std::cout;
const int Maxn = 2e7 + 5, Mod = 998244353;
typedef long long ll;
typedef ll arr[Maxn];
ll Add(ll x, ll y) { return (x += y) >= Mod ? x - Mod : (x < 0 ? x + Mod : x); }
ll min(ll x, ll y) { return x < y ? x : y; }
ll max(ll x, ll y) { return x > y ? x : y; }
inline ll read()
{
	rg ll res = 0, sign = 1;
	rg char ch = getchar();
	while (!isdigit(ch))
	{
		if (ch == '-')
			sign = -1;
		ch = getchar();
	}
	do
	{
		res = (res << 3) + (res << 1) + (ch ^ 48);
		ch = getchar();
	} while (isdigit(ch));
	return res * sign;
}
int n, m;
arr fac, inv, invfac;
ll ans;
ll qp(ll x, int y)
{
	ll res = 1;
	while (y)
	{
		if (y & 1)
			res = res * x % Mod;
		x = x * x % Mod;
		res >>= 1;
	}
	return res;
}
ll C(int x, int y) { return fac[x] * invfac[y] % Mod * invfac[x - y] % Mod; }
int main()
{
	fac[0] = inv[1] = invfac[0] = 1;
	for (rg int i = 1; i <= 20000000; i++)
	{
		fac[i] = fac[i - 1] * i % Mod;
		if (i > 1)
			inv[i] = (Mod - Mod / i) * inv[Mod % i] % Mod;
		invfac[i] = invfac[i - 1] * inv[i] % Mod;
	}
	rg int tmp;
	cin >> n >> m;
	ans = 1;
	for (rg int i = 1; i < n; i++)
		ans = ans * (3 * m + i) % Mod;
	ans = ans * invfac[n - 1] % Mod;
	ans = Add(ans, -(n * C(m - 1 + n - 1, n - 1) % Mod));
	if (n > m)
	{
		tmp = min(3 * m, n);
		for (rg int i = m + 2; i <= tmp; i += 2)
			ans = Add(ans, -(C(n, i) * C((3 * m - i) / 2 + n - 1, n - 1) % Mod));
	}
	cout << ans << '\n';
	return 0;
}

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

    //                                 (POLICY BASED DS)
    // #include <ext/pb_ds/assoc_container.hpp>
    // #include <ext/pb_ds/tree_policy.hpp>
    // using namespace __gnu_pbds;
    // template<typename T>
    // using ordered_set=tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
    // template<typename T>
    // using ordered_multiset=tree<T,null_type,less_equal<T>,rb_tree_tag,tree_order_statistics_node_update>;
    //                      ( find_by_order( )  ,  order_of_key( ) )

    typedef long long ll;
    typedef long double ld;
    typedef unsigned long long ull;
    typedef vector<int> vi;
    typedef vector<long long> vll;
    typedef pair<ll,ll> pll;

    const ll mod = 1e9 + 7;
    const ld PI = 3.1415926535897932384626;
    const ld eps = 1e-9;

    #define boost ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
    #define sidha(i,a,b) for(ll i=(ll)(a);i<(ll)(b);++i)
    #define ulta(i,a,b) for(ll i=(ll)(a);i>=(ll)(b);--i)
    #define stl(container,itr) \
        for(auto itr = container.begin(); itr != container.end(); itr++)
    #define sab(v) v.begin(), v.end()
    #define rall(v) v.rbegin(), v.rend()
    #define test ll t;cin>>t;while(t--)
    #define sz size()
    #define pb push_back
    #define mp make_pair
    #define fi first
    #define se second
    #define LOG2(X) (63ll - __builtin_clzll(X))
    #define endl '\n'
    #define modinv(x) power(x, mod-2)
    #define ncr(n,r) ( n >= r ? ((((fact[n]*modinv(fact[r]))%mod)*modinv(fact[n-r]))%mod) : (ll)0)
    #define MAX 100005

    ll power(ll x, ll y) {
        ll ans=1;
        x=x%mod;
        while(y>0) {
            if (y&1)
                ans=(ans*x)%mod;
            y=y>>1;
            x=(x*x)%mod;
        }
        return ans;
    }

    // vector<ll> adj[MAX];
    // ll visit[MAX];
    // void dfs(ll node){
    //     visit[node]=1;
    //     for(auto i : adj[node]){
    //         if(!visit[i]) dfs(i);
    //     }
    // }

    // ll spf[MAX];
    // void sieve(){
    //     sidha(i,1,MAX)  spf[i]=i;
    //     for(ll i=4;i<MAX;i+=2)  spf[i]=2;
    //     for(ll i=3;i*i<=MAX;i++){
    //         if(spf[i]==i){
    //             for(ll j=i*i;j<MAX;j+=i){
    //                 if(spf[j]==j)   spf[j]=i;
    //             }
    //         }
    //     }
    // }

    int main()
    {
        boost;
        ll n,count=0,ans=0;
        cin>>n;
        ll arr[n],suff[n];
        sidha(i,0,n)    cin>>arr[i];
        ulta(i,n-1,0){
            suff[i]=count;
            count=((count+arr[i])%mod);
        }
        sidha(i,0,n){
            ans=((ans+((arr[i]*suff[i])%mod))%mod);
        }
        cout<<ans;
        return 0;
    }


#pragma region header
#include <bitset>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <cctype>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <limits>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <math.h>
using namespace std;
#define int long long
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i <= (int)(n); i++)
#define rev(i, n) for(int i = (int)(n - 1); i >= 0; i--)
#define rev1(i, n) for(int i = (int)(n); i > 0; i--)
#define pb push_back
#define all(v) (v).begin(), (v).end()
#define resort(v) sort((v).rbegin(), (v).rend())
#define vi vector<int>
#define vvi vector<vector<int>>
#define vs vector<string>
#define vvs vector<vector<string>>
#define vc vector<char>
#define vvc vector<vector<char>>
#define vb vector<bool>
#define vvb vector<vector<bool>>
using ll = long long;
using P = pair<int, int>;
/* ----------------よく使う数字や配列----------------- */
int dx[] = { 1,0,-1,0 };
int dy[] = { 0,1,0,-1 };
constexpr ll mod = 1e9 + 7;
constexpr ll inf = INT32_MAX / 2;
constexpr ll INF = LLONG_MAX / 2;
constexpr long double eps = DBL_EPSILON;
constexpr long double pi = 3.141592653589793238462643383279;
signed main() {
    string S;
    cin >> S;
    int size = S.size();
    vector<int> date;
    rep(i, S.size() - 2) {
        string suuji=(S.substr(i, 3));
        int a=stoi(suuji);
        int b = abs(753 - a);
        date.push_back(b);
    }
    sort(date.begin(), date.end());
    cout << abs(date.at(0)) << endl;
}

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

int main(){
    string s;
    cin >> s;

    bool flg = true;
    int c_cnt = 0;
    for(int i=0; i<s.length(); i++){
        if(i==0){
            if(s.at(i)!= 'A'){
                flg = false; break;
            }
        }else if(isupper(s.at(i))){
            if(i==1 || i==s.length()-1 || s.at(i) != 'C'){
                flg = false; break;
            }
            c_cnt++;
        }
    }
    if(c_cnt != 1)
        flg = false;

    if(flg) cout << "AC" << endl;
    else cout << "WA" << endl;

    return 0;
}


#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<string>
#include<sstream>
#include<iomanip>
#include<utility>
#include<cmath>
#include<set>
#include<list>
#include<queue>
#include<stack>
#include<map>
#include<set>
using namespace std;
typedef long long int ll;
const int MAX=100000;
const int INFTY=1<<30;

int n,col[MAX],d[MAX];
vector<pair<int,int>> Q[MAX];//target,weight

void dijkstra(int s)
{
	priority_queue<pair<int,int>> PQ;//weight,id
	for(int i=0;i<n;i++)
	{
		d[i]=INFTY;
		col[i]=0;
	}
	d[s]=0;
	PQ.push(make_pair(0,s));
	col[s]=1;

	while(!PQ.empty())
	{
		pair<int,int> f=PQ.top();PQ.pop();
		int u=f.second;
		col[u]=2;
		if(d[u]<f.first*(-1))continue;
		for(int j=0;j<Q[u].size();j++)
		{
			int v=Q[u][j].first;
			if(col[v]==2)continue;
			if(d[u]+Q[u][j].second<d[v])
			{
				d[v]=d[u]+Q[u][j].second;
				PQ.push(make_pair(d[v]*(-1),v));
				col[v]=1;
			}
		}
	}

	for(int i=0;i<n;i++)
	{
		if(d[i]==INFTY)cout<<"INF"<<endl;
		else cout<<d[i]<<endl;
	}

	return;
}

int main()
{
	cin>>n;
	int u;int m;cin>>m>>u;
	int s,t,w;
	for(int i=0;i<m;i++)
	{
		cin>>s>>t>>w;
		Q[s].push_back(make_pair(t,w));
	}
	dijkstra(u);
	return 0;
}

#define _CRT_SECURE_NO_WARNINGS
// #define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
#define all(c) begin(c), end(c)
#define range(i,a,b) for(int i = a; i < (int)(b); i++)
#define rep(i,b) range(i,0,b)
#define eb emplace_back
typedef long long ll;
#define int ll
auto const inf = numeric_limits<int>::max()/4;

using Weight = int;
using Capacity = int;
struct Edge {
    int src, dst; Weight weight;
    Edge(int s, int d, int w) : src(s), dst(d), weight(w) {}
};
using Edges = vector<Edge>;
using Graph = vector<Edges>;
using Array = vector<Weight>;
using Matrix = vector<Array>;

pair<vector<Weight>, bool> spfa(const Graph &g, int s){
    const Weight inf = numeric_limits<Weight>::max()/4;
    const int n = g.size(); priority_queue<int> q;
    vector<Weight> dist(n, inf); vector<int> inQ(n);
    vector<int> count(n);
    dist[s] = 0; q.emplace(s); inQ[s] = true; ++count[s];
    bool negCycle = false;
    for(int i = 0; q.size(); i++){
        int v = q.top(); q.pop(); inQ[v] = false;
        for(auto &e : g[v]){
            if(dist[v] != inf && dist[e.dst] > dist[v] + e.weight){
                dist[e.dst] = dist[v] + e.weight;
                if(!inQ[e.dst]){
                    q.emplace(e.dst); inQ[e.dst] = true; ++count[e.dst];
                    if(count[e.dst] >= n){ negCycle = true; goto END; }
                }
            }
        }
    }
 END:;
    return make_pair(dist, !negCycle);
}

signed main(){
    int V,E,r;
    while(cin >> V >> E >> r){
        Graph g(V);
        rep(i,E){
            int a,b,c;
            cin >> a >> b >> c;
            g[a].eb(a,b,c);
        }
        bool ok;
        vector<Weight> dist;
        tie(dist, ok) = spfa(g,r);
        if(ok){
            for(int i = 0; i < (int)dist.size(); i++){
                if(dist[i] == inf) cout << "INF";
                else cout << dist[i];
                cout << endl;
            }
        } else {
            cout << "NEGATIVE CYCLE" << endl;
        }
    }
}


#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#define debug(a) cout << "*" << a << "*" << endl
using namespace std;
typedef long long ll;
char mp[50][101];
int m, n;
void fill_mp(int num, int x, char ch)
{
	for (int i = x; ; i += 2)
	{
		for (int j = 0; j < 100; j += 2)
		{
			if (num == 0)	return;
			mp[i][j] = ch;
			num--;
		}
	}
}
int main()
{
	while (~scanf("%d%d", &m, &n))
	{
		for (int i = 0; i < 25; i++)
		{
			memset(mp[i], '#', sizeof(mp[i]));
		}
		for (int i = 25; i < 50; i++)
		{
			memset(mp[i], '.', sizeof(mp[i]));
		}
		for (int i = 0; i < 50; i++)	mp[i][100] = 0;
		m--, n--;
		fill_mp(m, 0, '.'), fill_mp(n, 26, '#');
		printf("50 100\n");
		for (int i = 0; i < 50; i++)	printf("%s\n", mp[i]);
	}
}

#include<bits/stdc++.h>
#define rep(i,n) for (int i=0; i<n; i++)
#define REP(i,x,n) for (int i=x; i<n; i++)
using namespace std;
using vi = vector<int>;
using vvi = vector<vi>;
using ll = long long;

int main(){
  int n;
  cin >> n;
  string s;
  cin >> s;
  vi v1(n);
  rep(i,n){
    if (i == 0){
      v1.at(i) = 0;
      continue;
    }
    v1.at(i) += v1.at(i-1) ;
    if (s.at(i-1) == 'W') v1.at(i)++;
  }
  vi v2(n);
  rep(i,n){
    if (i == 0){
      v2.at(i) = 0;
      continue;
    }
    v2.at(i) += v2.at(i-1);
    if (s.at(n-i) == 'E') v2.at(i)++;
  }
  vi v3(n);
  rep(i,n){
    v3.at(i) = v1.at(i) + v2.at(n-1-i);
  }
  sort(v3.begin(),v3.end());
  cout << v3.at(0) << endl;
  return 0;
}


#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <string>
#include <cmath>
#include <iomanip>
#include <map>
#include <set>
#include <numeric>
#include <queue>
using namespace std;
#define loop(i,N) for(ll (i)=0; (i)<(N);++(i))
struct TEMP_OMAZINAI_ { TEMP_OMAZINAI_() { std::ios::sync_with_stdio(false); std::cin.tie(0); } } TEMP__omazinai_instance__;
#define INF ((1LL<<61) + (1<<29))
#define YesNo(x) {std::cout << ((x)?"Yes":"No") << std::endl;}
#define YESNO(x) {std::cout << ((x)?"YES":"NO") << std::endl;}
#define OddEven(x) {std::cout << ((x)%2?"Odd":"Even") << std::endl;}
#define ODDEVEN(x) {std::cout << ((x)%2?"ODD":"EVEN") << std::endl;}
typedef long long int ll;
ll my_gcd(ll a, ll b) { return b ? my_gcd(b, a%b) : a; };
void TEMP_INPUT_IMPL_() {};
template <class T, class... Args> void TEMP_INPUT_IMPL_(T& dest, Args&... args) { cin >> dest; TEMP_INPUT_IMPL_(args...); }
void TEMP_OUTPUT_IMPL_() {};
template <class T, class... Args> void TEMP_OUTPUT_IMPL_(T dest, Args... args) { cout << dest << (sizeof...(Args) ? " " : ""); TEMP_OUTPUT_IMPL_(args...); }
#define in(type, ...) type __VA_ARGS__; TEMP_INPUT_IMPL_(__VA_ARGS__)
#define in_v(type, name, cnt) vector<type> name(cnt); loop(i, cnt) cin >> name[i];
#define sort_v(v) std::sort(v.begin(), v.end())
#define rsort_v(v) std::sort(v.rbegin(), v.rend())
#define unique_v(v) v.erase(std::unique(v.begin(), v.end()), v.end()) //必ずソート後に実行
#define out(...) (TEMP_OUTPUT_IMPL_(__VA_ARGS__), std::cout<<std::endl)
#define set_fix(x) ((std::cerr<<std::fixed<<std::setprecision(x)),(std::cout<<std::fixed<<std::setprecision(x)))
//小さい方に寄る
#define space_op(x, y, a, b, c) ([](auto x_, auto y_, auto a_, auto b_, auto c_){if(x_<y_)return a_;if(x_>y_)return c_;return b_;}(x,y,a,b,c))
#define space_out(x, y, a, b, c) out(space_op(x, y, a, b, c))

 // ^^^ Template ^^^ //

struct UnionFind{
	vector<ll> parent;
	vector<ll> size;
	UnionFind() = delete;
	UnionFind(ll n) : parent(n), size(n, 1){
		loop(i, n)
			parent[i] = i;
	}

	int find(ll x) {
		if(parent[x] == x) return x;
		return parent[x] = find(parent[x]);
	}

	void unite(ll x_, ll y_){
		ll x = find(x_);
		ll y = find(y_);
		if(x==y) return ;
		if(size[x] < size[y]) swap(x, y);
		parent[y] = x;
		size[x] += size[y];
	}

	bool same(ll x, ll y){
		return find(x) == find(y);
	}
};

int main() {
	in(ll, N);
	vector<pair<ll, ll>> xv(N), yv(N);
	vector<pair<ll, pair<ll, ll>>> ev;
	ev.reserve(N*3);
	//set<ll> u;
	ll ans = 0;
	loop(i, N){
		in(ll, x, y);
		xv[i] = {x, i};
		yv[i] = {y, i};
	}
	sort_v(xv);
	sort_v(yv);
	loop(i, N-1){
		// x
		ev.push_back({
			xv[i+1].first - xv[i].first,
			make_pair(xv[i].second, xv[i+1].second)
		});
		ev.push_back({
			xv[i+1].first - xv[i].first,
			make_pair(xv[i+1].second, xv[i].second)
		});
		// y
		ev.push_back({
			yv[i+1].first - yv[i].first,
			make_pair(yv[i].second, yv[i+1].second)
		});
		ev.push_back({
			yv[i+1].first - yv[i].first,
			make_pair(yv[i+1].second, yv[i].second)
		});
	}
	sort_v(ev);
	UnionFind uf(N);
	for(auto e : ev){
		if(!uf.same(e.second.first, e.second.second)){
			ans += e.first;
			uf.unite(e.second.first, e.second.second);
		}
	}
	out(ans);
}

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

typedef long long ll;

ll N;
typedef tuple<ll, ll, ll> Point;
vector<Point> Points[2];
typedef tuple<ll, ll, ll> Edge;
vector<Edge> Edges;
vector<ll> Parent, Rank;
ll R;

void init() {
  Parent.resize(N, -1);
  Rank.resize(N, 0);
}
ll root(ll v) {
  if (Parent[v] == -1) return v;
  return Parent[v] = root(Parent[v]);
}
bool same(ll u, ll v) { return root(u) == root(v); }
void unite(ll u, ll v) {
  u = root(u);
  v = root(v);
  if (u == v) return;
  if (Rank[u] < Rank[v]) swap(u, v);
  Parent[v] = u;
  if (Rank[u] == Rank[v]) ++Rank[u];
}
int main() {
  cin >> N;
  for (ll v = 0; v < N; ++v) {
    ll x, y;
    cin >> x >> y;
    Points[0].push_back(Point(x, y, v));
    Points[1].push_back(Point(y, x, v));
  }
  for (ll k : {0, 1}) sort(Points[k].begin(), Points[k].end());
  for (ll k : {0, 1})
    for (ll i = 0; i < N - 1; ++i) {
      ll x, y, u, x2, y2, v;
      tie(x, y, u) = Points[k][i];
      tie(x2, y2, v) = Points[k][i + 1];
      Edges.push_back(Edge(min(abs(x2 - x), abs(y2 - y)), u, v));
    }
  sort(Edges.begin(), Edges.end());
  init();
  for (Edge edge : Edges) {
    ll d, u, v;
    tie(d, u, v) = edge;
    if (!same(u, v)) {
      unite(u, v);
      R += d;
    }
  }
  cout << R << endl;
  return 0;
}


#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <climits>
#include <cfloat>
using namespace std;

int main()
{
    for(;;){
        vector<int> card(5);
        if(!(cin >> card[0]))
            return 0;

        for(int i=1; i<5; ++i){
            char c;
            cin >> c >> card[i];
        }
        sort(card.begin(), card.end());

        vector<int> num(5, 0);
        for(int i=0; i<5; ++i){
            int j = i+1;
            while(j < 5 && card[j] == card[i])
                ++ j;
            ++ num[j-i];
            i = j-1;
        }

        if(num[4] == 1)
            cout << "four card" << endl;
        else if(num[3] == 1 && num[2] == 1)
            cout << "full house" << endl;
        else if(num[3] == 1)
            cout << "three card" << endl;
        else if(num[2] == 2)
            cout << "two pair" << endl;
        else if(num[2] == 1)
            cout << "one pair" << endl;
        else if(card[0] == 1 && card[1] + 3 == card[4])
            cout << "straight" << endl;
        else if(card[0] + 4 == card[4])
            cout << "straight" << endl;
        else
            cout << "null" << endl;
    }
}

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define inf 0x3f3f3f3f
#define MAX(x,y) x=max(x,y)
using namespace std;

const int N=18;
const int M=32775;

int n,m,bin[N],num[M],ma[N][M],sum[M],f[N][M],g[M];

int read()
{
	int x=0,f=1;char ch=getchar();
	while (ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}

int lowbit(int x)
{
	return x&(-x);
}

int main()
{
	n=read();m=read();
	bin[0]=1;
	for (int i=1;i<=n;i++) bin[i]=bin[i-1]*2,num[bin[i]]=i;
	int tot=0;
	for (int i=1;i<=m;i++)
	{
		int x=read()-1,y=read()-1,z=read();tot+=z;
		ma[x][bin[y]]=ma[y][bin[x]]=z;
	}
	for (int i=0;i<n;i++)
		for (int j=1;j<bin[n];j++)
			ma[i][j]=ma[i][j-lowbit(j)]+ma[i][lowbit(j)];
	for (int i=1;i<bin[n];i++) sum[i]=sum[i-lowbit(i)]+ma[num[lowbit(i)]][i-lowbit(i)];
	for (int i=0;i<n;i++)
		for (int j=0;j<bin[n];j++)
			f[i][j]=-inf;
	f[0][1]=0;
	for (int j=0;j<bin[n];j++)
		for (int i=0;i<n-1;i++)
		{
			if (f[i][j]<0) continue;
			for (int k=0;k<n;k++)
				if (!(j&bin[k])&&ma[i][bin[k]]) MAX(f[k][j+bin[k]],f[i][j]+ma[i][bin[k]]);
		}
	for (int i=0;i<bin[n];i++) g[i]=f[n-1][i];
	for (int i=1;i<bin[n];i++)
	{
		if (g[i]<0) continue;
		int r=i^(bin[n]-1);
		for (int s=r;s;s=(s-1)&r)
		{
			int mxv=0;
			for (int j=i;j;j-=lowbit(j)) mxv=max(mxv,sum[s+lowbit(j)]);
			MAX(g[i+s],g[i]+mxv);
		}
	}
	printf("%d",tot-g[bin[n]-1]);
	return 0;
}


#include <bits/stdc++.h>
#define MAX 100005
#define bit(x) (1ll << x)

using namespace std;

int n;
int cnt[64];
long long a[MAX], ans;

inline long long Rd() {
	long long x = 0; char ch = getchar();
	while(!isdigit(ch)) ch = getchar();
	while(isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
	return x;
}

struct linear_base {
	long long u[60];
	inline void insert(long long val) {
		for(int i = 59; i >= 0; --i) {
			if(val & bit(i)) {
				if(u[i]) val ^= u[i];
				else {
					u[i] = val;
					return;
				}
			}
		}
	}
	inline long long query() {
		long long res = 0;
		for(int i = 59; i >= 0; --i)
			if((res ^ u[i]) > res) res ^= u[i];
		return res;
	}
}lsk;

int main() {
	n = Rd();
	for(int i = 1; i <= n; ++i) {
		a[i] = Rd();
		for(int j = 59; j >= 0; --j)
			if(a[i] & bit(j)) ++cnt[j];
	}

	for(int i = 59; i >= 0; --i) {
		if(cnt[i] & 1) {
			ans += bit(i);
			for(int j = 1; j <= n; ++j) {
				if(a[j] & bit(i)) {
					a[j] ^= bit(i);
				}
			}
		}
	}
	for(int i = 1; i <= n; ++i) lsk.insert(a[i]);

	cout << ans + 2ll * lsk.query() << endl;
	return 0;
}

#include "bits/stdc++.h"
#define rep(i,n) for(int i = 0; i < (n); ++i)
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    vector<int> a(n);
    rep(i,n) cin >> a[i];
    ll ans = 0, cnt = 0;
    if(a[0] != 0){
        cout << -1 << endl;
        return 0;
    }
    vector<int> b(n, 0);
    for(int i = n-1; i >= 0; i--){
        if(b[i] > a[i]){
            cout << -1 << endl;
            return 0;
        }
        if(i > 0) b[i-1] = max(0, a[i] - 1);
        if(a[i] == b[i]) continue;
        ans += a[i];
    }
    cout << ans << endl;
	return 0;
}


/*

This Submission is to determine how many 120/240 min const. delivery point there are.

//info
120 req. steps <= 5
*/
#define  _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <algorithm>
#include <utility>
#include <functional>
#include <cstring>
#include <queue>
#include <stack>
#include <math.h>
#include <iterator>
#include <vector>
#include <string>
#include <set>
#include <math.h>
#include <iostream>
#include <random>
#include<map>
#include <iomanip>
#include <time.h>
#include <stdlib.h>
#include <list>
#include <typeinfo>
#include <list>
#include <set>
#include <cassert>
#include<fstream>
#include <unordered_map>
#include <cstdlib>
#include <complex>
#include <cctype>
#include <bitset>
using namespace std;
typedef string::const_iterator State;
#define Ma_PI 3.141592653589793
#define eps 1e-5
#define LONG_INF 1e18
#define GOLD 1.61803398874989484820458
#define MAX_MOD 1000000007
#define MOD 1000000007
#define seg_size 262144
#define REP(a,b) for(long long a = 0;a < b;++a)

unsigned long xor128() {
	static unsigned long x = time(NULL), y = 362436069, z = 521288629, w = 88675123;
	unsigned long t = (x ^ (x << 11));
	x = y; y = z; z = w;
	return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)));
}
//do gift-wrapping method
#define double long double
double dot(complex<double> a, complex<double> b) {
	return a.real() * b.real() + a.imag() * b.imag();
}
double gyaku_dot(complex<double> a, complex<double> b) {
	return a.real() * b.imag() - a.imag() * b.real();
}
double leng(complex<double> a) {
	return sqrt(a.real() * a.real() + a.imag() * a.imag());
}
double angles(complex<double> a, complex<double> b) {
	double cosine = dot(a, b) / (leng(a) * leng(b));
	double sine = gyaku_dot(a, b) / (leng(a) * leng(b));
	double kaku = acos(min((double)1.0, max((double)-1.0, cosine)));
	if (sine <= 0) {
		kaku = 2 * Ma_PI - kaku;
	}
	return kaku;
}
vector<int> convex_hull(vector<complex<double>> a) {
	vector<int> ans;
	double now_minnest = a[0].real();
	int now_itr = 0;
	REP(i, a.size()) {
		if (now_minnest > a[i].real()) {
			now_minnest = a[i].real();
			now_itr = i;
		}
	}
	ans.push_back(now_itr);
	complex<double> ba(0, 1);
	while (true) {
		int now_go = 0;
		double now_min = 0;
		double now_length = 0;
		int starter = ans[ans.size() - 1];
		for (int i = 0; i < a.size(); ++i) {
			if (i != starter) {
				double goa = angles(ba, a[i] - a[starter]);
				if (goa - now_min >= eps||(abs(goa - now_min) <= eps&&(abs(a[i] - a[starter]) - now_length) >= eps)) {
					now_min = goa;
					now_go = i;
					now_length = abs(a[i] - a[starter]);
				}
			}
		}
		if (now_go == ans[0]) break;
		ans.push_back(now_go);
		ba = complex<double>(a[now_go] - a[starter]);
	}
	return ans;
}
double ans[2000] = {};
#undef double
int main() {
#define double long double
	int n;
	cin >> n;
	vector<complex<double>> inputs;
	REP(i, n) {
		double x, y;
		cin >> x >> y;
		inputs.push_back(complex<double>(x, y));
	}
	vector<int> hoge;
	if (n == 2) {
		hoge.push_back(0);
		hoge.push_back(1);
	}
	else {
		hoge = convex_hull(inputs);
	}
	hoge.push_back(hoge[0]);
	hoge.push_back(hoge[1]);
	for (int i = 1; i < hoge.size() - 1; ++i) {
		complex<double> A = inputs[hoge[i]] - inputs[hoge[i - 1]];
		complex<double> B = inputs[hoge[i + 1]] - inputs[hoge[i]];
		complex<double> C = complex<double>(A.imag() * -1.0, A.real());
		complex<double> D = complex<double>(B.imag() * -1.0, B.real());
		ans[hoge[i]] = angles(D,C) / (2.0 * Ma_PI);
	}
	cout << fixed << setprecision(50);
	REP(i, n) {
		cout << ans[i] << endl;
	}
}

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
	int n;
	while(cin>>n){
		if(n==0)
			break;
		int da[22][22]={};
		int x,y;
		for(int i=0;i<n;i++){
			cin>>x>>y;
			da[y][x]=1;
		}
		int m;
		cin>>m;
		char v;
		int l;
		int nx=10,ny=10;
		for(int i=0;i<m;i++){
			cin>>v;
			cin>>l;
			if(v=='N'){
				for(int j=1;j<=l;j++)
					da[ny+j][nx]=0;
				ny+=l;
			}
			if(v=='E'){
				for(int j=1;j<=l;j++)
					da[ny][nx+j]=0;
				nx+=l;
			}
			if(v=='S'){
				for(int j=1;j<=l;j++)
					da[ny-j][nx]=0;
				ny-=l;
			}
			if(v=='W'){
				for(int j=1;j<=l;j++)
					da[ny][nx-j]=0;
				nx-=l;
			}
		}
		for(int i=0;i<22;i++){
			for(int j=0;j<22;j++){
				if(da[i][j]==1){
					cout<<"No"<<endl;
					j=30;
					i=30;
					break;
				}
			}
			if(i==21)
				cout<<"Yes"<<endl;
		}
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int maxn = 5000500;
const int mod = 1e9 + 7;
int a[maxn], pref[maxn], cntzer[maxn];
long long dp[maxn];
vector < int > v[maxn];
long long add(long long a, long long b){
    a += b;
    if(a >= mod) a -= mod;
    return a;
}

long long mul(long long a, long long b){
    return (a * b) % mod;
}

long long solve_fixed(int n, int X){
    dp[pref[n - 1]] = 1;
    long long ans = (pref[n - 1] == X ? 1:0);
    for(int i = n - 2 ; i >= 0 ; --i){
        if(pref[i] == X) ans = add(ans, dp[0]);
        dp[pref[i]] = add(dp[pref[i]],dp[X ^ pref[i]]);
    }
    return ans;
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int n;
    cin >> n;
    long long xr = 0;
    for(int i = 0 ; i < n ; ++i)
        cin >> a[i];
    pref[0] = a[0];
    cntzer[0] = (a[0] ? 0:1);
    v[a[0]].push_back(0);
    for(int i = 1 ; i < n ; ++i){
        pref[i] = a[i] ^ pref[i - 1];
        cntzer[i] = !pref[i] + cntzer[i - 1];
        v[pref[i]].push_back(i);
    }
    long long ans = solve_fixed(n, 0);
    for(int i = 1 ; i < maxn ; ++i){
        if((int)v[i].size() == 0 || (v[i][(int)v[i].size() - 1] != n - 1 && pref[n - 1])) continue;
        long long smx = 1, sm0 = !pref[n - 1];
        ans = add(ans, smx);
        for(int j = (int)v[i].size() - 2 ; j >= 0 ; --j){
            sm0 = add(sm0, mul(cntzer[v[i][j + 1]] - cntzer[v[i][j]], smx));
            ans = add(ans, sm0);
            smx = add(smx, sm0);
        }
    }
    cout << ans << '\n';
    return 0;

}

#include "bits/stdc++.h"
#include "ext/pb_ds/assoc_container.hpp"
#include "ext/pb_ds/tree_policy.hpp"
using namespace __gnu_pbds;
using namespace std;
typedef long long int ll;
#define int long long
#define pb push_back
#define fi first
#define se second
#define fr(i, a, b) for(int i = a; i <= b; i++)
#define all(x) x.begin(), x.end()
#define IO ios :: sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define pii pair<int,int>
#define sz(x) (int)x.size()
const int mod = 1e9 + 7;
const int mod1 = 998244353;
typedef long double f80;

#ifndef LOCAL
#pragma GCC optimize ("O2")
#define endl '\n'
#endif

template<typename T>
using ordered_set = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rand(int l, int r){
    uniform_int_distribution<int> uid(l, r);
    return uid(rng);
}

ll pwr(ll a,ll b, ll mod){
    a %= mod;
    int ans = 1;
    while(b){
        if(b & 1) ans = (ans * a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return ans;
}

string to_string(string s) {
  return '"' + s + '"';
}

string to_string(const char* s) {
  return to_string((string) s);
}

string to_string(bool b) {
  return (b ? "true" : "false");
}

template <typename A, typename B>
string to_string(pair<A, B> p) {
  return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}

template <typename A>
string to_string(A v) {
  bool first = true;
  string res = "{";
  for (const auto &x : v) {
    if (!first) {
      res += ", ";
    }
    first = false;
    res += to_string(x);
  }
  res += "}";
  return res;
}

void debug_out() { cerr << endl; }

template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
  cerr << " " << to_string(H);
  debug_out(T...);
}

#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif

const int N = 5e5 + 5;
int a[N], pre[N];
int dp[N];
map<int,int> m, m1;
void solve(){
	int n;
	cin >> n;
	fr(i, 1, n){
		cin >> a[i];
		pre[i] = pre[i - 1] ^ a[i];
	}
	int ans = 0;
	if(pre[n] != 0){ // xor != 0 and odd partitions ...
		int s0 = 1, s1 = 0;
		int val = pre[n];
		fr(i, 1, n){
			if(pre[i] == val){
				dp[i] = s0;
				s1 += dp[i];
				s1 %= mod;
			}
			else if(pre[i] == 0){
				dp[i] = s1;
				s0 += dp[i];
				s0 %= mod;
			}
		}
		cout << dp[n] << endl;
		return;
	}
	// xor = 0
	int c = 0;
	fr(i, 1, n - 1){
		if(pre[i] == 0)
			c++;
	}
	ans = pwr(2, c, mod);
	// xor != 0
	int c0 = 1;
	m[0] = 1;
	dp[0] = 1;
	fr(i, 1, n){
		if(pre[i] == 0){
			c0++;
		}
		else{
			dp[i] = (m1[pre[i]] * c0 - m[pre[i]] + mod + 1) % mod;
			ans += dp[i];
			ans %= mod;
			m[pre[i]] += c0 * dp[i];
			m[pre[i]] %= mod;
			m1[pre[i]] += dp[i];
			m1[pre[i]] %= mod;
		}
	}
	cout << ans;
}
signed main(){
    IO;
    #ifdef LOCAL
        freopen("inp.txt","r", stdin);
        freopen("out.txt", "w", stdout);
    #endif
    cout << setprecision(10) << fixed;
    int t = 1;
    // cin >> t;
    fr(tt, 1, t){
        solve();
    }
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define str string
#define pii pair<int, int>
#define pll pair<ll, ll>
#define fi first
#define se second

#define vc vector<char>
#define vvc vector<vc>
#define vi vector<int>
#define vll vector<ll>
#define vvi vector<vi>
#define vvll vector<vll>
#define vvvll vector<vvll>
#define vs vector<str>
#define vvs vector<vs>
#define vpii vector<pii>
#define vvpii vector<vpii>
#define vpll vector<pll>
#define vvpll vector<vpll>
#define vb vector<bool>
#define vvb vector<vb>
#define rep(i, a, b) for (int i = (a); i < int(b); i++)
#define repi(i, a, b) for (int i = (a); i <= int(b); i++)

using namespace std;
ll INF = LONG_LONG_MAX;
ll mod = 1000000000 + 7;

template <typename T, typename L>
void read(vector<T> & _data, L & _size, bool _shift) {
    _data.resize(_size + (ll)_shift);
    for (ll i = (ll)_shift; i < _size + (ll)_shift; i++)
        cin >> _data[i];
}

template <typename T, typename L>
void read(vector<vector<T>> & _data, L & _rows, L & _cols, bool _shiftRows, bool _shiftCols) {
    _data.resize(_rows + (ll)_shiftRows);
    for (ll i = 0; i < _rows + (ll)_shiftRows; i++)
        _data[i].resize(_cols + (ll)_shiftCols);
    for (ll i = (ll)_shiftRows; i < _rows + (ll)_shiftRows; i++)
        for (ll j = (ll)_shiftCols; j < _cols + (ll)_shiftCols; j++)
            cin >> _data[i][j];
}

template <typename T>
void write(vector<T> & _data, bool _shift) {
    for (ll i = (ll)_shift; i < _data.size(); i++)
        cout << _data[i] << " ";
    cout << endl;
}

//TODO: SOLUTION

ll h, w;
vll l, r;

void solve() {
    cin >> h >> w;
    l.resize(h + 1);
    r.resize(h + 1);
    repi(i, 1, h) {
        cin >> l[i] >> r[i];
    }

    set<pll> s;
    map<ll, ll> m;
    m[0] = 0;

    repi(i, 1, w) {
        s.insert({i, i});
        m[0]++;
    }

    ll x = 1;
    while (x != h + 1) {
        auto it = s.lower_bound({l[x], 0});
        ll ans = INF;
        vpll todel;
        vpll toins;
        while (it != s.end() && it->first <= r[x]) {
            //cout << it->fi << " "<< it->se << ", ";
            toins.push_back({r[x] + 1, it->second});
            todel.push_back({it->first, it->second});
            it++;
        }
        for (auto p : todel) {
            m[p.first - p.second]--;
            if (m[p.first - p.second] == 0)
                m.erase(p.first - p.second);
            s.erase(p);
            //cout << "delete " << p.second << ":" << p.first << endl;
        }

        if (!toins.empty()) {
            auto p = toins[toins.size() - 1];
            //cout << "insert " << p.se << ":" << p.fi << endl;
            if (m.count(p.first - p.second) && p.first <= w)
                m[p.first - p.second]++;
            else if (p.first <= w)
                m[p.first - p.second] = 1;
            if (p.first <= w)
                s.insert(p);
        }
        if (m.empty()) {
            cout << -1 << endl;
        }
        else {
            cout << x + m.begin()->fi << endl;
        }
        x++;
    }
}

int main() {

    // TODO: Set value of this variable manually
    bool _multipleTestCases = false;

    if (_multipleTestCases) {
        ll t; cin >> t;
        while (t--)
            solve();
    }
    else {
        solve();
    }

    return 0;
}

/*Hatsune Miku 4ever!*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define _for(i,a,b) for(int i = (a);i < b;i ++)
#define _rep(i,a,b) for(int i = (a);i > b;i --)
#define INF 0x3f3f3f3f
#define mod 1000000007
#define lowbit(x) ((x)&(-x))
#define pb push_back
#define MIKU 39
#define Design ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define debug() printf("Miku Check OK!\n")
#define maxn 200039

int n, m;
struct SegTree
{
	struct SegNode
	{
		int l,r;
		ll add;
		ll ans;
		#define l(x) tree[x].l
		#define r(x) tree[x].r
		#define add(x) tree[x].add
		#define ANS(x) tree[x].ans
	}tree[maxn<<2];
	void build(int p,int l,int r)
	{
		add(p) = 0;
		l(p) = l,r(p) = r;
		if(l==r)
		{
			ANS(p) = 0;
			return ;
		}
		int mid = (l+r)/2;
		build(p*2, l, mid);
		build(p*2+1, mid+1, r);
	}

	void spread(int p)
	{
		if(add(p))
		{
			ANS(p*2) = l(p) - add(p);
			ANS(p*2+1) = (l(p)+r(p))/2+1-add(p);
			add(p*2) = add(p);
			add(p*2+1) = add(p);
			add(p) = 0;
		}
	}
	void change(int p,int l,int r,ll d)
	{
		if(l <= l(p) && r >= r(p))
		{
			ANS(p) = l(p) - d;
			add(p) = d;
			return ;
		}
		spread(p);
		int mid = (l(p)+r(p))/2;
		if(l <= mid)
			change(p*2, l, r, d);
		if(r > mid)
			change(p*2+1, l, r, d);
		ANS(p) = min(ANS(p*2),ANS(p*2+1));
	}
	ll ask(int p,int pos)
	{
		if(l(p)==r(p))
			return pos - ANS(p);
		spread(p);
		int mid = (l(p)+r(p))/2;
		if(pos <= mid)
			return ask(p*2, pos);
		else
			return ask(p*2+1, pos);
	}
}T;

int main()
{
	int H, W;
	scanf("%d%d",&H,&W);
	T.build(1,1,W);
	int now = 1;
	_for(i,1,H+1)
	{
		int a, b;
		scanf("%d%d",&a,&b);
		if(now < a)
			T.change(1,a,b,T.ask(1,a-1));
		else if(now >= a && now <= b)
		{
			T.change(1,now,b,-1000000);
			now = b+1;
		}
		if(now > W)
			printf("-1\n");
		else
			printf("%lld\n",T.tree[1].ans+i);
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <set>
using namespace std;
#define REP(i, n) for(int i = 0; i < n; i++)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define ALL(x) (x).begin(),(x).end() //sortなどの引数を省略したい
#define SIZE(x) ((ll)(x).size()) //sizeをsize_tからllに直しておく
#define MAX(x) *max_element(ALL(x)) //最大値を求める
#define MIN(x) *min_element(ALL(x)) //最小値を求める
typedef long long ll;
typedef long double ld;
int main(){
    set<ll> v;
    ll n;cin>>n;
    REP(i,n){
        ll a;cin>>a;
        if(v.find(a)!=v.end()){
            v.erase(a);
        }else{
            v.insert(a);
        }
    }
    cout<<v.size()<<endl;
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const long long INF = 1LL << 60;

int main() {
    int N, count = 0;
    cin >> N;
    vector<int> v(N);

    for(int i=0; i<N; i++) {
        cin >> v[i];
    }
    sort(v.begin(), v.end());

    for(int i=0; i<N; i++) {
        if(v[i] == v[i+1] && i <= N-2) {
            i++;
        }
        else {
            count++;
        }
    }
    cout << count << endl;
}


#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>
using namespace std;

//型定義
typedef long long ll;

//定数
const ll INF=1e+17;
const int MOD=1e+9+7;

//REPマクロ
#define REP(i,n) for(ll i=0;i<(ll)(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define REP2(i,a,b) for(ll i=a;i<(ll)(b);i++)
#define REPD2(i,a,b) for(ll i=a;i>(ll)(b);i--)

//vectorの扱い
#define ALL(x) (x).begin(),(x).end() //sortなどの引数省略
#define SIZE(x) ((ll)(x).size()) //size
#define MAX(x) *max_element(ALL(x)) //最大値
#define MIN(x) *min_element(ALL(x)) //最小値

//グローバル変数

//ライブラリ挿入

int main(){
    int N;
    cin >> N;
    vector<ll> A(N);
    REP(i,N) cin >> A[i];
    vector<vector<ll>> dp(N+1,vector<ll>(2,0));
    dp[0][0]=0;
    dp[0][1]=0;
    dp[1][0]=0;
    dp[1][1]=A[0];

    REP2(i,1,N){
        if(i%2==1){
            dp[i+1][0]=max(dp[i][1],dp[i-1][0]+A[i]);
        }else{
            dp[i+1][0]=max(dp[i][0],dp[i-1][0]+A[i]);
            dp[i+1][1]=dp[i-1][1]+A[i];
        }
    }
    cout<<dp[N][0]<<endl;
}


#include<stdio.h>
#include<string.h>
#define N 8

int mp[N][N],row[N],col[N],dneg[2*N-1],dops[2*N-1];

void init()
{
    for(int i=0; i<N; i++)
        row[i]=col[i]=0;
    for(int i=0; i<2*N-1; i++)
        dneg[i]=dops[i]=0;
    for(int i=0; i<N; i++)
        for(int j=0; j<N; j++)
            mp[i][j]=0;
}

void check()
{
    for(int i=0; i<N; i++)
        for(int j=0; j<N; j++)
            if(mp[i][j])
            {
                if(row[i]!=j)
                    return ;
            }
    for(int i=0; i<N; i++)
    {
        for(int j=0; j<N; j++)
        {
            printf("%c",(row[i]==j)?'Q':'.');
        }
        printf("\n");
    }
    return ;
}

void dfs(int i)
{
    if(i==N)
    {
        check();
        return ;
    }
    for(int j=0; j<N; j++)
    {
        if(col[j] || dops[i+j] || dneg[i-j+N-1]) continue;
        row[i]=j;
        col[j]=dops[i+j]=dneg[i-j+N-1]=1;
        dfs(i+1);
        row[i]=col[j]=dops[i+j]=dneg[i-j+N-1]=0;
    }
}

int main()
{
    int k,r,c;
    while(~scanf("%d",&k))
    {
        init();
        for(int i=0; i<k; i++)
        {
            scanf("%d%d",&r,&c);
            mp[r][c]=1;
        }
        dfs(0);
    }
    return 0;
}

// clang-format off
#include <bits/stdc++.h>
#define int long long
#define main signed main()
#define loop(i, a, n) for (int i = (a); i < (n); i++)
#define rep(i, n) loop(i, 0, n)
#define forever while (true)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define prec(n) fixed << setprecision(n)
template<typename A> using V = std::vector<A>;
template<typename A> using F = std::function<A>;
template<typename A, typename B> using P = std::pair<A, B>;
using pii = P<int, int>;
using vi = V<int>;
using vd = V<double>;
using vs = V<std::string>;
using vpii = V<pii>;
using vvi = V<vi>;
using vvpii = V<vpii>;
constexpr int INF = sizeof(int) == sizeof(long long) ? 1000000000000000000LL : 1000000000;
constexpr int MOD = 1000000007;
constexpr double PI = acos(-1);
template<typename A, typename B> bool cmin(A &a, const B &b) { return a > b ? (a = b, true) : false; }
template<typename A, typename B> bool cmax(A &a, const B &b) { return a < b ? (a = b, true) : false; }
template<typename T> std::istream &operator>>(std::istream &is, std::vector<T> &v) { for (T &x : v) is >> x; return is; }
using namespace std;
// clang-format on

using Weight = int;
struct Edge {
  int src, dst;
  Weight weight;
  Edge(const int &s = 0, const int &d = 0, const Weight &w = 0) : src(s), dst(d), weight(w) {}
};

using Edges = std::vector<Edge>;
using Array = std::vector<Weight>;
using Matrix = std::vector<Array>;

class Graph {
  std::vector<Edges> g;

public:
  Graph(const int &size = 0) : g(size) {}

  void addArc(const int &src, const int &dst, const Weight &w = 1) { g[src].emplace_back(src, dst, w); }

  void addEdge(const int &node1, const int &node2, const Weight &w = 1) {
    addArc(node1, node2, w);
    addArc(node2, node1, w);
  }

  const Edges &operator[](const int &i) const { return g[i]; }

  Graph toRootedTree(int r);
  std::pair<std::vector<Weight>, std::vector<int>> dijkstra(const int &src, const int &inf);
  Matrix warshallFloyd(const int &inf);
  std::pair<Weight, Edges> prim(const int &r);
  template<typename UnionFind> std::pair<Weight, Edges> kruskal();
  Weight solveTSP(const int &inf);
};

Matrix Graph::warshallFloyd(const int &inf = std::numeric_limits<Weight>::max() / 8) {
  int n = g.size();
  Matrix d(n, Array(n, inf));
  rep(i, n) d[i][i] = 0;
  for (auto &adj : g) {
    for (auto &e : adj) cmin(d[e.src][e.dst], e.weight);
  }
  rep(k, n) rep(i, n) rep(j, n) {
    if (d[i][k] != inf && d[k][j] != inf) cmin(d[i][j], d[i][k] + d[k][j]);
  }
  return d;
}

main {
  ios::sync_with_stdio(false);
  int n, t;
  cin >> n >> t;
  Graph g(n);
  while (t--) {
    int s, t, d;
    cin >> s >> t >> d;
    g.addArc(s, t, d);
  }
  Matrix d = g.warshallFloyd(INF);
  rep(i, n) if (d[i][i] < 0) {
    cout << "NEGATIVE CYCLE" << endl;
    return 0;
  }
  rep(i, n) {
    rep(j, n) {
      if (j) cout << ' ';
      cout << (d[i][j] == INF ? "INF" : to_string(d[i][j]));
    }
    cout << endl;
  }
}


#include<algorithm>
using namespace std;

#define MAXN 100000

int AC[MAXN] = {};
int WA[MAXN] = {};

int main()
{
    int ACCount = 0;
    int WACount = 0;
    int n,m;
    scanf("%d %d",&n,&m);
    for(int i = 0; i < m; i++)
    {
        int curNum;
        char first, second;
        scanf("%d %c%c", &curNum, &first, &second);
        if(AC[curNum - 1] != 0)
        {
            continue;
        }
        if(first == 'A')
        {
            AC[curNum - 1] = 1;
            WACount += WA[curNum - 1];
            ACCount += 1;
        }
        else
        {
            WA[curNum - 1] += 1;
        }
    }
    printf("%d %d",ACCount, WACount);
}

#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int,int>;

vector<int> x(10), y(10);

double dist (int i, int j) {
    double dx = x.at(i) - x.at(j);
    double dy = y.at(i) - y.at(j);
    return pow(dx*dx + dy*dy, 0.5);
}

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

    for (int i = 1; i <= n; ++i) cin >> x.at(i) >> y.at(i);
    double sum = 0.0;
    vector<int> v(n);
    rep(i,n) v.at(i) = i + 1;

    do {
        for (int i = 0; i < n - 1; ++i) sum += dist(v.at(i), v.at(i+1));
    } while (next_permutation(v.begin(), v.end()));

    int factorial = 1;
    for (int i = 1; i <= n; ++i) factorial *= i;
    cout << std::fixed << std::setprecision(15);
    cout << sum / factorial << endl;

    return 0;
}


#include<bits/stdc++.h>
typedef long long int ll;
#define pb push_back
#define pi  3.141592653589793238462643383279
#define int long long
#define ff first
#define ss second
#define endl '\n'
#define inf 21474836478965499999
#define all(x) (x).begin(), (x).end()
#define rep(i,x,y) for(int i=(int)x; i<y; i++)
#define high_functioning_sociopath  ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
const unsigned int M = 1000000007;
/*------------------------------------- THE GAME IS ON ---------------------------------------------*/
void solve()
{
     int n; cin>>n;
     queue<int>q;
     for(int i=0;i<n;i++)
     {
            int x;
            cin>>x;
            q.push(x);
     }
     int ht=0;
     int prev=q.front();
     q.pop();
     while(q.size()>0)
     {
            int temp=q.front();
            ht+=max(ll(0),prev-temp);
            prev=max(temp,prev);
            q.pop();
     }
     cout<<ht<<endl;
}
int32_t main()
{
   high_functioning_sociopath
   ll t=1;
   //cin>>t;
   while(t--)
   {
      solve();
   }
}

#include<bits/stdc++.h>

using namespace std;

int main() {
    int n;
    cin>>n;
    int t;
    cin>>t;
    long long int ans = 0, max = t;
    for(int i = 1; i < n; i++) {
        cin>>t;
        if(t < max) {
            ans += max-t;
        }
        else if(t > max) {
            max = t;
        }
    }
    cout<<ans<<endl;
    return 0;
}


#include <iostream>
using namespace std;

#include <stdio.h>
#include <algorithm>
#include <string>
/********
*   ?????¢??¢?´¢ Linear Search
*********/

/*
int linearSearch(int strS int strT, int n )
{
	int key;

	for(int i =0 ; i < n; i++){
		if(strS[i] == key){
			return i;
		}
	}
	return NOT_FOUND;
}
*/

int main(void)
{
	int n , q;
	int strS[10000]={0} ;
	int strT[500]={0} ;
	int count = 0 ;

	cin >> n;
	for(int i = 0; i<n; i++){
		cin >> strS[i];
	}

	cin >> q;
	for(int i = 0; i<n; i++){
		cin >> strT[i];
	}

	for(int j = 0; j<q ; j++){
		for(int i =0; i < n; i++){
			if(strT[j] == strS[i]){
				count++;
				break;
			}
		}
	}
	cout << count << endl;

    return 0;
}

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

#define V(a) a.begin(), a.end()
typedef set<int> s;

int main()
{
	s a[2], C;

	for (auto &i : a) {
		int n, x;
		cin >> n;
		while (n--) {
			cin >> x;
			i.insert(x);
		}
	}

	set_intersection(V(a[0]), V(a[1]), inserter(C, C.end()));

	cout << C.size() << endl;
}


#include<bits/stdc++.h>

int main(){
        int h, m, k;
        scanf("%d %d", &h, &m);
        int s = h*60 + m;
        scanf("%d %d", &h, &m);
        int g = h*60 + m;
        scanf("%d", &k);
        printf("%d\n", std::max(0, g-s-k));
        return 0;
}

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

int main(){
    int h1, h2, m1, m2 , k; cin >> h1 >> m1 >> h2 >> m2 >> k;
    m1 += 60 *  h1; m2 += h2 * 60;
    cout << m2 - m1 - k << '\n';
    return 0;
}


#include<stdio.h>
int main()
{
	int N,R;
	int Z;
	scanf("%d %d",&N,&R);
	Z=100*(10-N);
	if(N>=10){
		printf("%d",R);
	}
	else if(N<10){
		printf("%d",R+Z);
	}
	return 0;
}

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

#define ll long long
#define pb push_back

const int maxn = 2e3 + 20;
const int maxm = maxn * maxn + 20;
const int mod = 1e9 + 7;

int dp[maxn][maxn] , fac[maxm] , caf[maxm];

inline void mkay(int &a)
{
	if(a >= mod)
		a -= mod;
	else if(a < 0)
		a += mod;
}

int bpw(int a , int b)
{
	if(!b)
		return 1;
	int x = bpw(a , b / 2);

	x = 1LL * x * x % mod;
	if(b&1)
		x = 1LL * x * a % mod;

	return x;
}

int c(int s , int r)
{
	if(r < 0 || r > s)
		return 0;

	return 1LL * fac[s] * caf[r] % mod * caf[s - r] % mod;
}

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

	fac[0] = 1;
	for(int i = 1; i < maxm; i++)
		fac[i] = 1LL * fac[i - 1] * i % mod;

	caf[maxm - 1] = bpw(fac[maxm - 1] , mod - 2);
	for(int i = maxm - 1; i > 0; i--)
		caf[i - 1] = 1LL * caf[i] * i % mod;

	int n , k;
	cin >> n >> k;

	if(k == 1)
		return cout << 1 << endl , 0;

	dp[0][0] = 1;
	for(int j = 0; j <= n; j++)
		for(int i = 0; i <= j; i++)
		{
			mkay(dp[i + 1][j] += 1LL * dp[i][j] * (n - i) % mod * c(n * k - (k - 1) * i - j - 1 , k - 2) % mod);
			mkay(dp[i][j + 1] += dp[i][j]);
		}

	cout << dp[n][n] << endl;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n; cin>>n;
  for(int i=111; i<=999; i+=111) if(n<=i){cout<<i; break;}
}

#include<bits/stdc++.h>
#define all(v) v.begin(),v.end()
using namespace std;
using ll=long long;
#ifdef ONLINE_JUDGE
#define D(...)
#else
#define D(...)cerr<<__LINE__<<":"<<"["<<#__VA_ARGS__<<"]->",P(__VA_ARGS__)
#endif
void P(){cerr<<endl;}
template<typename H,typename...T>void P(H h,T...t){cerr<<h<<" ";P(t...);}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);
    int n;cin>>n;
    while(1){
        string s=to_string(n);
        unordered_set<char>st(all(s));
        if(int(st.size())==1){
            return cout<<n,0;
        }
        ++n;
    }
}


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

vector<vector<int>> g(100010);
vector<int> check(100010, -1);
bool dfs(int key){
    bool flag=false;
    for(int i=0; i<g[key].size(); ++i){
        if(check[g[key][i]]<0){
            check[g[key][i]]=1-check[key];
            flag |= dfs(g[key][i]);
        }
        else flag |= check[key]==check[g[key][i]];
    }
    return flag;
}

int main() {
	int N, M; cin >> N >> M;
	for(int i=0; i<M; ++i){
	    int u, v;
	    cin >> u >> v;
	    g[u].push_back(v);
	    g[v].push_back(u);
	}
	long solo=0, matsu=0, other=0;
	for(int i=1; i<=N; ++i){
	    if(check[i]<0){
	        if(g[i].size()<1) ++solo;
	        else{
	            check[i]=0;
	            if(dfs(i)) ++other;
	            else ++matsu;
	        }
	    }
	}
	cout << solo*(2*N-solo)+matsu*matsu+(matsu+other)*(matsu+other) << endl;
	return 0;
}

#include<bits/stdc++.h>
#define MP make_pair
#define FR first
#define SE second
using namespace std;

const int S=(1<<20)+5;
char buf[S],*H,*T;
inline char Get()
{
    if(H==T) T=(H=buf)+fread(buf,1,S,stdin);
    if(H==T) return -1;return *H++;
}
inline int read()
{
    int x=0;char c=Get();
    while(!isdigit(c)) c=Get();
    while(isdigit(c)) x=x*10+c-'0',c=Get();
    return x;
}

const int N=200010;
struct Edge{int to,next;} e[N<<1];
int fa[N],sz[N],n,m,h[N],sum=0;
pair<int,int> circle[N];
bool parity[N],odd[N];
int cnt[2];

int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);}

void add_edge(int u,int v)
{
    e[++sum].to=v;
    e[sum].next=h[u];
    h[u]=sum;
}

void dfs(int u,int fa)
{
    parity[u]=parity[fa]^1;
    for(int t=h[u];t;t=e[t].next)
        if(e[t].to!=fa) dfs(e[t].to,u);
}

int main()
{
    int u,v,tot=0;
    n=read();m=read();
    for(int i=1;i<=n;i++) fa[i]=i,sz[i]=1;
    for(int i=1;i<=m;i++)
    {
        u=read();v=read();
        if(find(u)!=find(v))
        {
            add_edge(u,v);
            add_edge(v,u);
            u=find(u);v=find(v);
            fa[u]=v;sz[v]+=sz[u];
        }
        else circle[++tot]=MP(u,v);
    }
    for(int i=1;i<=n;i++)
        if(fa[i]==i) dfs(i,0);
    for(int i=1;i<=tot;i++)
        if(parity[circle[i].FR]==parity[circle[i].SE])
            odd[find(circle[i].FR)]=1;
    int alone=0;
    long long ans=0;
    for(int i=1;i<=n;i++)
    {
        if(fa[i]!=i) continue;
        if(sz[i]==1) alone++,ans+=n;
        else cnt[odd[i]]++;
    }
    ans+=1ll*(n-alone)*alone;
    ans+=2ll*cnt[0]*cnt[0];
    ans+=1ll*cnt[1]*(cnt[1]+2*cnt[0]);
    cout<<ans<<endl;
    return 0;
}


#include <iostream>
#include <algorithm>
#include <utility>
#include <fstream>
#include <iomanip>
#include <complex>
#include <cmath>
#include <vector>
#include <cstring>
#include <string>
#include <sstream>
#include <map>
#include <set>
#include <queue>

#define IO ios::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL);
typedef long long ll;
typedef long double ld;
const ll INF = 1e18;
const int N = 3e2 + 5, inf = 1e9, mod = 998244353;
using namespace std;

int n, a, freq[4] = {};
ld dp[N][N][N] = {};
bool vis[N][N][N] = {};

ld solve ( int c1 , int c2 , int c3 )
{
    if ( c1 + c2 + c3 == 0 )
        return 0;
    if ( vis[c1][c2][c3] )
        return dp[c1][c2][c3];
    vis[c1][c2][c3] = true;
    ld ret = 1.0, c0 = n - ( c1 + c2 + c3 );
    if ( c1 )
        ret += solve ( c1 - 1 , c2 , c3 ) * ( 1.0 * c1 / n );
    if ( c2 )
        ret += solve ( c1 + 1 , c2 - 1 , c3 ) * ( 1.0 * c2 / n );
    if ( c3 )
        ret += solve ( c1 , c2 + 1 , c3 - 1 ) * ( 1.0 * c3 / n );
    ret /= ( 1 - ( c0 / n ) );
    return dp[c1][c2][c3] = ret;
}

int main()
{
    IO
    cin >> n;
    for(int i = 0; i < n; i++)
    {
        cin >> a;
        freq[a]++;
    }
    cout << fixed << setprecision(10) << solve( freq[1] , freq[2] , freq[3] ) << '\n';
    return 0;
}

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

#define ll long long
#define ull unsigned long long
#define endl '\n'
//const int MOD = 1e9+7;

bool ok(int a, int b, int c, int d, vector<char> s){
    int ans=0;
    if(s[1]=='+')
        ans = a+b;
    else
        ans = a-b;

    if(s[3]=='+')
        ans = ans + c;
    else
        ans = ans-c;

    if(s[5]=='+')
        ans += d;
    else
        ans -= d;

    if(ans==7)
        return true;
    else
        return false;
}

int main(){
    string s;
    cin >> s;
    int a=s[0]-'0';
    int b=s[1]-'0';
    int c=s[2]-'0';
    int d=s[3]-'0';

    char sign[2] = {'+', '-'};
    vector<char> ans(7);
    ans[0]=s[0];
    ans[2]=s[1];
    ans[4]=s[2];
    ans[6]=s[3];

    for(int i=0; i<2; ++i){
        for(int j=0; j<2; ++j){
            for(int k=0; k<2; ++k){
                ans[1]=char(sign[i]);
                ans[3]=char(sign[j]);
                ans[5]=char(sign[k]);
                if(ok(a,b,c,d,ans)){
                    for(auto x:ans)
                        cout << x;
                    cout << "=7";
                    return 0;
                }
            }
        }
    }
}


//
//  main.cpp
//  testing
//
//  Created by 伊藤大騎 on 2019/01/07.
//  Copyright © 2019 HamamatsuJOHOKU. All rights reserved.
//
/*
 科目選択 (Selecting Subjects)

 JOI 君は物理，化学，生物，地学，歴史，地理の 6 科目のテストを受けた． それぞれのテストは 100 点満点で採点された．
 JOI 君は物理，化学，生物，地学の 4 科目から 3 科目を選択し，歴史，地理の 2 科目から 1 科目を選択する．
 テストの合計点が最も高くなるように科目を選ぶとき， JOI 君の選んだ科目のテストの合計点を求めよ．

 入力は 6 行からなり，1 行に 1 つずつ整数が書かれている．
 1 行目には JOI 君の物理のテストの点数 A が書かれている．
 2 行目には JOI 君の化学のテストの点数 B が書かれている．
 3 行目には JOI 君の生物のテストの点数 C が書かれている．
 4 行目には JOI 君の地学のテストの点数 D が書かれている．
 5 行目には JOI 君の歴史のテストの点数 E が書かれている．
 6 行目には JOI 君の地理のテストの点数 F が書かれている．
 書かれている整数 A, B, C, D, E, F はすべて 0 以上 100 以下である．

 出力
 JOI 君が選んだ科目のテストの合計点を 1 行で出力せよ．

 入出力例

 入力例 1    入力例 2
 100        15
 34         21
 76         15
 42         42
 10         15
 0          62

 出力例 1    出力例 2
 228        140

 入出力例 1 では，JOI 君が物理，生物，地学，歴史の 4 科目を選ぶとき，テストの合計点が最高になる．
 物理，生物，地学，歴史の点数はそれぞれ 100, 76, 42, 10 なので，選んだ科目のテストの合計点は 228 である．

 入出力例 2 では，JOI 君が化学，生物，地学，地理の 4 科目を選ぶとき，テストの合計点が最高になる．
 化学，生物，地学，地理の点数はそれぞれ 21, 15, 42, 62 なので，選んだ科目のテストの合計点は 140 である．

 入出力例 2 では，JOI 君が物理，化学，地学，地理の 4 科目を選ぶ場合でも，選んだテストの合計点は 140 である．

 */

#include <iostream>
#include <algorithm>

using namespace std;
int main (){

    int hairetsu[6]={0},ans=0,maxim=0;

    for (int i=0;i<6;i++){
        cin>>hairetsu[i];
    }

    for (int i=0;i<3;i++){
        for (int j=0;j<4;j++){
            if (maxim<hairetsu[j]){
                maxim=hairetsu[j];
            }
        }

        ans+=maxim;

        for (int j=0;j<4;j++){
            if (hairetsu[j]==maxim){
                hairetsu[j]=0;
                maxim=0;
            }
        }
    }
    ans+=max(hairetsu[4],hairetsu[5]);

    cout<<ans<<endl;

return 0;
}

#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 <iostream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#define vv(a, b, c, d) vector<vector<d> >(a, vector<d>(b, c))
typedef unsigned long long ull;
#define vvi std::vector<std::vector<int> >
#define vvs std::vector<std::vector<string> >
#define MODs 1000000007;
typedef long long int ll;
using namespace std;
int main(int argc, char const *argv[]) {
  int N;
  ll ans = 0;
  string s, S, t, T="";
  std::cin >> N;
  std::cin >> s;
  S = s.substr(0, N);
  t = s.substr(N);
  for(int i=0;i<N;i++) T+=t[N-1-i];
  std::vector<int> num(26, 0);
  for(int i=0;i<N;i++) num[S[i]-'a']++, num[T[i]-'a']--;
  bool flag = true;
  for(int i=0;i<26;i++) if(num[i]!=0) flag = false;
  vvs str = vv(0, 2, "", string);
  for(int i=0;i<(1<<N);i++){
    int n = i+(1<<20), count=0;
    string ah = "", bh = "";
    while(count<N){
      if(n%2==1) ah += T[count];
      if(n%2==0) bh += T[count];
      count++;
      n/=2;
    }
    str.push_back(std::vector<string> {ah, bh});
  }
  sort(str.begin(), str.end());
  for(int i=0;i<(1<<N);i++){
    int n = i + (1<<20), count=0;
    string ah="", bh="";
    while(count<N){
      if(n%2==1) ah += S[count];
      if(n%2==0) bh += S[count];
      count++;
      n/=2;
    }
    int k = upper_bound(str.begin(), str.end(), std::vector<string> {ah,bh}) - lower_bound(str.begin(), str.end(), std::vector<string> {ah, bh});
    ans += k;
  }
  std::cout << (!flag?0:ans) << '\n';
  return 0;
}

#include "bits/stdc++.h"
using namespace std;
using ll     = long long;
using pii    = pair<int, int>;
using pll    = pair<ll, ll>;
using vi     = vector<int>;
using vl     = vector<ll>;
using vvi    = vector<vi>;
using vvl    = vector<vl>;
const ll INF = 1LL << 60;
const ll MOD = 1000000007;
template <class T>
bool chmax(T &a, const T &b) {
    return (a < b) ? (a = b, 1) : 0;
}
template <class T>
bool chmin(T &a, const T &b) {
    return (b < a) ? (a = b, 1) : 0;
}
template <class C>
void print(const C &c, std::ostream &os = std::cout) {
    std::copy(std::begin(c), std::end(c), std::ostream_iterator<typename C::value_type>(os, " "));
    os << std::endl;
}

int main() {
    int n;
    cin >> n;
    string s;
    cin >> s;
    map<pair<string, string>, int> cnt;
    for (int i = 0; i < (1 << n); ++i) {
        string red  = "";
        string blue = "";
        for (int j = 0; j < n; ++j) {
            if (1 << j & i) {
                red += s[j];
            } else {
                blue = s[j] + blue;
            }
        }
        cnt[make_pair(red, blue)]++;
    }
    ll ret = 0;
    for (int i = 0; i < (1 << n); ++i) {
        string red  = "";
        string blue = "";
        for (int j = 0; j < n; ++j) {
            if (1 << j & i) {
                red = s[j + n] + red;
            } else {
                blue += s[j + n];
            }
        }
        ret += cnt[make_pair(red, blue)];
    }
    cout << ret << "\n";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(ll i = 0; i < n; i++)
#define rep2(i, x, n) for(int i = x; i <= n; i++)
#define rep3(i, x, n) for(int i = x; i >= n; i--)
#define elif else if
#define sp(x) fixed << setprecision(x)
#define pb push_back
#define eb emplace_back
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
const ll MOD = 1e9+7;
//const ll MOD = 998244353;
const int inf = (1<<30)-1;
const ll INF = (1LL<<60)-1;
const ld EPS = 1e-10;
template<typename T> bool chmax(T &x, const T &y) {return (x < y)? (x = y, true) : false;};
template<typename T> bool chmin(T &x, const T &y) {return (x > y)? (x = y, true) : false;};

int main(){
    string A;
    cin >> A;
    int N = sz(A);
    ll cnt[26];
    fill(cnt, cnt+26, 0);
    ll ans = 1;
    rep(i, N){
        int j = A[i]-'a';
        ans += i-(cnt[j]++);
    }
    cout << ans << endl;
}

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

#ifdef LOCAL
#define debug(var) cerr << (#var) << " = " << (var) << endl;
#else
#define debug(var)
#endif

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

int h[30];

void solve() {
  string s; cin >> s;
  for (int i = 0; i < (int)s.size(); ++i) {
    ++h[s[i]-'a'];
  }
  long long ans = 1LL*s.size()*(s.size()-1)/2;
  for (int i = 0; i < 30; ++i) {
    if (!h[i]) continue;
    ans -= 1LL*h[i]*(h[i]-1)/2;
  }
  printf("%lld", ans+1);
}

int main() {
  init();
  int t = 1; //scanf("%d", &t);
  while (t--) {
    solve();
  }
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int INF = 1e9;

int main()
{
  int n = 0;
  fscanf(stdin, "%d", &n);
  vector<ll> rows(n + 5), cols(n + 5);
  for (int i = 0; i < n; ++i) {
    fscanf(stdin, "%lld %lld", &rows[i + 1], &cols[i + 1]);
  }
  vector<vector<ll> > dp(n + 5, vector<ll>(n + 5, 0));
  for (int l = 2; l <= n; ++l) {
    for (int i = 1; i <= n - l + 1; ++i) {
      int j = l + i - 1;
      dp[i][j] = std::numeric_limits<ll>::max();
      for (int k = i; k <= j - 1; ++k) {
        dp[i][j] = min(dp[i][j],
                       dp[i][k] + dp[k + 1][j] + rows[i] * cols[k] * cols[j]);
      }
    }
  }
  fprintf(stdout, "%lld\n", dp[1][n]);
  return 0;
}

# include <bits/stdc++.h>
# define sz(x) (int)((x).size())
# define f first
# define s second
# define pb push_back
# define ub upper_bound
# define lb lower_bound
# define all(x) x.begin(), x.end()
# define pqueue priority_queue
# define Speed() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
# define rep(i,n) for(int i=0;i<n;++i)
# define forn(i,n) for(int i=1;i<=n;++i)

using namespace std;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

# define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
# define debug cerr<<"ERROR"<<endl
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
	cerr << *it << " = " << a << endl;
	err(++it, args...);
}

template<class T> void umin(T &a,T b){a=min(a,b);}
template<class T> void umax(T &a,T b){a=max(a,b);}

typedef long long ll;
typedef pair<int,int> pii;

const int dx[]={1,0,-1,0,-1,-1,1,1};
const int dy[]={0,1,0,-1,-1,1,-1,1};
const int inf=1e9,mod=1e9+7,N=2e5+5;

int f(int x){
	return x*x;
}

void solve(){
	int n;
	cin>>n;
	vector<int>x(n),y(n),v;
	rep(i,n)cin>>x[i]>>y[i];
	forn(i,n)v.pb(i);
	int cnt=0;
	double ans=0;
	do{
		cnt++;
		rep(i,n-1){
			ans+=sqrt(f(x[v[i]-1]-x[v[i+1]-1])+f(y[v[i]-1]-y[v[i+1]-1]));
		}
	}
	while(next_permutation(all(v)));
	double res=ans/cnt;
	printf("%.12f",res);
}

int main(){
 	Speed();
	int T=1;
	//cin>>T;
	while(T--)solve();
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<ll,ll> P;
#define pb push_back
#define mp make_pair
#define fr(i,n) for(int i=0;i<n;i++)
#define Fr(i,n) for(int i=0;i++<n;)
#define ifr(i,n) for(int i=n-1;i>=0;i--)
#define iFr(i,n) for(int i=n;i>0;i--)

ll par[2][200010],size[2][200010];

void init(int num,int n){
  fr(i,n){
    par[num][i]=i;
    size[num][i]=1;
  }
}

int find(int num,int x){
  if(par[num][x]==x) return x;
  else return par[num][x]=find(num,par[num][x]);
}

void unit(int num,int x,int y){
  x=find(num,x);
  y=find(num,y);
  if(x==y) return;
  if(size[num][x]<size[num][y]){
    par[num][x]=y;
    size[num][y]+=size[num][x];
  }
  else{
    par[num][y]=x;
    size[num][x]+=size[num][y];
  }
}

bool same(int num,int x,int y){
  return find(num,x)==find(num,y);
}

void prt(vector<ll>& s){
  for(auto it=s.begin();it!=s.end();it++) cout<<(*it)<<" ";
  cout<<endl;
}

int main(){
  ll n,k[2],p,q;
  P pq[200010];
  map<P,ll> tmp;
  cin>>n>>k[0]>>k[1];
  fr(i,2) init(i,n);
  fr(j,2){fr(i,k[j]){cin>>p>>q;unit(j,--p,--q);}}
  fr(i,n) tmp[mp(find(0,i),find(1,i))]++;
  fr(i,n) cout<<tmp[mp(find(0,i),find(1,i))]<<" ";
  cout<<endl;
}

//============================================================================
// Name        : hoba.cpp :)
// Author      : (O_O Diab) (Why_not) (el 3AQ)
// Version     :
// Copyright   : please, Don't touch me :(
// Description : problem (I) in C++
// MAIN IDEA   : max sum of S(X) + S(S(X)) => 100 so brute force
//============================================================================
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define rw freopen("input.txt","r",stdin),freopen("output.txt","w",stdout);
#define pb push_back
#define F first
#define S second
#define pf push_front
#define lp(i,a,b) for (int i=a;i<=(int)b;++i)
#define lp2(i,a,b) for (int i=a;i>=b;--i)
#define f(x) return cout<<x<<"\n",0
#define pii pair<int,int>
#define pll pair<ll,ll>
#define all(c) c.begin(),c.end()
#define allr(c) c.rbegin(),c.rend()
#define p(x) cout<<#x<<" = { "<<x<<" } \n"
#define vi vector<int>
#define vl vector<ll>
#define vii vector<pii>
#define vll vector<pll>
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define EPS 1e-6
// to convert string to number use int a = stoi(string);
// to convert number to string use string s = to_string(int);
#define FAST ios::sync_with_stdio(0),ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define clr(c,x) memset(c,x,sizeof(c));
using namespace __gnu_pbds;
using namespace std;
const ll INFL = 0x3f3f3f3f3f3f3f3fLL;
const int dx[] = { 0, 1, 0, -1, 1, -1, 1, -1 };
const int dy[] = { 1, 0, -1, 0, 1, -1, -1, 1 };
const int N = 2e5 + 5, mod = (int) 1e9 + 7, INF = 0x3f3f3f3f;
vi vv;
vector<vi> v, vec;
set<int> st;
int ans[N] = { }, comp[N] = { };
bool vis[N] = { };
void dfs(int node) {
	vis[node] = true;
	for (auto u : v[node])
		if (!vis[u])
			dfs(u);
	vv.pb(node);
}
int main() {
#ifdef ONLINE_JUDGE
	FAST
#endif
	int n, k, l;
	cin >> n >> k >> l;
	v.resize(n + 1);
	lp(i,1,k)
	{
		int x, y;
		cin >> x >> y;
		v[x].pb(y);
		v[y].pb(x);
	}
	int cnt = 0;
	lp(i,1,n)
	{
		if (vis[i])
			continue;
		vv.clear();
		dfs(i);
		cnt++;
		for (auto u : vv)
			comp[u] = cnt;
	}
	clr(vis, 0);
	v.clear();
	v.resize(n + 1);
	vec.resize(n + 1);
	lp(i,1,l)
	{
		int x, y;
		cin >> x >> y;
		v[x].pb(y);
		v[y].pb(x);
	}
	lp(i,1,n)
	{
		if (vis[i])
			continue;
		vv.clear();
		dfs(i);
		st.clear();
		for (auto u : vv) {
			vec[comp[u]].pb(u);
			st.insert(comp[u]);
		}
		for (auto u : st) {
			for (auto k : vec[u])
				ans[k] = vec[u].size();
			vec[u].clear();
		}
	}
	lp(i,1,n)
		cout << ans[i] << " ";
	return 0;
}


#include<iostream>
#include<iomanip>
#include<cmath>
#include<string>
#include<vector>
#include<list>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
#define fi first
#define se second
#define mp make_pair
#define rep(i, n) for(int i=0;i<n;++i)
#define rrep(i, n) for(int i=n;i>=0;--i)
const int inf=1e9+7;
const ll mod=1e9+7;
const ll big=1e18;
const double PI=2*asin(1);

int main() {
  ll H, W, A, B;
  cin>>H>>W>>A>>B;
  H--;
  W--;
  ll ue[H+W+1];
  ue[0] = 1;
  for(ll i=1;i<=H+W;++i){
    ue[i] = ue[i-1]*i%mod;
  }
  ll ans = ue[H+W];
  ll h = mod - 2;
  ll shita1=1, shita2=1, shita3=1, shita4=1;
  ll tmpshita1, tmpshita2, tmpshita3, tmpshita4;
  ll two;
  while(h>0){
    tmpshita1 = ue[H];
    tmpshita2 = ue[W];
    two = 1;
    while(2*two<=h){
      two *= 2;
      tmpshita1 *= tmpshita1;
      tmpshita1 %= mod;
      tmpshita2 *= tmpshita2;
      tmpshita2 %= mod;
    }
    h -= two;
    shita1 *= tmpshita1;
    shita1 %= mod;
    shita2 *= tmpshita2;
    shita2 %= mod;
  }
  ans = ans*shita1%mod*shita2%mod;
  ll tmpans;
  for(ll i=0;i<B;++i){
    tmpans = ue[H-A+i]*ue[W+A-i-1]%mod;
    shita1 = 1;
    shita2 = 1;
    shita3 = 1;
    shita4 = 1;
    h = mod - 2;
    two = 1;
    while(h>0){
      two = 1;
      tmpshita1 = ue[i];
      tmpshita2 = ue[H-A];
      tmpshita3 = ue[W-i];
      tmpshita4 = ue[A-1];
      while(2*two<=h){
        two *= 2;
        tmpshita1 *= tmpshita1;
        tmpshita2 *= tmpshita2;
        tmpshita3 *= tmpshita3;
        tmpshita4 *= tmpshita4;
        tmpshita1 %= mod;
        tmpshita2 %= mod;
        tmpshita3 %= mod;
        tmpshita4 %= mod;
      }
      h -= two;
      shita1 *= tmpshita1;
      shita2 *= tmpshita2;
      shita3 *= tmpshita3;
      shita4 *= tmpshita4;
      shita1 %= mod;
      shita2 %= mod;
      shita3 %= mod;
      shita4 %= mod;
    }
    tmpans = tmpans*shita1%mod*shita2%mod*shita3%mod*shita4%mod;
    ans = (ans-tmpans+mod)%mod;
  }
  cout<<ans<<endl;
}

#include <bits/stdc++.h>
const char nl = '\n';
using namespace std;
using ll = long long;
using ld = long double;
const int MOD = 1e9+7;
const int N = 205, X = 1e5+10;

int n, x;
int s[N];
int dp[2][X]; // dp[i][j] = # of ways to end with j, last mod i

void add(int& a, int b) {
  a += b;
  if (a >= MOD) a -= MOD;
}

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> x;
  for (int i = 0; i < n; i++) {
    cin >> s[i];
  }
  sort(s, s + n, greater<int>());
  dp[0][x] = 1;
  for (int i = 0; i < n; i++) {
    memset(dp[1], 0, sizeof dp[1]);
    // take self
    for (int j = 0; j <= x; j++) {
      add(dp[1][j%s[i]], dp[0][j]);
    }
    // don't take self
    for (int j = 0; j <= x; j++) {
      add(dp[1][j], (ll) dp[0][j] * (n - i - 1) % MOD);
    }
    swap(dp[0], dp[1]);
  }
  int ans = 0;
  for (int i = 0; i < s[n-1]; i++) {
    add(ans, (ll) i * dp[0][i] % MOD);
  }
  cout << ans << nl;
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

int N, M;
bool feeld[25][25];

void solve() {
	int x = 10, y = 10;
	for (int i = 0; i < M; i++) {
		char c;
		int d;

		cin >> c >> d;
		if (c == 'N') {
			for (int j = 0; j < d; j++) {
				feeld[++y][x] = 0;
			}
		}
		if (c == 'E') {
			for (int j = 0; j < d; j++) {
				feeld[y][++x] = 0;
			}
		}
		if (c == 'S') {
			for (int j = 0; j < d; j++) {
				feeld[--y][x] = 0;
			}
		}
		if (c == 'W') {
			for (int j = 0; j < d; j++) {
				feeld[y][--x] = 0;
			}
		}
	}

	bool isok = true;
	for (int i = 0; i <= 20; i++) {
		for (int j = 0; j <= 20; j++) {
			isok *= !feeld[i][j];
		}
	}

	if (isok) cout << "Yes" << endl;
	else cout << "No" << endl;
}

int main() {
	while (1) {
		cin >> N; if (N == 0) break;

		memset(feeld, 0, sizeof(feeld));
		for (int i = 0; i < N; i++) {
			int x, y; cin >> x >> y;
			feeld[y][x] = 1;
		}

		cin >> M;
		solve();
	}

	return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define TEMP_T template<typename T>
TEMP_T void sort(T& v){ sort(v.begin(), v.end()); }
TEMP_T void revs(T& v){ reverse(v.begin(), v.end()); }
TEMP_T void uniq(T& v){ sort(v); v.erase(unique(v.begin(), v.end()), v.end()); }
TEMP_T T    cums(T& v){ T r(v.size()); partial_sum(v.begin(), v.end(), r); return r; }
TEMP_T void show(T& v, char delim=' ', char end='\n'){ for(int i=0; i<v.size()-1; i++) cout << v[i] << delim; cout << v[v.size()-1] << end; }
TEMP_T T    acum(vector<T>& v, T b=0){ return accumulate(v.begin(), v.end(), b); }
TEMP_T vector<T> inpt(int n){ vector<T> v(n); for (int i=0; i<n; i++) cin >> v[i]; return v; }

static inline int in(){ int x; scanf("%d", &x); return x; }
static const int dx[] = {0, 0, 1, -1, 1, 1, -1, -1};
static const int dy[] = {1, -1, 0, 0, 1, -1, 1, -1};

struct Field {
  Field(int w, int h) : w(w), h(h) {}
  bool invalid(int x, int y){ return x < 0 || w <= x || y < 0 || h <= y; }
  const int w, h;
};

struct Solver {
  Solver(){}
  int solve(){
  }
};

int main()
{
  int n;
  while (n = in()){
    int robo_x, robo_y;
    robo_x = robo_y = 10;
    set<pair<int, int> > gems;
    for (int i = 0; i < n; i++){
      int x, y;
      x = in();
      y = in();
      gems.insert(make_pair(x, y));
    }
    set<pair<int, int> > robos;
    int m = in();
    for (int i = 0; i < m; i++){
      string s;
      int v;
      int d;
      cin >> s >> v;

      if (s == "N") d = 0;
      else if (s == "W") d = 3;
      else if (s == "E") d = 2;
      else d = 1;
      for (int j = 0; j < v; j++){
        robos.insert(make_pair(robo_x, robo_y));
        robo_x += dx[d];
        robo_y += dy[d];
        robos.insert(make_pair(robo_x, robo_y));
      }
    }
    vector<pair<int, int> > mult;
    set_intersection(gems.begin(), gems.end(),
        robos.begin(), robos.end(),
        back_inserter(mult)
        );

    if (mult.size() == gems.size()){
      puts("Yes");
    }
    else puts("No");
  }

  return (0);
}


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

#define LL long long
#define LD long double
#define SC(t,x) static_cast<t>(x)
#define AR(t) vector < t >
#define PII pair < int, int >
#define PLL pair < LL, LL >
#define PIL pair < int, LL >
#define PLI pair < LL, int >
#define MP make_pair
#define PB push_back
#define PF push_front
#define POB pop_back
#define POF pop_front
#define PRF first
#define PRS second
#define INIT(ar,val) memset ( ar, val, sizeof ( ar ) )
#define lp(loop,start,end) for ( int loop = start; loop < end; ++loop )
#define lpd(loop,start,end) for ( int loop = start; loop > end; --loop )
#define lpi(loop,start,end) for ( int loop = start; loop <= end; ++loop )
#define lpdi(loop,start,end) for ( int loop = start; loop >= end; --loop )
#define qmax(a,b) (((a)>(b))?(a):(b))
#define qmin(a,b) (((a)<(b))?(a):(b))
#define qabs(a) (((a)>=0)?(a):(-(a)))

const int INF = 0x3fffffff;
const int SINF = 0x7fffffff;
const long long LINF = 0x3fffffffffffffff;
const long long SLINF = 0x7fffffffffffffff;
const int MAXN = 1000007;
const int MOD = 998244353;

int n, m;
LL frac[MAXN], rf[MAXN];

void init ();
void input ();
void work ();

void addv ( int &x, int y )
{
	x += y;
	if ( x >= MOD ) x -= MOD;
}

int qpow ( int a, int b )
{
	LL base = a, ans = 1;
	while ( b ){
		if ( b & 1 ) ( ans *= base ) %= MOD;
		( base *= base ) %= MOD;
		b >>= 1;
	}
	return SC ( int, ans );
}

int C ( int n, int m )
{
	return SC ( int, frac[n] * rf[m] % MOD * rf[n-m] % MOD );
}

int getmd ( int n, int m )
{
	return C ( n + m, n );
}

int main()
{
	init();
	input();
	work();
}

void init ()
{
	// Init Everything Here

	ios::sync_with_stdio ( false );

	frac[0] = 1;
	lp ( i, 1, MAXN ) frac[i] = frac[i-1] * i % MOD;
	rf[MAXN-1] = qpow ( frac[MAXN-1], MOD-2 );
	lpdi ( i, MAXN-2, 0 ) rf[i] = rf[i+1] * ( i + 1 ) % MOD;
}

void input ()
{
	// input method

	scanf ( "%d%d", &n, &m );
}

void work ()
{
	// main work

	int ans = 0;
	lpi ( i, 1, qmin ( n, m ) ) addv ( ans, SC ( LL, getmd ( n-i, m-i ) ) * getmd ( i, i ) % MOD );
	ans = SC ( LL, ans ) * qpow ( getmd ( n, m ) * 2 % MOD, MOD-2 ) % MOD;
	addv ( ans, qmax ( n, m ) );
	cout << ans << endl;
}

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

#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()

typedef long long ll;
typedef array<int, 3> tri;
typedef long double ld;

template <class T> istream& operator>>(istream& I, vector<T>& v) {for (T &e: v) I >> e; return I;}
template <class T> ostream& operator<<(ostream &O, const vector<T>& v) {for (const T &e: v) O << e << ' '; return O;}

void _main() {
        int n; cin >> n;
        string s; cin >> s;
        vector<int> w(n), e(n);
        for (int i = 0; i < n; i++) {
                if (i) w[i] = w[i - 1];
                w[i] += s[i] == 'W';
        }

        for (int i = n - 1; i >= 0; i--) {
                if (i + 1 < n) e[i] = e[i + 1];
                e[i] += s[i] == 'E';
        }

        int ans = n;
        for (int i = 0; i < n; i++) {
                ans = min(ans, (i ? w[i - 1] : 0) + (i + 1 < n ? e[i + 1] : 0));
        }

        cout << ans;
}

signed main() {
        ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
//        freopen("input.txt", "r", stdin);
        int _t = 1;
//        cin >> _t;
        while (_t--) _main();
        return 0;
}


#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <limits>
#include <queue>
#include <iomanip>
#include <set>
//#include <bits/stdc++.h>
template<typename T> bool chmax(T &a,T b){if(a<b){a=b;return true;}return false;}
template<typename T> bool chmin(T &a,T b){if(a>b){a=b;return true;}return false;}
using namespace std;
#define ALL(X) X.begin(),X.end()
using ll = long long int;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<vvll> vvvll;
const int MOD=1000000007;
//const int MOD=998244353;
const int INTMAX=2147483647;
const ll LLMAX=9223372036854775807;

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

    ll N;
    cin>>N;
    vll L(2*N);
    for(ll i=0;i<2*N;i++)cin>>L[i];
    sort(ALL(L));
    ll ans=0;
    for(ll i=0;i<2*N;i++){
        ans+=L[i];
        i++;
    }
    cout<<ans<<endl;

    return 0;
}

#include<stdio.h>
#include<algorithm>
#define reg register
#define ri reg int
#define rep(i, x, y) for(ri i = x; i <= y; ++i)
#define nrep(i, x, y) for(ri i = x; i >= y; --i)
#define DEBUG 1
#define ll long long
#define max(i, j) (i) > (j) ? (i) : (j)
#define min(i, j) (i) < (j) ? (i) : (j)
struct IO {
	#define MAXSIZE (1 << 20)
	#define isdigit(x) (x >= '0' && x <= '9')
	char buf[MAXSIZE], *p1, *p2;
	char pbuf[MAXSIZE], *pp;
	#if DEBUG
	#else
		IO() : p1(buf), p2(buf), pp(pbuf) {}
		~IO() {
			fwrite(pbuf, 1, pp - pbuf, stdout);
		}
	#endif
	inline char gc() {
		#if DEBUG
    		return getchar();
		#endif
    	if(p1 == p2)
			p2 = (p1 = buf) + fread(buf, 1, MAXSIZE, stdin);
    	return p1 == p2 ? ' ' : *p1++;
	}
	inline bool blank(char ch) {
    	return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t';
	}
	template <class T>
	inline void read(T &x) {
    	register double tmp = 1;
    	register bool sign = 0;
    	x = 0;
    	register char ch = gc();
    	for(; !isdigit(ch); ch = gc())
    		if(ch == '-') sign = 1;
    	for(; isdigit(ch); ch = gc())
			x = x * 10 + (ch - '0');
    	if(ch == '.')
			for(ch = gc(); isdigit(ch); ch = gc())
        		tmp /= 10.0, x += tmp * (ch - '0');
    	if(sign) x = -x;
	}
	inline void read(char *s) {
		register char ch = gc();
		for(; blank(ch); ch = gc());
		for(; !blank(ch); ch = gc())
			*s++ = ch;
    	*s = 0;
	}
	inline void read(char &c) {
    	for(c = gc(); blank(c); c = gc());
	}
	inline void push(const char &c) {
		#if DEBUG
    		putchar(c);
		#else
    		if(pp - pbuf == MAXSIZE) {
				fwrite(pbuf, 1, MAXSIZE, stdout);
				pp = pbuf;
			}
    		*pp++ = c;
		#endif
	}
	template <class T>
	inline void write(T x) {
    	if(x < 0) {
			x = -x;
			push('-');
		}
    	static T sta[35];
    	T top = 0;
    	do{
			sta[top++] = x % 10;
			x /= 10;
    	}while(x);
    	while(top)
			push(sta[--top] + '0');
	}
	template <class T>
	inline void write(T x, char lastChar) {
    	write(x);
		push(lastChar);
	}
} io;
int a[110], n, ans;
int main() {
	io.read(n);
	rep(i, 1, n * 2) io.read(a[i]);
	std::sort(a + 1, a + 2 * n + 1);
	rep(i, 1, n) ans += a[2 * i - 1];
	io.write(ans);
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i, n) for (ll i = 0; i < n; ++i)
#define P pair<ll, ll>
#define Graph vector<vector<ll>>
#define fi first
#define se second
constexpr ll mod = 1000000007;
constexpr ll INF = (1ll << 60);
constexpr double pi = 3.14159265358979323846;
template <typename T>
inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T>
inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}

int main() {
    ll N, H, W;
    cin >> N >> H >> W;
    cout << (N - H + 1) * (N - W + 1) << "\n";
    return 0;
}

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

int main(){
  	int a,b;
  cin >> a >> b;
  cout << max((2*max(a,b))-1, a+b) << endl;
  return 0;
}


#include<iostream>
#include<algorithm>
using namespace std;
static const int INFTY = (1 << 21);
int main(){
	int t[105][105];int c[105][105];
	int n,m,a,b,cost,time,kk,p,q,r;
	while(cin >> n >> m,n,m){
		for(int i=1;i<105;i++){
			for(int j=1;j<105;j++){
				t[i][j] = c[i][j] = INFTY;
			}
		}
		for(int i = 0;i < n;i++){
			cin >> a >> b >> cost >> time;
			t[a][b] = time;
			t[b][a] = time;
			c[a][b] = cost;
			c[b][a] = cost;
		}
		for(int k=1;k<=m;k++){
			for(int i=1;i<=m;i++){
				if(t[i][k] == INFTY) continue;
				for(int j=1;j<=m;j++){
					if(t[i][k] == INFTY) continue;
					t[i][j] = min(t[i][j],t[i][k]+t[k][j]);
					c[i][j] = min(c[i][j],c[i][k]+c[k][j]);
				}
			}
		}
		cin >>  kk;
		for(int i=0;i<kk;i++){
			cin >> p >> q >> r;
			if(r == 0) cout << c[p][q] << endl;
			else cout << t[p][q] << endl;
		}
	}
	return 0;
}

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
	string s, t, r;
	int n, a, b;
	cin >> s >> n;
	while (n--) {
		cin >> t >> a >> b;
		if (t == "print")
			cout << s.substr(a, b - a + 1) << endl;
		else if (t == "reverse")
			reverse(s.begin() + a, s.begin() + b + 1);
		else {
			cin >> r;
			s.replace(a, b - a + 1, r);
		}
	}
}


/// Bismillahir Rahmanir Rahim
//Author: Tanvir Hussain
//ICE,NSTU
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
const long long MOD = 1000000007;
#define SET(x) memset(x, 0, sizeof(x))
#define SET2d(x,m,n) memset(x, 0, sizeof(x[0][0]) * m * n)
#define SETBOOL(x) memset(x,false,sizeof(x))
#define CLR(x) memset(x, -1, sizeof(x))
#define CLR2d(x,m,n) memset(x, -1, sizeof(x[0][0]) * m * n)
#define mp make_pair
#define PII pair<int, int>
#define pf printf
#define sf scanf
#define ALL(x) x.begin(),x.end()
#define pb push_back
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define np std::string::npos
#define highest(x) numeric_limits<x>::max()
#define lowest(x) numeric_limits<x>::min()
#define Inf INFINITY
#define minv(v) *min_element(v.begin(),v.end())
#define maxv(v) *max_element(v.begin(),v.end())
#define cases(cs,t) for(int cs=1;cs<=t;cs++)
#define PI acos(-1)
#define no1 __builtin_popcount
#define BOUNDARY(i, j) ((i >= 0 && i < row) && (j >= 0 && j < column))
#define uniq(vec) vec.resize(distance(vec.begin(),unique(vec.begin(),vec.end())))
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define sz(a) int(a.size())
#define ff first
#define ss second
#define endl "\n"
#define forch(it,s) for(auto it:s)
#define each(it,s) for(auto it = s.begin(); it != s.end(); ++it)
#define rep(i,a) for(int i=0; i<a;i++)
#define rep1(i,a,b) for(int i=(a);i<=(b);++i)
#define irep(i,b,a) for(int i=(b);i>=(a);--i)
#define bits(n) __builtin_popcount(n)
#define maxpq priority_queue<int>
#define minpq priority_queue<int, vector<int>, greater<int> >

int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);}
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pair<int,int>> vpii;
typedef tree<pair<int, int>,null_type,less<pair<int, int>>,rb_tree_tag,tree_order_statistics_node_update> ordered_multiset;
int dx8[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dy8[] = {1,-1, 1, -1, 0, 0, -1, 1};
int dx4[] = {0, 0, 1, -1};
int dy4[] = {1, -1, 0, 0};
const int maxx=100005;

//this fuction sorts vector pair according to first element in descending order.
bool sortinrev(const pair<int,int> &a,const pair<int,int> &b)
{
    return a.first>b.first;
}

template<typename T>inline T Bigmod(T base, T power, T MOD){
    T ret=1;
    while(power)
    {
        if(power & 1)ret=(ret*base)%MOD;
        base=(base*base)%MOD;
        power>>=1;
    }
    return ret;
}
double sq(double x) {return x*x;}
ll po(ll b,ll p){
    ll res=1;
    while(p){
        res*=b;
        p--;
    }
    return res;
}
ll lg2(ll x){
    ll res=0;
    while(x>1){
        res++;
        x/=2ll;
    }
    return res;
}
void solve(){
    int n,u,v;
    cin>>n>>u>>v;
    u--,v--;
    vi edg[n];
    rep(i,n-1){
        int u,v;
        cin>>u>>v;
        u--,v--;
        edg[u].pb(v);
        edg[v].pb(u);
    }
    vi taka(n,-1),akoi(n,-1);
    queue<int>q;
    taka[u]=0;
    q.push(u);
    while(!q.empty()){
        int u=q.front();
        q.pop();
        forch(it,edg[u]){
            if(taka[it]==-1){
                taka[it]=taka[u]+1;
                q.push(it);
            }
        }
    }
    akoi[v]=0;
    q.push(v);
    while(!q.empty()){
        int u=q.front();
        q.pop();
        forch(it,edg[u]){
            if(akoi[it]==-1){
                akoi[it]=akoi[u]+1;
                q.push(it);
            }
        }
    }
    int ans=0;
    rep(i,n){
        if(taka[i]<akoi[i]){
            ans=max(ans,akoi[i]);
        }
    }
    cout<<(ans-1)<<endl;
}

signed main()

{
    IOS;
    /*#ifndef ONLINE_JUDGE
        freopen ("data.in","r",stdin);
        freopen ("data.out","w",stdout);
    #endif*/
    int t;
    t=1;
    while(t--){
        solve();
    }

     return 0;

}
///Alhamdulillah

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

vector<int>adj[100003],leaf;
int par[100003],depth[100005],sparse[100005][20],root=0,lz=0;

int lca(int p,int q)
{

    int a,b,c,d,lp,i,j;

    if(depth[p]<depth[q])
    {
        c=p; p=q; q=c;
    }

    for(j=19;j>=0;j--)
    {
         if((depth[p]-(1 << j))>=depth[q])
         {
             p=sparse[p][j];  if(depth[p]==depth[q])break;
         }
    }

    if(p==q){ return p; }
    else
    {
         for(j=19;j>=0;j--)
         {
             if(sparse[p][j]!=0 && sparse[p][j]!=sparse[q][j])
             {

                 p=sparse[p][j]; q=sparse[q][j];

                 if(par[p]==par[q])break;
             }

         }

         return par[p];
    }

}

void dfs(int src)
{
    int sz=adj[src].size();

    if(sz==1 && src!=root){   leaf.push_back(src);  lz++;   }

    for(int lp=0;lp<sz;lp++)
    {
        int u=adj[src][lp];

        if(u!=root && par[u]==0)
        {
            par[u]=src; sparse[u][0]=src; depth[u]=depth[src]+1;
            dfs(u);

        }

    }

}

int main()
{

    int n,m,a,b,i,j,u,v,ans,z,x,y,fr,sc,tr,w;
    scanf("%d %d %d",&n,&u,&v);

    for(i=1;i<=n-1;i++)
    {
        scanf("%d %d",&a,&b);
        adj[a].push_back(b); if(root==0){  if(adj[a].size()==2)root=a;  }
        adj[b].push_back(a); if(root==0){  if(adj[b].size()==2)root=b;  }

    }

    if(n==2)printf("0\n");
    else
    {
       dfs(root);

       for(j=1;j<=19;j++)
       {
           for(i=1;i<=n;i++)
           {
               if(sparse[i][j-1]!=0)
               {
                   sparse[i][j]=sparse[sparse[i][j-1]][j-1];
               }
           }
       }

       m=lca(u,v);

       ans=(depth[v]-depth[m])+(depth[u]-depth[m]); ans=ans-1;

       for(i=0;i<lz;i++)
       {
           y=leaf[i]; m=lca(u,y); w=lca(v,y);

           fr=(depth[u]-depth[m])+(depth[y]-depth[m]);
           sc=(depth[v]-depth[w])+(depth[y]-depth[w]);

           if(fr<sc)
           {
               if(sc-1>ans)ans=sc-1;
           }

       }

       printf("%d\n",ans);

    }

    return 0;
}


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

// 1個置くと3増えて全体でN*Q
// クオリティQは3の倍数になる必要がある(N != 0 mod 3)

using block = vector<string>;
// Quality 1
block b3 = {
        "a..",
        "a..",
        ".aa"
};
// Quality 3
block b4 = {
        "aacd",
        "bbcd",
        "cdaa",
        "cdbb"
};
// Quality 3
block b5 = {
        "aabbc",
        "bc..c",
        "bc..d",
        "c.ccd",
        "cddee"
};
// Quality 3
block b7 = {
        "ac..c..",
        "ac..c..",
        "b.cc.cc",
        "bc..c..",
        "ac..c..",
        "a.cc.cc",
        ".aabbaa"
};

void horizontal_add(block &a, block b){
    for (int i = 0; i < a.size(); ++i) a[i] += b[i];
}

void vertical_add(block &a, block b){
    a.insert(a.end(), b.begin(), b.end());
}

block solve_k(int n, block b){
    block res = b;
    for (int i = 0; i < n - 1; ++i) {
        horizontal_add(res, b);
    }
    block unit = res;
    for (int i = 0; i < n - 1; ++i) {
        vertical_add(res, unit);
    }
    return res;
}

block solve(int n){
    block res;
    if (n % 3 == 0) return solve_k(n/3, b3);
    if (n % 4 == 0) return solve_k(n/4, b4);
    int t = __builtin_ctz(n);
    int m = n >> t; // m >= 5 が保証される
    if ((m - 1) % 4) res = b7;
    else res = b5;
    for (int i = 0; i < (m - 5) / 4; ++i) {
        horizontal_add(res, block(res.size(), "...."));
        string s(res.size(), '.');
        block below(4, s);
        horizontal_add(below, b4);
        vertical_add(res, below);
    }
    return solve_k(n/m, res);
}

int main() {
    int N;
    cin >> N;
    if (N == 2) {
        cout << -1 << "\n";
    } else {
        auto ans = solve(N);
        for (int i = 0; i < N; ++i) {
            cout << ans[i] << "\n";
        }
    }
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pli = pair<ll, int>;
using pil = pair<int, ll>;
using uint = unsigned int;
template <typename T>
using Graph = vector<vector<T>>;
const int MOD = 1e9 + 7;
const ld PI = acosl(-1);

int mdigit(ll val) {
    int l = 0, r = 61;
    while (r - l > 1) {
        int mid = (l + r) / 2;
        ll bit = (1LL << r) - (1LL << mid);
        (val & bit ? l : r) = mid;
    }
    return l;
}

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

    int T;
    cin >> T;
    for (int a = 0; a < T; ++a) {
        int N;
        cin >> N;
        vector<ll> A(N);
        for (int i = 0; i < N; ++i)
            cin >> A[i];
        string S;
        cin >> S;

        bool isok = true;
        vector<ll> v(61);
        for (int i = N - 1; i >= 0; --i) {
            int tmp;
            while (A[i] && v[tmp = mdigit(A[i])])
                A[i] ^= v[tmp];
            if (A[i]) {
                if (S[i] == '0')
                    v[tmp] = A[i];
                else {
                    isok = false;
                    break;
                }
            }
        }

        cout << !isok << '\n';
    }

    return 0;
}