#include <functional>
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <assert.h>
#include <bitset>
#include <string>
#include <cstdio>
#include <math.h>
#include <complex>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <set>
#include <bitset>
#include <map>
using namespace std;

#define int64 long long
#define mp make_pair

#ifdef _DEBUG
	const int N = 210;
#else
	const int N = 210;
#endif

int n;
string s;
bool used[N][N][N];

void dfs(int b, int g, int r)
{
	if (used[b][g][r]) return;
	used[b][g][r] = true;
	if (b >= 1 && g >= 1) dfs(b - 1, g - 1, r + 1);
	if (b >= 1 && r >= 1) dfs(b - 1, g + 1, r - 1);
	if (g >= 1 && r >= 1) dfs(b + 1, g - 1, r - 1);
	if (b >= 2) dfs(b - 1, g, r);
	if (g >= 2) dfs(b, g - 1, r);
	if (r >= 2) dfs(b, g, r - 1);
}

int main()
{
#ifdef _DEBUG
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
	scanf("%d\n", &n);
	cin >> s;
	int b = 0, g = 0, r = 0;
	for (int i = 0; i < n; i++)
		if (s[i] == 'B') b++;
		else if (s[i] == 'G') g++;
		else r++;
	memset(used, false, sizeof(used));
	dfs(b, g, r);
	if (used[1][0][0]) cout << 'B';
	if (used[0][1][0]) cout << 'G';
	if (used[0][0][1]) cout << 'R';
    return 0;
}


#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int d[21][21][1<<8][1<<8];
int B[21],C[21];
int a[21];
char s[21][21];
int cx[10],cy[10],bx[10],by[10];
int n,m,cnt,bcnt;
struct node
{
    int x,y,s1,s2;
};
bool in(int x,int y)
{
    return x>=0&&x<n&&y>=0&&y<m;
}
bool check(int x,int y,int nx,int ny,int gx,int gy)
{
    if(x==gx&&gy<y)
    {
        if(nx>x)
            return 1;
    }
    if(nx==gx&&gy<ny)
    {
        if(x>nx)
            return 1;
    }
    return 0;
}
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
void bfs(int sx,int sy)
{
    queue<node>q;
    d[sx][sy][0][0]=0;
    node tmp;tmp.x=sx;tmp.y=sy;tmp.s1=0;tmp.s2=0;
    q.push(tmp);
    while(!q.empty())
    {
        node now=q.front();
        q.pop();
        int x=now.x;
        int y=now.y;
        int s1=now.s1;
        int s2=now.s2;
        int nx,ny,ns1,ns2;
        for(int k=0;k<4;k++)
        {
            int nx=x+dx[k];
            int ny=y+dy[k];
            ns1=s1;ns2=s2;
            if(!in(nx,ny)||s[nx][ny]!='.')
                continue;
            for(int i=0;i<cnt;i++)
            {
                if(check(x,y,nx,ny,cx[i],cy[i]))
                    ns1^=(1<<i);
            }
            for(int i=0;i<bcnt;i++)
            {
                if(check(x,y,nx,ny,bx[i],by[i]))
                    ns2^=(1<<i);
            }
            if(d[nx][ny][ns1][ns2]==-1)
            {
                d[nx][ny][ns1][ns2]=d[x][y][s1][s2]+1;
                tmp.x=nx;tmp.y=ny;tmp.s1=ns1;tmp.s2=ns2;
                q.push(tmp);
            }
        }
    }
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
        scanf("%s",s[i]);
    int sx,sy;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(s[i][j]>='1'&&s[i][j]<='8')
            {
                cx[s[i][j]-'1']=i;
                cy[s[i][j]-'1']=j;
                cnt++;
            }
            else if(s[i][j]=='B')
            {
                bx[bcnt]=i;
                by[bcnt]=j;
                bcnt++;
            }
            else if(s[i][j]=='S')
            {
                sx=i;sy=j;
            }
        }
    }
    for(int i=0;i<cnt;i++)
        scanf("%d",&a[i]);
    memset(d,-1,sizeof(d));
    s[sx][sy]='.';
    bfs(sx,sy);
    int ans=0;
    for(int i=0;i<(1<<cnt);i++)
    {
        int cur=0;
        if(d[sx][sy][i][0]==-1)
            continue;
        for(int j=0;j<cnt;j++)
        {
            if(i&(1<<j))
                cur+=a[j];
        }
        ans=max(ans,cur-d[sx][sy][i][0]);
    }
    printf("%d",ans);
}


#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
	int M,n, a, b, c;
    cin.tie(0);
    cin >> n >> a >> b >> c;
    M =min(min(a, b), c);
	if (n == 1)
	{
		cout << 0;
	}
	if (M == c && n!=1)
	{
		cout << (min(a, b) + c * (n - 2));
	}
	else if(n!=1 && M!=c )
	{
		cout << (min(a, b)*(n - 1));
	}
}


#include <bits/stdc++.h>
#include <ext/pb_ds/detail/standard_policies.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define FIO                     ios::sync_with_stdio(false); cin.tie(nullptr)
#define TC(t)                   int t; cin >> t; for(int i = 1; i <= t; i++)
#define ll                      long long int
#define ull                     unsigned long long int
#define lll                     __int128
#define lld                     long double
#define loop(i, a, b)           for(ll i = a; i <= b; i++)
#define loop2(i, b, a)          for(ll i = b; i >= a; i--)
#define ini(x, y)               memset(x, y, sizeof(x))
#define all(x)                  x.begin(), x.end()
#define all2(x)                 x.rbegin(), x.rend()
#define sz(x)                   (ll)x.size()
#define pb                      push_back
#define ppb                     pop_back
#define mp                      make_pair
#define ff                      first
#define ss                      second
#define M                       1000000007
#define endl                    '\n'
#define bits(x)                 __builtin_popcountll(x)
#define zrbits(x)               __builtin_ctzll(x)
#define vl                      vector<ll>
#define pll                     pair<ll,ll>
#define vpll                    vector<pll>
#define uni(x)                  x.erase(unique(all(x)), x.end())
#define ordered_set             tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update>
#define multi_ordered_set       tree<ll, null_type, less_equal<ll>, rb_tree_tag, tree_order_statistics_node_update>
#define mxheap                  priority_queue<ll>
#define mnheap                  priority_queue<ll, vector<ll>, greater<ll>>
#define mxheap2                 priority_queue<pair<ll,ll>>
#define mnheap2                 priority_queue<pair<ll,ll>, vector<pair<ll,ll>>, greater<pair<ll,ll>>>

const int N = 2e5 + 5;
const int L = 20;
const int MX = 1e9 + 10;
const ll INF = 1e18;

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

using namespace std;
using namespace __gnu_pbds;

inline ll uceil(ll a,ll b) {return (a % b ? a / b + 1 : a / b);}
inline ll mod(ll x) {return ( (x % M + M) % M );}
ll ulog(ll val, ll base) {ll cnt = 0; val /= base; while(val) {cnt++; val /= base;} return cnt;}
ll power(ll a, ll b) {ll res = 1; while (b) {if (b & 1) res = res * a; a = a * a; b >>= 1;} return res;}
ll modpow(ll a, ll b) {ll res = 1; while (b) {if (b & 1) res = res * a % M; a = a * a % M; b >>= 1;} return res;}

#ifndef ONLINE_JUDGE
#define deb(x)                  cerr << #x << " = " << x << endl;
#define deb2(x, y)              cerr << #x << " = " << x << ", " << #y << " = " << y << endl;
#define deb3(x, y, z)           cerr << #x << " = " << x << ", " << #y << " = " << y << ", " << #z << " = " << z << endl;
#define deb4()                  cerr << endl;
#define done                    cerr << "Line " << __LINE__ << " is done" << endl;
#else
#define deb(x)
#define deb2(x, y)
#define deb3(x, y, z)
#define deb4()
#define done
#endif

template<typename T> ostream& operator<<(ostream& os, const vector<T>& v) {for(auto& x : v) os << x << " "; return os;}
template<typename T> ostream& operator<<(ostream& os, const set<T>& v) {for(auto& x : v) os << x << " "; return os;}
template<typename T, typename S> ostream& operator<<(ostream& os, const pair<T, S>& p) {os << p.first << ' ' << p.second; return os;}
template<typename... T> void in(T&... args) {((cin >> args), ...);}
template<typename... T> void out(T&&... args) {((cout << args << endl), ...);}
template<typename... T> void out2(T&&... args) {((cout << args << " "), ...);}
template<typename... T> void out3(T&&... args) {((cout << args << " "), ...); cout << endl;}

ll fact[N], invfact[N];

void precompute() {
        fact[0] = invfact[0] = 1;
        for (int i = 1; i < N; i++) {
                fact[i] = fact[i - 1] * i % M;
        }
        invfact[N - 1] = modpow(fact[N - 1], M - 2);
        for(int i = N - 2; i >= 0; i--) {
                invfact[i] = invfact[i + 1] * (i + 1) % M;
        }
}

ll nCr(ll n, ll r) {
        if (r < 0 || n < 0 || r > n) return 0;
        return fact[n] * invfact[r] % M * invfact[n - r] % M;
}

void solve() {
        ll n, k;
        cin >> n >> k;
        ll ans = 0;
        loop(i, 0, min(k, n)) {
                ans += nCr(n, i);
                ans %= M;
        }
        cout << ans << endl;
}

signed main () {
        precompute();
        #ifndef ONLINE_JUDGE
                freopen("input.txt", "r", stdin);
                freopen("output.txt", "w", stdout);
        #endif
        FIO;
        // TC(t)
        solve();
        return 0;
}


#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

int main() {
    int a, b, c, d, e, f, s = 0;

    cin >> a >> b >> c >> d >> e >> f;

    switch(e > f){
    case true:
        while(a > 0 && d > 0){
            a--;
            d--;
            s+= e;
        }
        while(b > 0 && c > 0 && d > 0){
            b--;
            c--;
            d--;
            s+= f;
        }
    case false:
        while(b > 0 && c > 0 && d > 0){
            b--;
            c--;
            d--;
            s+= f;
        }
        while(a > 0 && d > 0){
            a--;
            d--;
            s+= e;
        }
    }

    cout << s;

    return 0;
}


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

#define ll long long

vector <ll> v;
vector <ll> vv;
set <ll> st;

ll x,y,z;
string s,s1,s2;

void memset_ll(ll a[], ll v, ll n)
{
    for(ll i=0; i<n; i++)
        a[i]=v;
}
void memset_s(char a[], char v, ll n)
{
    for(ll i=0; i<n; i++)
        a[i]=v;
}

int compare(const void * a, const void * b)
{
    return ( *(ll*)a - *(ll*)b );
}
void q_sort(ll a[], ll n)
{
    qsort(a, n, sizeof(ll), compare);
}

static int compare1 (const void * a, const void * b)
{
    if (*(double*)a > *(double*)b)
        return 1;
    else if (*(double*)a < *(double*)b)
        return -1;
    else
        return 0;
}
void q_sort_d(double a[], ll n)
{
    qsort(a, n, sizeof(double), compare1);
}

ll sum(ll n)
{
    ll i=0,a[6],j,k=0;
    while(n>0)
    {
        a[i]=n%10;
        n/=10;
        i++;
    }
    for(j=0; j<i; j++)
        k+=a[j];
    return k;
}

string trans_upper(string ss)
{
    transform(ss.begin(),ss.end(),ss.begin(), ::toupper);
    return ss;
}

ll power(ll a, ll b)
{
    ll pow = 1;
    while ( b )
    {
        if ( b & 1 )
        {
            pow = pow * a;
            --b;
        }
        a = a*a;
        b = b/2;
    }
    return pow;
}

ll fact(ll n)
{
    ll f=1,i;
    for(i=1; i<=n; i++)
        f=f*i;
    return f;
}

ll is_prime(ll n)
{
    ll i,j,k=1;
    for(i=2; i<=n/2; i++)
    {
        if(n%i==0)
        {
            k=0;
            break;
        }
    }
    return k;
}

int main()
{
    ll t,l,p,q,n,m,o=0,r,i,j,h,k,e=0,d=0,f=0,g=0;
    ll temp=0,nl,np;
    double p1,p2=0.0,p3=0.0,p4,p5,p6,pp,ppp;
    p1=3.1415926536;
    string ss,s3[7];
    cin>>s;
    cin>>ss;
    s3[0]="saturday";
    s3[1]="sunday";
    s3[2]="monday";
    s3[3]="tuesday";
    s3[4]="wednesday";
    s3[5]="thursday";
    s3[6]="friday";
    for(i=0;i<7;i++)
    {
        t=s.compare(s3[i]);
        if(t==0)
            p=i;
        t=ss.compare(s3[i]);
        if(t==0)
            q=i;
    }
    if(q<p)
        q+=7;
    r=q-p;
    if(r==0||r==3||r==2)
    {
        cout<<"YES";
        return 0;
    }
    cout<<"NO";

    return 0;
}


#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
//#define int long long
using namespace std;
typedef long long ll;
typedef long double ldb;
const int Mod=1e9+7;
const int blo=32767;
const ldb Pi=acos(-1.0);
struct complex{
	ldb x,y;
	complex (ldb xx=0,ldb yy=0){ x=xx; y=yy;}
};
ll n; int m,bit,len,rev[550000];
ll fac[1100000],inv[1100000],invfac[1100000];
ll A[550000],B[550000],aa[550000],bb[550000];
complex a[550000],b[550000],c[550000],d[550000],
		e[550000],f[550000],g[550000],h[550000];
complex operator+(complex a,complex b){ return complex(a.x+b.x,a.y+b.y);}
complex operator-(complex a,complex b){ return complex(a.x-b.x,a.y-b.y);}
complex operator*(complex a,complex b){ return complex(a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x);}

void FFT(complex *A,int type){
	for (int i=0;i<len;i++)
		if (i<rev[i]) swap(A[i],A[rev[i]]);
	for (int mid=1;mid<len;mid<<=1){
		complex Wn(cos(Pi/mid),type*sin(Pi/mid));
		for (int R=mid<<1,j=0;j<len;j+=R){
			complex w(1,0);
			for (int k=0;k<mid;k++,w=w*Wn){
				complex x=A[j+k],y=w*A[j+mid+k];
				A[j+k]=x+y; A[j+mid+k]=x-y;
			}
		}
	}
}
void MTT(ll *A,ll *B,ll *res){
	memset(a,0,sizeof(a)); memset(b,0,sizeof(b));
	memset(c,0,sizeof(c)); memset(d,0,sizeof(d));
	memset(e,0,sizeof(e)); memset(f,0,sizeof(f));
	memset(g,0,sizeof(g)); memset(h,0,sizeof(h));
	for(int i=0;i<=m;i++) a[i].x=A[i]/blo,b[i].x=A[i]%blo;
	for(int i=0;i<=m;i++) c[i].x=B[i]/blo,d[i].x=B[i]%blo;
	FFT(a,1); FFT(b,1);
	FFT(c,1); FFT(d,1);
	for(int i=0;i<len;i++){
		e[i]=a[i]*c[i]; f[i]=a[i]*d[i];
		g[i]=b[i]*c[i]; h[i]=b[i]*d[i];
	}
	FFT(e,-1); FFT(f,-1);
	FFT(g,-1); FFT(h,-1);
	for (int i=0;i<=m;i++) res[i]=((ll)(e[i].x/len+0.5)%Mod*blo%Mod*blo%Mod+
									(ll)(f[i].x/len+0.5)%Mod*blo%Mod+
									(ll)(g[i].x/len+0.5)%Mod*blo%Mod+
									(ll)(h[i].x/len+0.5)%Mod)%Mod;
}
void mult(ll *A,ll *B,ll x){
    ll tmp=1;
    for (int i=0;i<=m;i++) bb[i]=B[i]*tmp%Mod,tmp=tmp*x%Mod;
    for (int i=0;i<=m;i++) aa[i]=A[i];
    MTT(aa,bb,B);
}
ll C(int n,int m){
	if (n<m) return 0;
	return fac[n]*invfac[m]%Mod*invfac[n-m]%Mod;
}
int main(){
	scanf("%lld%d",&n,&m);
	if (n>m){ puts("0"); return 0;}
	fac[0]=1; for (int i=1;i<=1000000;i++) fac[i]=fac[i-1]*i%Mod;
	inv[1]=1; for (int i=2;i<=1000000;i++) inv[i]=(Mod-Mod/i)*inv[Mod%i]%Mod;
	invfac[0]=1; for (int i=1;i<=1000000;i++) invfac[i]=invfac[i-1]*inv[i]%Mod;

	len=1; bit=0; while (len<=m+m) len<<=1,bit++;
	for (int i=0;i<len;i++) rev[i]=(rev[i>>1]>>1)|((i&1)<<(bit-1));

    B[0]=1;
    for (int i=1;i<=m;i++) A[i]=invfac[i];
	ll t=2;
	while (n){
		if (n&1) mult(A,B,t);
		mult(A,A,t);
		t=t*t%Mod; n>>=1;
	}
    ll ans=0;
    for (int i=0;i<=m;i++) ans=(ans+B[i]*fac[i]%Mod*C(m,i)%Mod)%Mod;
    printf("%lld\n",ans);
	return 0;
}


#include<iostream>
#include<math.h>
using namespace std;
int main(){
	int x,y,z;
	cin>>x>>y;
	z=sqrt(x*x*1.0+y*y*1.0);
	if(z==sqrt(x*x*1.0+y*y*1.0))
	{
		cout<<"black";
		return 0;}
	if(z%2==0)
		if((x>=0&&y>=0 )|| (x<=0 &&y<=0))
			cout<<"black";
		else cout<<"white";
	else
		if((x>=0&&y>=0 )|| (x<=0 &&y<=0))
			cout<<"white";
		else cout<<"black";

	return 0;

}


//
//  main.cpp
//  irinasolves
//
//  Created by Irina Korneeva on 02/08/16.
//  Copyright © 2016 Irina. All rights reserved.
//

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdlib>
struct el {
    long long x, y;
};
using namespace std;
int main(int argc, const char * argv[]) {
    long long d, k, a, b, t;
    cin >> d >> k >> a >> b >> t;
    if(k > d) {
        cout << d * a;
        return 0;
    }
    if(a  >= b ) {
        cout << b * d;
        //cout << "ir";
    } else {
            long long n = d/k;
            long long ans =  n * a * k + (n - 1) * t;
            if(t + k * a > k * b) {
                    cout << k * a + (d - k) * b;
                   // cout << "ir";
            } else if(d % k) {
                ans += t + (d - n * k) * a;
                cout << min(ans, n * a * k + (n - 1) * t +  (d - n * k) * b);
            } else {
                cout << ans;
            }
    }
}


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

struct matrix
{
    ll v[7][7];
};
matrix bin,ans;
ll mod,x,y,sp_x,sp_y,t;

matrix mult(matrix a,matrix b)
{
    matrix temp;
    for(int i=0;i<6;i++)
        for(int j=0;j<6;j++)
        {
            temp.v[i][j]=0;
            for(int k=0;k<6;k++)
                temp.v[i][j]=(temp.v[i][j]+a.v[i][k]*b.v[k][j]-1)%mod+1;
        }
    return temp;
}

matrix quick(matrix a,matrix b,ll n)
{
    while(n)
    {
        if(n&1)
            a=mult(a,b);
        b=mult(b,b);
        n>>=1;
    }
    return a;
}

void init()
{
    memset(ans.v,0,sizeof(ans.v));
    ans.v[0][0]=x;
    ans.v[0][1]=y;
    ans.v[0][2]=sp_x;
    ans.v[0][3]=sp_y;
    ans.v[0][4]=0;
    ans.v[0][5]=1;

    memset(bin.v,0,sizeof(bin.v));
    for(int i=0;i<4;i++)
        bin.v[0][i]=bin.v[1][i]=1;
    bin.v[0][0]=bin.v[1][1]=2;

    bin.v[2][0]=bin.v[2][2]=1;
    bin.v[3][1]=bin.v[3][3]=1;
    bin.v[5][5]=bin.v[5][4]=1;
    for(int i=0;i<5;i++)
        bin.v[4][i]=1;
}

//void debug(const matrix &a)
//{
//    cout<<"**********"<<endl;
//    for(int i=0;i<6;i++)
//    {
//        for(int j=0;j<6;j++)
//            cout<<a.v[i][j]<<' ';
//        cout<<endl;
//    }
//    cout<<"**********"<<endl;
//}

int main()
{
//    freopen("in.txt","r",stdin);
    cin>>mod>>x>>y>>sp_x>>sp_y>>t;
    init();
//    debug(ans);
    ans=quick(ans,bin,t);
//    debug(ans);
//    debug(bin);
    cout<<(ans.v[0][0]%mod-1+mod)%mod+1<<" "<<(ans.v[0][1]%mod-1+mod)%mod+1<<endl;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define f first
#define s second
#define pii pair<int,int>
#define forn(a,b,c) for(int a=b;a<=c;a++)
#define ford(a,b,c) for(int a=b;a>=c;a--)
const int N=1e5+5;
const int mod=1e9+7;
int add(int x, int y){ x+=y;if(x>=mod) x-=mod;return x;}
int sub(int x, int y){ x-=y;if(x<0) x+=mod;return x;}
int mul(int x, int y){ x=(ll)x*y%mod;return x;}
int powmod(int x, int k){ int ans=1;for(;k;k>>=1,x=mul(x,x)) if(k&1) ans=mul(ans,x);return ans;}
int inv(int x){ return powmod(x,mod-2);}
int dv(int x, int y){ x=(ll)x*inv(y)%mod; return x;}
int mu[N],prime[N];
vector<int>primes;
void precalc(){
    //sieve with mobius function
    forn(i,2,N-1){
        prime[i]=1;
        mu[i]=1;
    }
    forn(i,2,N-1){
        if(prime[i]){
            for(int j=i;j<N;j+=i){
                prime[j]=false;
                mu[j]*=-1;
            }
            for(ll j=(ll)i*i;j<N;j+=(ll)i*i){
                mu[j]=0;
            }
        }
    }
}
int main()
{

    precalc();
    int n;
    scanf("%d",&n);
    int ans=1;
    forn(i,2,n){
        int f=n/i;
        if(mu[i]==1){
            ans=sub(ans,mul(f,inv(n-f)));
        }
        if(mu[i]==-1){
            ans=add(ans,mul(f,inv(n-f)));
        }
    }
    printf("%d\n",ans);
    return 0;
}


// https://codeforces.com/contest/1271/problem/E

/*

Mistake -
1 : The approach that if we cannot make cnt >= k using mid ; then we can never make cnt >= k using any mid greater
than mid is wrong

Reason :
Let say mid = 3 ; and maxx = 11
we can make only cnt = 3 using current mid ( 3 , 6 , 7 ).

But for a greater mid - mid = 4 ; we are allowed to use the odd term after it ( 5 ) too ; and we can unfold its
recursion tree too.
Hence using that ; f(4) = 6.

So at this point - there is a conflict.
Should we reject the binary search or should we modify it.

This time ; this binary search can be modified.
Reason - the best candidate that gives us a greater f(mid) near to mid is mid + 1 ( in case mid is odd ).
This is because mid + 1 is even ; and thus we may use recursion tree of mid+2 also to increase our count !

SO we can check for mid-1 ; mid ; and mid+1.
if f(mid + delta) < k ; then we can say that we need to move left ; and do hi = mid - 1.
Else we may say we can move right and do lo = mid + 1.

*/

/*

Mistake 2 - TLE on test case 16.
Earlier ; I was trying to go on every node ; and I was doing f ( node*2 ) ; and f(2*node + 1) ;

But if we unfold the recursion tree ; we will see that it is a binary tree.
We can easily see that height of tree is logarithmic ; and for n <= 1e18 ; height <= 64.

But ; then what will be the number of nodes in the binary tree ?
It will be (1 << max_height) - 1 ( heights are taken 0 based ).

SO since max height can be upto 64 ; hence number of nodes >= 1e18 ( easily ). So we will get a TLE.

What can we do -
Observation : the nodes in the binary tree are consecutive at every level.
Hence ; if we keep a track of the level ; we will know the number of nodes in that level = (1 << level).

And we can see from the highest node will this entire block is <= maxx. If yes ; we may add 1 << level to answer.
Else ; we can find upto which index this holds true ; and we may add those many nodes !

Thus by maintaining only the max node of any level ; we will do only max_height number of iterations !
And thus we may solve function f() in log(1e18) time.

*/

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

# define C continue;
# define R return

# define D double
# define I insert
# define ll long long
# define ld long double

# define ull unsigned long long
# define ui unsigned int

# define pb push_back
# define pf push_front

# define vi vector < int >
# define vc vector < char >
# define vs vector < string >
# define vb vector < bool >
# define vd vector < D >
# define vll vector < ll >
# define vull vector < ull >
# define vld vector < ld >

# define vvi vector < vector < int > >
# define vvb vector < vector < bool > >
# define vvc vector < vector < char > >
# define vvll vector < vector < ll > >
# define vvd vector < vector < D > >
# define vvld vector < vector < ld > >

# define all(v) (v).begin() , (v).end()
# define allrev(v) (v).rbegin() , (v).rend()
# define allcomp(v) v.begin() , v.end() , comp
# define allrevcomp(v) v.rbegin() , v.rend() , comp

# define pii pair < int , int >
# define pll pair < ll , ll >
# define pld pair < ld , ld >
# define pDD pair < D , D >

# define vpld vector < pld >
# define vpii vector < pii >
# define vpll vector < pll >
# define vpDD vector < pDD >

# define vvpii vector < vector < pii > >
# define F first
# define S second
# define mp make_pair

# define dist(a,b,p,q) sqrt((p-a)*(p-a) + (q-b)*(q-b))

# define pp(n) printf("%.10Lf",n);
# define line cout<<"\n";
# define fast ios_base::sync_with_stdio(false) ; cin.tie(0) ; cout.tie(0);

string vow = "aeiou";

const int dxhorse[] = {-2, -2, -1, -1, 1, 1, 2, 2};
const int dyhorse[] = {1, -1, 2, -2, 2, -2, 1, -1};

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

const ld pie = 3.14159265358979 ;
const ll mod = 1e9 + 7 ;

ll maxx ;
ll cnt = 0 ;

void f ( ll n , ll lev )
{
    if ( n > maxx )
    {
        ll values_this_level = (1LL << lev) ;
        n = n - values_this_level + 1 ;

        cnt += max ( 0LL , maxx - n + 1 ) ;
        return ;
    }

    cnt += (1LL << lev) ;
    f ( n*2 + 1 , lev + 1 ) ;
}

void solve ( int test_case )
{
    cin >> maxx ;
    ll k ; cin >> k ;

    ll ans = 1 ;
    for ( ll lo = 1 , hi = maxx ; lo <= hi ; )
    {
        ll mid = lo + (hi-lo)/2 ;
        bool found = false ;

        for ( int del_mid = -1 ; del_mid <= 1 ; del_mid ++ )
        {
            ll temp = mid + del_mid ;
            if ( temp < 1 ) C ;
            if ( temp > maxx ) C ;

            cnt = 0 ;
            if ( temp % 2 == 0 )
                f ( temp , 0 ) , f ( temp+1 , 0 ) ;
            else
                f ( temp , 0 ) ;

            if ( cnt >= k )
            {
                ans = max ( ans , temp ) ;
                found = true ;
            }
        }

        if ( found )
            lo = mid + 1 ;
        else
            hi = mid - 1 ;
    }

    cout << ans ; line
}

int main()
{fast
    int t = 1;
    // cin >> t;

    for ( int i=0 ; i < t ; i++ ) solve(i);
    return 0;
}


#include <iostream>
#include <vector>
using namespace std;
int main()
{
	int m, n, i=0;
	bool k = 0;
	vector <int> a(0);
	cin >> m >> n;
	a.push_back(n);
	while (n > 0)
	{
		if (n % 2 == 0)
		{
			n /= 2;
			a.push_back(n);
		}
		if (n == m)
		{
			k = true;
			break;
		}
		if(n<m)
		{
			k = false;
			break;
		}
		if (n % 10 == 1)
		{
			n /= 10;
			a.push_back(n);
		}
		if (n == m)
		{
			k = true;
			break;
		}
		if (n<m)
		{
			k = false;
			break;
		}
		if(n % 10 != 1 && n % 2!=0 && n!=m)
		{
			k = false;
			break;
		}
	}
	if (k == true)
	{
		cout << "YES" << endl;
		cout << a.size() << endl;
		for (i = a.size() - 1;i >= 0;i--)
			cout << a[i] << " ";
		cout << endl;
	}
	else
		cout << "NO" << endl;
	return 0;
}


#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <string.h>
#include <string>
#include <math.h>
#include <stack>
#include <map>
#include <sstream>
#include <set>
#include <queue>
#define MAXN 100010
#define pi 3.14159265358979323846
using namespace std;
int n,m;
int main(){
    scanf("%d %d",&n,&m);
    int mx1= n*2,mx2= m*3;
    map<int,int>mp;
    for(int i =2;i<=n*2;i+=2){
        mp[i]++;
    }
    for(int j=3;j<=m*3;j+=3){
        mp[j]++;
    }
    for(int i =1;i<=max(mx1,mx2);i++){
        if(mp[i]>1){
            if(mx1+2<mx2+3){
                mx1+=2;
                mp[mx1]++;
            }else{
                mx2+=3;
                mp[mx2]++;
            }
        }
    }
    printf("%d\n",max(mx1,mx2));
    return 0;
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
double v,r,s,f;
const double pi=3.1415926535897932384626433832795;
const double eps=1e-15;
int n;
int main()
{
	scanf("%d %lf %lf",&n,&r,&v);
	while(n--)
	{
		scanf("%lf %lf",&s,&f);
		double dis=f-s;
		double yu=fmod(dis,2*pi*r);
		int t=floor(dis/(2*pi*r));
		double lo=0,up=2*pi;
		while(lo+eps<up)
		{
			double m=(lo+up)/2;
			if(2*sin(m/2)*r+m*r<yu)
			{
				lo=m;
			}
			else
			{
				up=m;
			}
		}
		double len=(t*(2*pi*r)+up*r);
		printf("%.12f\n",len/v);
	}
}


#include <bits\stdc++.h>
#include <ext\rope>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_cxx;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef double dbl;
//const long double pi = M_PI;
long double eps = 1e-13;

typedef tree<int, pair<int, int>, less<int>, rb_tree_tag,
tree_order_statistics_node_update> Tree;

inline void putint(int x)
{
    char s[9];
    int l = 0;
    while (x)
        s[l++] = '0' + (x % 10), x /= 10;
    while (l--)
        putc(s[l], stdout);
    putc(' ', stdout);
}

inline int getint()
{
    char ch;

    while (ch = getchar(), ch < '0' || ch > '9');

    int x = ch - '0';
    while (ch = getchar(), ch >= '0' && ch <= '9')
    {
        x *= 10;
        x += ch - '0';
    }
    return x;
}

void solve(int n)
{
    int m;
    int x, y;
    m = getint();

    Tree Car;

    for (int i = 1; i <= n; i++)
        Car.insert(mp(i, mp(0, i)));

    set<int> used;
    for (int i = 1; i <= n; i++)
        used.insert(i);

    for (int i = 0; i < m; i++)
    {
        x = getint();
        y = getint();
        used.erase(x);
        y--;

        Tree::iterator it = Car.find_by_order(y);
        if ((it -> second).first != 0 && (it -> second).first != x)
        {
            printf("-1\n");
            return;
        }
        Car.insert(mp(-i, mp(x, (it -> second).second)));
        Car.erase(it);
    }

    for (Tree::iterator it = Car.begin(); it != Car.end(); it++)
        if ((it -> second).first == 0)
            (it -> second).first = *used.begin(),
            used.erase(used.begin());

    vector<int> ans(n + 1, 0);
    vector<char> Used(n + 1, 0);

    for (Tree::iterator it = Car.begin(); it != Car.end(); it++)
        ans[(it -> second).second] = (it -> second).first;

    for (int i = 1; i <= n; i++)
        Used[ans[i]] = 1;
    bool ok = true;
    for (int i = 1; i <= n; i++)
        ok &= Used[i];
    if (!ok)
    {
        printf("-1\n");
        return;
    }

    for (int i = 1; i <= n; i++)
        putint(ans[i]);
    printf("\n");
}

int main()
{
    int i, j;

    #ifndef ONLINE_JUDGE
    freopen("input.txt", "rt", stdin);
    freopen("output.txt", "w", stdout);
    #endif

    int n, m;
    cin >> n;
    solve(n);
}


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

#define mod 1000000009

int pfix(int x) { return x>=mod ? x-mod : x; }
int dfix(int x) { return x<0 ? x+mod : x; }

int ti[1000005];
int fi[1000005];

int main()
{
	int n;
	scanf("%d",&n);
	int dans = min(6,(n-1)*2);
	int btopn = (n-4)>>1;
	register int f = 1;
	register int t = 4;
	for(int i=1; i<=btopn; ++i)
	{
		t = pfix(t<<1);
		f = 1LL*f*dfix(t-3) % mod;
		dans = (dans + 1LL*f*4) % mod;
	}
	if(n>4 && n&1)
	{
		f = 1LL*f*(2*btopn+3) % mod;
		dans = (dans + 1LL*f*2) % mod;
	}

	printf("%lld\n",(2LL*dans*dans+2)%mod);
}


#include <iostream>
#include <fstream>
#include <memory.h>
#include <math.h>
#include <iomanip>
#include <string.h>
#include <sstream>
#include <algorithm>
#include <stdio.h>
#include <time.h>
#include <cctype>

using namespace std;

int main()
{
    int n,m,i,j,a,b;
    cin>>n>>m>>i>>j>>a>>b;
    if ((i==1) && (j==1)) cout<<0<<endl;
    else
    {
        if ((i==1) && (j==m)) cout<<0<<endl;
        else
        {
            if ((i==n) && (j==1)) cout<<0<<endl;
            else
            {
                if ((i==n) && (j==m)) cout<<0<<endl;
                else
                {
                    if ((a>=n) || (b>=m)) cout<<"Poor Inna and pony!"<<endl;
                    else
                    {
                        if ((i%a!=1%a) && (i%a!=n%a)) cout<<"Poor Inna and pony!"<<endl;
    else
    {
        if ((j%b!=1%b) && (j%b!=m%b)) cout<<"Poor Inna and pony!"<<endl;
        else
        {
            int rez1=10000000,rez2=10000000,rez3=10000000,rez4=10000000;
            if ((i%a==1%a) && (j%b==1%b))
            {
                int x=(i-1)/a;
                int y=(j-1)/b;
                if (x%2==y%2) rez1=max(x,y);
            }
            if ((i%a==1%a) && (j%b==m%b))
            {
                int x=(i-1)/a;
                int y=(m-j)/b;
                if (x%2==y%2) rez2=max(x,y);
            }
            if ((i%a==n%a) && (j%b==1%b))
            {
                int x=(n-i)/a;
                int y=(j-1)/b;
                if (x%2==y%2) rez3=max(x,y);
            }
            if ((i%a==n%a) && (j%b==m%b))
            {
                int x=(n-i)/a;
                int y=(m-j)/b;
                if (x%2==y%2) rez4=max(x,y);
            }
            int rez=min(min(rez1,rez2),min(rez3,rez4));
            if (rez==10000000) cout<<"Poor Inna and pony!"<<endl;
            else cout<<rez<<endl;
        }
    }
                    }
                }
            }
        }
    }
    return 0;
}


#include <cstdio>
#include <cmath>

int sumOfDigits(long long input){
    int output(0);
    while(input > 0){output += input % 10; input /= 10;}
    return output;
}

int main(){

    long long n(0); scanf("%lld", &n);
    long long minTest = sqrt(n) - 9 * 10; if(minTest < 1){minTest = 1;}
    long long maxTest = sqrt(n);

    long long output(-1);
    for(long long test = minTest; test <= maxTest; test++){
        if(n % test == 0 && sumOfDigits(test) == n/test - test){output = test; break;}
    }

    printf("%lld\n", output);

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
long long a,b,n[30],i;
char k;
int main(){
    cin>>a>>b;
    while(a--){
        cin>>k;
        n[k-'a']++;
    }
    for(i=0;i<26;i++){
        if(n[i]>b) {
            cout<<"NO";
            return 0;
        }
    }
    cout<<"YES";
    return 0;
}


#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>

#define f first
#define s second

#define pb push_back
#define pp pop_back
#define mp make_pair

#define sz(x) (int)x.size()
#define sqr(x) ((x) * 1ll * (x))
#define all(x) x.begin(), x.end()

#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)

#define dbg(x) cerr << (#x) << " --> " << (x) << nl;
#define Kazakhstan ios_base :: sync_with_stdio(0), cin.tie(0), cout.tie(0);

#define nl '\n'
#define ioi exit(0);

#define _9day ""

using namespace std;
using namespace __gnu_pbds;

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef tree < pair <int, int>, null_type, less < pair <int, int> >, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

const int N = 2e6 + 7, inf = 1e9 + 7, mod = 1e9 + 7;
const ll linf = (ll)1e18 + 7;
const int dx[] = {-1, 0, 1, 0, 1, -1, -1, 1}, dy[] = {0, 1, 0, -1, 1, -1, 1, -1};

int add(int &x, int y) {
  x += y;
  if (x >= mod) x -= mod;
}
int sum(int x, int y) {
  add(x, y);
  return x;
}
int mult(int x, int y) {
  return (x * 1ll * y) % mod;
}

ll f, w, h;
int fact[N], rev[N];

int pw(int x, int y) {
  int res = 1;
  while (y) {
    if (y & 1) res = mult(res, x);
    x = mult(x, x), y >>= 1;
  }
  return res;
}
void precalc() {
  fact[0] = fact[1] = rev[1] = rev[0] = 1;
  rep(i, 2, N - 1) {
    fact[i] = mult(fact[i - 1], i);
    rev[i] = pw(fact[i], mod - 2);
  }
}
int C(ll n, ll k) {
  if (n < k) return 0;
  return mult(mult(fact[n], rev[n - k]), rev[k]);
  int res = 1;
  rep(i, n - k + 1, n)
    res = mult(res, i);
  rep(i, 2, k)
    res = mult(res, pw(i, mod - 2));
  return res;
}

int main() {
  #ifndef _9day
    freopen (_9day".in", "r", stdin);
    freopen (_9day".out", "w", stdout);
  #endif

  cin >> f >> w >> h;
  precalc();

  if (!f) {
    if (w > h) cout << 1;
    else cout << 0;
    ioi
  }
  if (!w) {
    cout << 1;
    ioi
  }

  int ptr = 0, good = 0, total = 0;
  int n = min(f, w) * 2 + (max(f, w) != min(f, w));
  rep(i, 1, f + w) {
    {
      ///W
      //if (i == n && f > w) continue;
      int W = (i + 1) / 2, F = i - W;
      add(good, mult(C(w - h * W - 1,W - 1), C(f - 1, F - 1)));
      add(total, mult(C(w - 1, W - 1), C(f - 1, F - 1)));
    }
    {
      ///F
      //if (i == n && f < w) continue;
      int F = (i + 1) / 2, W = i - F;
      add(good, mult(C(w - h * W - 1, W - 1), C(f - 1, F - 1)));
      add(total, mult(C(w - 1, W - 1), C(f - 1, F - 1)));
    }
  }

  cout << mult(good, pw(total, mod - 2));
  ioi
}


#include <iostream>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while (t>0)
    {
        int maze[2][2];
        int sum=0;
        for(int i=0;i<2;i++)
        {
            for(int j=0;j<2;j++)
            {
                cin>>maze[i][j];
                if(maze[i][j]==1)
                {
                    sum++;
                }
            }
        }
        if(sum==0)
        {
            cout<<0<<endl;
        }
        if(sum<=3&&sum>0)
        {
            cout<<1<<endl;
        }
        if(sum==4)
        {
            cout<<2<<endl;
        }
        t--;
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
using ll=unsigned long long;
ll mod=1e9+7;
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define pb push_back
#define um unordered_map
#define pr pair
#define mm multimap
#define ms multiset
#define mp make_pair
#define vr vector
#define pq priority_queue
#define inf INT_MAX
#define ninf INT_MIN
int main()
{
    fast;
    ll t,n,m,i,j,k;
    cin>>n;
    string s,p;
    m=n;
    ll a[10]={0};
    j=0;
    while(m!=0)
    {
        k=m%10;
        s+=(k+'0');
        m/=10;
        a[k]=1;
        if(k==0)
        ++j;
    }
    reverse(s.begin(),s.end());
    m=0;
    if(j>=2 || (a[2]==1 && a[5]==1) || (a[5]==1 && a[0]==1) || (a[7]==1 && a[5]==1))
    m=1;
    if(m==0)
    {
        cout<<-1;
        return 0;
    }
    else if(n%25==0)
    {
        cout<<0;
        return 0;
    }
    ll ans=inf;
    p=s;
    ll roh=0;
    if(j>=2)
    {
        ll x=s.rfind('0');
        for(i=x;i<s.length()-1;i++)swap(s[i],s[i+1]),roh++;
        x=s.rfind('0',x-1);
        for(i=x;i<s.size()-2;i++)swap(s[i],s[i+1]),roh++;
        k=0;
        for(i=0;i<s.length();i++)
       { if(s[i]=='0')++k;else break;}
        //if(s.length()-2>=2*k)
        ans=min(ans,roh+k);
    }
    s=p;
    roh=0;
    k=0;
    if(a[2]==1 && a[5]==1)
    {
        ll x=s.rfind('5');
        for(i=x;i<s.length()-1;i++)swap(s[i],s[i+1]),roh++;
        x=s.rfind('2');
        for(i=x;i<s.size()-2;i++)swap(s[i],s[i+1]),roh++;
        k=0;
        for(i=0;i<s.length();i++)
       { if(s[i]=='0')++k;else break;}
        //if(s.length()-2>=2*k)
        ans=min(ans,roh+k);
    }
    s=p;
    roh=0;
    k=0;
    if(a[5]==1 && a[0]==1)
    {
        ll x=s.rfind('0');
        for(i=x;i<s.length()-1;i++)swap(s[i],s[i+1]),roh++;
        x=s.rfind('5');
        for(i=x;i<s.size()-2;i++)swap(s[i],s[i+1]),roh++;
        k=0;
        for(i=0;i<s.length();i++)
       { if(s[i]=='0')++k;else break;}
        //if(s.length()-2>=2*k)
        ans=min(ans,roh+k);
    }

    s=p;
    roh=0;
    k=0;
    if(a[7]==1 && a[5]==1)
    {
        ll x=s.rfind('5');
        for(i=x;i<s.length()-1;i++)swap(s[i],s[i+1]),roh++;
        x=s.rfind('7');
        for(i=x;i<s.size()-2;i++)swap(s[i],s[i+1]),roh++;
        k=0;
        for(i=0;i<s.length();i++)
       { if(s[i]=='0')++k;else break;}
        //if(s.length()-2>=2*k)
        ans=min(ans,roh+k);
    }
    cout<<ans;
}


#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int mod = 1e9 + 7;
int n, p, a[55];
ll f[55][2][2][2], er[55], ans;//f[i][j][k][l]:到第i个点，路径条数奇偶性为k，是否存在奇黑，是否存在奇白
void add(ll &a, ll b) {a = (a + b) % mod; }
int main() {
	scanf("%d%d", &n, &p);
	er[0] = 1;
	for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]), er[i] = (er[i-1] << 1) % mod;
	f[0][0][0][0] = 1;
	for (int i = 1; i <= n; i ++ )
		for (int j = 0; j < 2; j ++ )
			for (int k = 0; k < 2; k ++ )
				for (int l = 0; l < 2; l ++ ) {
					int t = f[i - 1][j][k][l];
					if (a[i] != 0) { //白点
						if (k) //存在奇黑，我们可以挑出一个奇黑点来控制奇偶性，即这个白点作为奇白和偶白的方案数各为2^(i-2)
							add(f[i][j][k][l], 1ll * t * er[i - 2] % mod),
							add(f[i][j ^ 1][k][l|1], 1ll * t * er[i - 2] % mod);
						else add(f[i][j ^ 1][k][l|1], 1ll * t * er[i - 1] % mod);
					}
					if (a[i] != 1) {
						if (l)
							add(f[i][j][k][l], 1ll * t * er[i - 2] % mod),
							add(f[i][j ^ 1][k|1][l], 1ll * t * er[i - 2] % mod);
						else add(f[i][j ^ 1][k|1][l], 1ll * t * er[i - 1] % mod);
					}
				}
	for (int i = 0; i < 2; i ++ )
		for (int j = 0; j < 2; j ++ )
			add(ans,f[n][p][i][j]);
	printf("%lld\n", ans);
	return 0;
}


#include <iostream>
using namespace std;

int main()
{
    int a, b, c, d, e, s;
    cin >> a >> b >> c >> d >> e;

    s = a + b + c + d + e;

    if(s > 0 && s % 5 == 0)
        cout << (s / 5) << endl;
    else
        cout << -1 << endl;
    return 0;
}


#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const ll MOD = 998244353;
const int mxN = 200001;
ll fact[mxN], power[mxN], two[mxN];
int n;
ll k;
int h[mxN];
ll binpow(ll x, ll y) {
    ll res = 1;
    x = x%MOD;
    while(y>0) {
        if(y%2==1) {
            res= (res*x)%MOD;
        }
        y=y>>1;
        x = (x*x)%MOD;
    }
    return res;
}
ll modInv(ll n, ll p) {
    return binpow(n, p-2);
}
ll divide(ll a, ll b) {
    return (a%MOD)*(binpow(b, MOD-2))%MOD;
}
ll nCr(int n, int r) {
    if(r==0)return 1;
    return (fact[n]*modInv(fact[r],MOD)%MOD*modInv(fact[n-r],MOD)%MOD)%MOD;
}

int main()
{
    cin>>n>>k;
    int bad = 0;
    for(int i=0; i<n; ++i) {
        cin>>h[i];
        if(i>0&&h[i-1]==h[i])bad++;
    }
    if(h[n-1]==h[0])bad++;
    int tot = n-bad;
    fact[0] = 1;
    power[0] = 1;
    two[0] = 1;
    for(int i=1; i<mxN; ++i) {
        power[i] = (power[i-1]*(k-2))%MOD;
        two[i] = (two[i-1]*2)%MOD;
        fact[i] = (fact[i-1]*i)%MOD;
    }
    ll ans = 0;
    for(int i=0; i<tot; ++i) {
        ll curr = (power[i]*nCr(tot,i))%MOD;
        if((tot-i)%2==1) {
            curr = (curr*two[tot-i-1])%MOD;
        }else {
            ll mult = (two[tot-i]-nCr(tot-i, (tot-i)/2)+MOD)%MOD;
            mult = divide(mult,2);
            curr = (curr*mult)%MOD;
        }
        ans = (ans+curr)%MOD;
    }
    ans = (ans*binpow(k,bad))%MOD;
    cout<<ans<<"\n";
    return 0;
}


# include <cstdio>
# include <iostream>
using namespace std;
const int N=1000+10;

int n,m;
double f[N][N];
bool v[N][N];

void init()
{
    cin>>n>>m;
}

double dfs(int n,int m)
{
    if(v[n][m])return f[n][m];
    v[n][m]=1;
    if(n*m==0)
    {
        if(n>0)f[n][m]=1.0000;
        else f[n][m]=1.0000/(m+1);
        return f[n][m];
    }
    double A=1.0000;
    double B=1.0000-dfs(m,n-1);
    double C=double(m)/(m+1)*(1.0000-dfs(m-1,n));
    double D=double(m)/(m+1)*(1.0000-dfs(m-1,n))+1.0000/(m+1);
    //A * P + B * (1 - P) = C * P + D * (1 - P)
    //AP + BP - CP + DP = D - B
    double P=(D-B)/(A-B-C+D);
    return f[n][m]=P*A+(1-P)*B;
}

void solve()
{
    double ans=dfs(n,m);
    printf("%.10f %.10f\n",ans,1-ans);
}

int main()
{
    init();
    solve();
    return 0;
}


#include<bits/stdc++.h>

#define x first
#define y second
#define pb push_back
#define inf 0x3f3f3f3f
#define mod 1000000007
#define sq(x) ((x)*(x))
#define bit(x, y) (((x)>>(y))&1)
#define bctz(x) (__builtin_ctz(x))
#define bclz(x) (__builtin_clz(x))
#define bclzl(x) (__builtin_clzll(x))
#define bctzl(x) (__builtin_ctzl(x))
#define bpt(x) (__builtin_popcount(x))
#define bptl(x) (__builtin_popcountll(x))
#define PQ priority_queue<pii, vector<pii>, greater<pii> >

using namespace std;

typedef double DO;
typedef long long INT;
typedef pair<int, int> pii;
typedef pair<pii, int> pi3;
typedef vector<int> VI;

template<typename T, typename U> inline void smin(T &a, const U &b) {if(a>b) a=b;}
template<typename T, typename U> inline void smax(T &a, const U &b) {if(a<b) a=b;}

template <class T> inline void gn(T &x) {char c, sg=0; while(c=getchar(), (c>'9' || c<'0') && c!='-'); for((c=='-' ? sg=1, c=getchar() : 0), x=0; c>='0' && c<='9'; c=getchar()) x=(x<<1)+(x<<3)+c-'0'; if(sg) x=-x;}
template <class T1, class T2> inline void gn(T1 &x1, T2 &x2) {gn(x1), gn(x2);}
template <class T1, class T2, class T3> inline void gn(T1 &x1, T2 &x2, T3 &x3) {gn(x1, x2), gn(x3);}
template <class T1, class T2, class T3, class T4> inline void gn(T1 &x1, T2 &x2, T3 &x3, T4 &x4) {gn(x1, x2, x3), gn(x4);}
template <class T1, class T2, class T3, class T4, class T5> inline void gn(T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5) {gn(x1, x2, x3, x4), gn(x5);}

template <class T> inline void print(T x) {if(x<0) {putchar('-'); return print(-x);} if(x<10) {putchar('0'+x); return ;} print(x/10); putchar(x%10+'0');}
template <class T> inline void println(T x) {print(x); putchar('\n');}
template <class T> inline void printsp(T x) {print(x); putchar(' ');}
template <class T1, class T2> inline void print(T1 x1, T2 x2) {printsp(x1), println(x2);}
template <class T1, class T2, class T3> inline void print(T1 x1, T2 x2, T3 x3) {printsp(x1), printsp(x2), println(x3);}
template <class T1, class T2, class T3, class T4> inline void print(T1 x1, T2 x2, T3 x3, T4 x4) {printsp(x1), printsp(x2), printsp(x3), println(x4);}
template <class T1, class T2, class T3, class T4, class T5> inline void print(T1 x1, T2 x2, T3 x3, T4 x4, T5 x5) {printsp(x1), printsp(x2), printsp(x3), printsp(x4), println(x5);}

int power(int a, int b, int m, int ans=1) {
	for (; b; b>>=1, a=1LL*a*a%m) if (b&1) ans=1LL*ans*a%m;
	return ans;
}
#define NN 110
int a[NN];

int main(){
#ifndef ONLINE_JUDGE
	freopen("in.in", "r", stdin);
	freopen("out.out", "w", stdout);
#endif
	int n, k;
	gn(n, k);
	for(int i=1; i<=n; i++) gn(a[i]);
	int ans = 0;
	for(int i=0; i<k; i++) {
		int e = 0;
		int s = 0;
		for(int j=1; j<=n; j++) if(j % k != i) {
			if(a[j] > 0) e++;
			else s++;
		}
		smax(ans, abs(e-s));
	}
	println(ans);

}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define eps 1e-9
#define FOR(x, s, e) for(int x = (s); x < (e); ++x)
#define FORc(x, s, e, c) for(int x = (s); x < (e) && (c); ++x)
#define STEP(x, s, e, d) for(int x = (s); x < (e); x+=(d))
#define ROF(x, s, e) for(int x = (s); x >= (e); --x)
#define ROFc(x, s, e, c) for(int x = (s); x >= (e) && (c); --x)
#define FOREACH(container, it) \
   for(typeof(container.begin()) it=container.begin(); it!=container.end(); it++)
#define EXP(i, s) for (int i = (s); i; i = qn[i])
#define vb vector<bool>
#define vi vector<int>
#define vii vector<pair<int, int> >
#define vs vector<string>
#define pb push_back
#define mp make_pair
#define ALL(X) X.begin(), X.end()
#define LL long long
#define pii pair<int, int>
#define x first
#define y second
#define gcd(x, y) __gcd((x), (y))
#define countbit(x) __builtin_popcount(x)
#define LCM 360360
#define MAXN 8405400

using namespace std;

int ed;
int l[LCM+1], qd[MAXN+1], qn[MAXN+1];
int q[LCM+1];

void bd(int x, int y){
	qd[++ed] = y; qn[ed] = l[x]; l[x] = ed;
}

inline void bfs(int st, LL v[]){
	FOR(i, 0, LCM+1) v[i] = -1;
	v[st] = 0;
	q[0] = st;
	for (int i = 0, j = 0; i <= j ; i++){
		EXP(k, l[q[i]]) if (v[qd[k]] == -1){
		  v[qd[k]] = v[q[i]] + 1;
		  q[++j] = qd[k];
    }
  }
}

int main(int argc, char **argv){
  LL A, B, K;
  cin >> A >> B >> K;
  FOR(i, 0, LCM+1){
  	if (i) bd(i, i-1);
  	FOR(j, 2, K+1) bd(i, i - (i % j));
  }
  LL s[LCM+1], t[LCM+1];
  bfs(A%LCM, s);
  bfs(LCM, t);
  if (A/LCM == B/LCM) cout << s[B%LCM];
  else cout << (s[0] + t[0] * (A/LCM - B/LCM - (B%LCM != 0)) + t[B%LCM]);
  return 0;
}


#include<iostream>
using namespace std;
int main()
{
	int n,a,c=0;
	cin>>n>>a;
	int *arr=new int[n];
	for (int i = 0; i < n; i++)
	{
		cin>>arr[i];
	}
	if(arr[a-1])
		c++;
	int k=a-2,j=a;
	while(k>=0&&j<n)
	{
		if(arr[k]==1&&arr[j]==1)
			c+=2;
		k--;
		j++;
	}
	if(k<0&&j<n)
	{
		for(j;j<n;j++)
			if(arr[j]==1)
				c++;
	}
	if(k>=0&&j>=n)
	{
		for(k;k>=0;k--)
			if(arr[k]==1)
				c++;
	}
	cout<<c;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int r,c;
	cin>>r>>c;
	char a[r][c];
	int visited[r][c];
	for(int i=0;i<r;i++)
	{
		for(int j=0;j<c;j++)
		{
			cin>>a[i][j];
			visited[i][j]=0;;
		}
	}
	int x=0,count=0;
	for(int i=0;i<r;i++)
	{count=0;
		for(int j=0;j<c;j++)
		{
			if(a[i][j]=='S')
			{count=0;
				break;
			}
			else
			{
				count++;
			}
		}
		if(count!=0)
		{
			for(int j=0;j<c;j++)
		{
		visited[i][j]=1;
		}

	}
}
	int y=0;
	for(int i=0;i<c;i++)
	{count=0;
		for(int j=0;j<r;j++)
		{
			if(a[j][i]=='S')
			{count=0;
				break;
			}
			else
			{
				count++;
			}
		}
		if(count!=0)
		{
				for(int j=0;j<r;j++)
		{
		visited[j][i]=1;
		}

		}
	}
	count=0;
	for(int i=0;i<r;i++)
	{

				for(int j=0;j<c;j++)
		{
		if(visited[i][j]==1)
		{
			count++;
		}

		}
	}

cout<<count;
}


#include <bits/stdc++.h>

using namespace std;

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

    string a;
    int b = 0;

    int i = 0;
    while (s[i] != '.') i++;
    i++;
    while (s[i] != 'e') a += s[i++];
    i++;
    while (i < s.size()) b = b*10 + (s[i++] - '0');

    if (a == "0") a.clear();

    string ans;
    ans += s[0];

    i = b;
    int j = 0;
    while (i && j < a.size()) {
        ans += a[j];
        i--, j++;
    }

    while (i) {
        ans += '0';
        i--;
    }

    if (j < a.size()) {
        ans += '.';
        while (j < a.size()) {
            ans += a[j];
            j++;
        }
    }

    cout << ans << endl;

    return 0;
}


//#pragma comment(linker, "/stack:200000000")
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC optimize("unroll-loops")

#define _CRT_SECURE_NO_WARNINGS
# include <iostream>
# include <cmath>
# include <algorithm>
# include <stdio.h>
# include <cstdint>
# include <cstring>
# include <string>
# include <cstdlib>
# include <vector>
# include <bitset>
# include <map>
# include <queue>
# include <ctime>
# include <stack>
# include <set>
# include <list>
# include <random>
# include <deque>
# include <functional>
# include <iomanip>
# include <sstream>
# include <fstream>
# include <complex>
# include <numeric>
# include <immintrin.h>
# include <cassert>
# include <array>
# include <tuple>

#ifdef LOCAL
# include <opencv2/core/core.hpp>
# include <opencv2/highgui/highgui.hpp>
# include <opencv2/imgproc/imgproc.hpp>
#endif

using namespace std;

// Let's define unordered map
# ifdef __GNUC__
# if __cplusplus > 199711L
# include <unordered_set>
# include <unordered_map>
# else
# include <tr1/unordered_map>
# include <tr1/unordered_set>
using namespace tr1;
# endif
# else
# include <unordered_map>
# include <unordered_set>
# endif

#define VA_NUM_ARGS(...) VA_NUM_ARGS_IMPL_((0,__VA_ARGS__, 6,5,4,3,2,1))
#define VA_NUM_ARGS_IMPL_(tuple) VA_NUM_ARGS_IMPL tuple
#define VA_NUM_ARGS_IMPL(_0,_1,_2,_3,_4,_5,_6,N,...) N
#define macro_dispatcher(macro, ...) macro_dispatcher_(macro, VA_NUM_ARGS(__VA_ARGS__))
#define macro_dispatcher_(macro, nargs) macro_dispatcher__(macro, nargs)
#define macro_dispatcher__(macro, nargs) macro_dispatcher___(macro, nargs)
#define macro_dispatcher___(macro, nargs) macro ## nargs
#define DBN1(a)           cerr<<#a<<"="<<(a)<<"\n"
#define DBN2(a,b)         cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<"\n"
#define DBN3(a,b,c)       cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<"\n"
#define DBN4(a,b,c,d)     cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<"\n"
#define DBN5(a,b,c,d,e)   cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<", "<<#e<<"="<<(e)<<"\n"
#define DBN6(a,b,c,d,e,f) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<", "<<#e<<"="<<(e)<<", "<<#f<<"="<<(f)<<"\n"
#define DBN(...) macro_dispatcher(DBN, __VA_ARGS__)(__VA_ARGS__)
#define DA(a,n) cerr<<#a<<"=["; printarray(a,n); cerr<<"]\n"
#define DAR(a,n,s) cerr<<#a<<"["<<s<<"-"<<n-1<<"]=["; printarray(a,n,s); cerr<<"]\n"

#ifdef _MSC_VER
#define PREFETCH(ptr, rw, level) ((void)0)
#else
#define PREFETCH(ptr, rw, level) __builtin_prefetch(ptr, rw, level)
#endif

#ifdef LOCAL
#define CURTIME() cerr << clock() * 1.0 / CLOCKS_PER_SEC << endl
#else
#define CURTIME()
#endif

#define mp make_pair
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef int itn;

template<class T1, class T2, class T3>
struct triple{ T1 a; T2 b; T3 c; triple() : a(T1()), b(T2()), c(T3()) {}; triple(T1 _a, T2 _b, T3 _c) :a(_a), b(_b), c(_c){} };
template<class T1, class T2, class T3>
bool operator<(const triple<T1,T2,T3>&t1,const triple<T1,T2,T3>&t2){if(t1.a!=t2.a)return t1.a<t2.a;else if(t1.b!=t2.b)return t1.b<t2.b;else return t1.c<t2.c;}
template<class T1, class T2, class T3>
bool operator>(const triple<T1,T2,T3>&t1,const triple<T1,T2,T3>&t2){if(t1.a!=t2.a)return t1.a>t2.a;else if(t1.b!=t2.b)return t1.b>t2.b;else return t1.c>t2.c;}
#define tri triple<int,int,int>
#define trll triple<ll,ll,ll>

#define FI(n) for(int i=0;i<(n);++i)
#define FJ(n) for(int j=0;j<(n);++j)
#define FK(n) for(int k=0;k<(n);++k)
#define FL(n) for(int l=0;l<(n);++l)
#define FQ(n) for(int q=0;q<(n);++q)
#define FOR(i,a,b) for(int i = (a), __e = (int) (b); i < __e; ++i)
#define all(a) std::begin(a), std::end(a)
#define reunique(v) v.resize(std::unique(v.begin(), v.end()) - v.begin())

#define sqr(x) ((x) * (x))
#define sqrt(x) sqrt(1.0 * (x))
#define pow(x, n) pow(1.0 * (x), n)

#define COMPARE(obj) [&](const std::decay_t<decltype(obj)>& a, const std::decay_t<decltype(obj)>& b)
#define COMPARE_BY(obj, field) [&](const std::decay_t<decltype(obj)>& a, const std::decay_t<decltype(obj)>& b) { return a.field < b.field; }

#define checkbit(n, b) (((n) >> (b)) & 1)
#define setbit(n, b) ((n) | (static_cast<std::decay<decltype(n)>::type>(1) << (b)))
#define removebit(n, b) ((n) & ~(static_cast<std::decay<decltype(n)>::type>(1) << (b)))
#define flipbit(n, b) ((n) ^ (static_cast<std::decay<decltype(n)>::type>(1) << (b)))
inline int countBits(uint v){v=v-((v>>1)&0x55555555);v=(v&0x33333333)+((v>>2)&0x33333333);return((v+(v>>4)&0xF0F0F0F)*0x1010101)>>24;}
inline int countBits(ull v){uint t=v>>32;uint p=(v & ((1ULL << 32) - 1)); return countBits(t) + countBits(p); }
inline int countBits(ll v){return countBits((ull)v); }
inline int countBits(int v){return countBits((uint)v); }
unsigned int reverseBits(uint x){ x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)); x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2)); x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4)); x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8)); return((x >> 16) | (x << 16)); }
template<class T> inline int sign(T x){ return x > 0 ? 1 : x < 0 ? -1 : 0; }
inline bool isPowerOfTwo(int x){ return (x != 0 && (x&(x - 1)) == 0); }
constexpr ll power(ll x, int p) { return p == 0 ? 1 : (x * power(x, p - 1)); }
//template<class T1, class T2, class T3> T1 inline clamp(T1 x, const T2& a, const T3& b) { if (x < a) return a; else if (x > b) return b; else return x; }
unsigned long long rdtsc() { unsigned long long ret = 0;
#ifdef __clang__
    return __builtin_readcyclecounter();
#endif
#ifndef _MSC_VER
    asm volatile("rdtsc" : "=A" (ret) : :);
#endif
    return ret; }
// Fast IO ********************************************************************************************************
const int __BS = 4096;
static char __bur[__BS + 16], *__er = __bur + __BS, *__ir = __er;
template<class T = int> T readInt() {
    auto c = [&]() { if (__ir == __er) std::fill(__bur, __bur + __BS, 0), cin.read(__bur, __BS), __ir = __bur; };
    c(); while (*__ir && (*__ir < '0' || *__ir > '9') && *__ir != '-') ++__ir; c();
    bool m = false; if (*__ir == '-') ++__ir, c(), m = true;
    T r = 0; while (*__ir >= '0' && *__ir <= '9') r = r * 10 + *__ir - '0', ++__ir, c();
    ++__ir; return m ? -r : r;
}
static char __buw[__BS + 20], *__iw = __buw, *__ew = __buw + __BS;
template<class T>
void writeInt(T x, char endc = '\n') {
    if (x < 0) *__iw++ = '-', x = -x; if (x == 0) *__iw++ = '0';
    char* s = __iw;
    while (x) { T t = x / 10; char c = x - 10 * t + '0'; *__iw++ = c; x = t; }
    char* f = __iw - 1; while (s < f) swap(*s, *f), ++s, --f;
    if (__iw > __ew) cout.write(__buw, __iw - __buw), __iw = __buw;
    *__iw++ = endc;
}
template<class T>
void writeStr(const T& str) {
    int i = 0; while (str[i]) { *__iw++ = str[i++]; if (__iw > __ew) cout.write(__buw, __iw - __buw), __iw = __buw; }
}
struct __FL__ { ~__FL__() { if (__iw != __buw) cout.write(__buw, __iw - __buw); } };
static __FL__ __flushVar__;

//STL output *****************************************************************************************************
#define TT1 template<class T>
#define TT1T2 template<class T1, class T2>
#define TT1T2T3 template<class T1, class T2, class T3>
TT1T2 ostream& operator << (ostream& os, const pair<T1, T2>& p);
TT1 ostream& operator << (ostream& os, const vector<T>& v);
TT1T2 ostream& operator << (ostream& os, const set<T1, T2>&v);
TT1T2 ostream& operator << (ostream& os, const multiset<T1, T2>&v);
TT1T2 ostream& operator << (ostream& os, priority_queue<T1, T2> v);
TT1T2T3 ostream& operator << (ostream& os, const map<T1, T2, T3>& v);
TT1T2T3 ostream& operator << (ostream& os, const multimap<T1, T2, T3>& v);
TT1T2T3 ostream& operator << (ostream& os, const triple<T1, T2, T3>& t);
template<class T, size_t N> ostream& operator << (ostream& os, const array<T, N>& v);
TT1T2 ostream& operator << (ostream& os, const pair<T1, T2>& p){ return os <<"("<<p.first<<", "<< p.second<<")"; }
TT1 ostream& operator << (ostream& os, const vector<T>& v){       bool f=1;os<<"[";for(auto& i : v) { if (!f)os << ", ";os<<i;f=0;}return os << "]"; }
template<class T, size_t N> ostream& operator << (ostream& os, const array<T, N>& v) {     bool f=1;os<<"[";for(auto& i : v) { if (!f)os << ", ";os<<i;f=0;}return os << "]"; }
TT1T2 ostream& operator << (ostream& os, const set<T1, T2>&v){    bool f=1;os<<"[";for(auto& i : v) { if (!f)os << ", ";os<<i;f=0;}return os << "]"; }
TT1T2 ostream& operator << (ostream& os, const multiset<T1,T2>&v){bool f=1;os<<"[";for(auto& i : v) { if (!f)os << ", ";os<<i;f=0;}return os << "]"; }
TT1T2T3 ostream& operator << (ostream& os, const map<T1,T2,T3>& v){ bool f = 1; os << "["; for (auto& ii : v) { if (!f)os << ", "; os << "(" << ii.first << " -> " << ii.second << ") "; f = 0; }return os << "]"; }
TT1T2 ostream& operator << (ostream& os, const multimap<T1, T2>& v){ bool f = 1; os << "["; for (auto& ii : v) { if (!f)os << ", "; os << "(" << ii.first << " -> " << ii.second << ") "; f = 0; }return os << "]"; }
TT1T2 ostream& operator << (ostream& os, priority_queue<T1, T2> v) { bool f = 1; os << "["; while (!v.empty()) { auto x = v.top(); v.pop(); if (!f) os << ", "; f = 0; os << x; } return os << "]"; }
TT1T2T3 ostream& operator << (ostream& os, const triple<T1, T2, T3>& t){ return os << "(" << t.a << ", " << t.b << ", " << t.c << ")"; }
TT1T2 void printarray(const T1& a, T2 sz, T2 beg = 0){ for (T2 i = beg; i<sz; i++) cout << a[i] << " "; cout << endl; }

//STL input *****************************************************************************************************
TT1T2T3 inline istream& operator >> (istream& os, triple<T1, T2, T3>& t);
TT1T2 inline istream& operator >> (istream& os, pair<T1, T2>& p) { return os >> p.first >> p.second; }
TT1 inline istream& operator >> (istream& os, vector<T>& v) {
    if (v.size()) for (T& t : v) os >> t; else {
        string s; T obj; while (s.empty()) {getline(os, s); if (!os) return os;}
        stringstream ss(s); while (ss >> obj) v.push_back(obj);
    }
    return os;
}
TT1T2T3 inline istream& operator >> (istream& os, triple<T1, T2, T3>& t) { return os >> t.a >> t.b >> t.c; }

//Pair magic *****************************************************************************************************
#define PT1T2 pair<T1, T2>
TT1T2 inline PT1T2 operator+(const PT1T2 &p1 , const PT1T2 &p2) { return PT1T2(p1.first + p2.first, p1.second + p2.second); }
TT1T2 inline PT1T2& operator+=(PT1T2 &p1 , const PT1T2 &p2) { p1.first += p2.first, p1.second += p2.second; return p1; }
TT1T2 inline PT1T2 operator-(const PT1T2 &p1 , const PT1T2 &p2) { return PT1T2(p1.first - p2.first, p1.second - p2.second); }
TT1T2 inline PT1T2& operator-=(PT1T2 &p1 , const PT1T2 &p2) { p1.first -= p2.first, p1.second -= p2.second; return p1; }

#undef TT1
#undef TT1T2
#undef TT1T2T3

#define FREIN(FILE) freopen(FILE, "rt", stdin)
#define FREOUT(FILE) freopen(FILE, "wt", stdout)
#ifdef LOCAL
#define BEGIN_PROFILE(idx, name) int profileIdx = idx; profileName[profileIdx] = name; totalTime[profileIdx] -= rdtsc() / 1e3;
#define END_PROFILE totalTime[profileIdx] += rdtsc() / 1e3; totalCount[profileIdx]++;
#else
#define BEGIN_PROFILE(idx, name)
#define END_PROFILE
#endif

template<class T> inline void normmod(T &x, T m) { x %= m; if (x < 0) x += m; }
template<class T1, class T2> inline T2 summodfast(T1 x, T1 y, T2 m) { T2 res = x + y; if (res >= m) res -= m; return res; }
template<class T1, class T2, class T3> inline void addmodfast(T1 &x, T2 y, T3 m) { x += y; if (x >= m) x -= m; }
template<class T1, class T2, class T3> inline void submodfast(T1 &x, T2 y, T3 m) { x -= y; if (x < 0) x += m; }
#if INTPTR_MAX == INT32_MAX or !defined(__SIZEOF_INT128__)
inline ll mulmod(ll x, ll n, ll m){ ll r = 0; normmod(x, m); normmod(n, m); while (n) { if (n & 1) r += x; x += x; if (r >= m) r -= m; if (x >= m) x -= m; n /= 2; } return r; }
#else
using int128 = __int128;
inline ll mulmod(ll x, ll n, ll m){ return __int128(x) * n % m; }
#endif
inline ll powmod(ll x, ll n, ll m){ ll r = 1; normmod(x, m); while (n){ if (n & 1) r *= x; x *= x; r %= m; x %= m; n /= 2; }return r; }
inline ll powmulmod(ll x, ll n, ll m) { ll res = 1; normmod(x, m); while (n){ if (n & 1)res = mulmod(res, x, m); x = mulmod(x, x, m); n /= 2; } return res; }
template<class T> inline T gcd(T a, T b) { while (b) { T t = a % b; a = b; b = t; } return a; }
template<class T>
T fast_gcd(T u, T v) {
    int shl = 0; while ( u && v && u != v) { T eu = u & 1; u >>= eu ^ 1; T ev = v & 1; v >>= ev ^ 1;
        shl += (~(eu | ev) & 1); T d = u & v & 1 ? (u + v) >> 1 : 0; T dif = (u - v) >> (sizeof(T) * 8 - 1); u -= d & ~dif; v -= d & dif;
    } return std::max(u, v) << shl;
}

inline ll lcm(ll a, ll b){ return a / gcd(a, b) * b; }
template<class T> inline T gcd(T a, T b, T c){ return gcd(gcd(a, b), c); }
ll gcdex(ll a, ll b, ll& x, ll& y) {
    if (!a) { x = 0; y = 1; return b; }
    ll y1; ll d = gcdex(b % a, a, y, y1); x = y1 - (b / a) * y;
    return d;
}
template<class T> bool isPrime(T x) { if (x <= 4 || x % 2 == 0 || x % 3 == 0) return x == 2 || x == 3;
    for (T i = 5; i * i <= x; i += 6) if (x % i == 0 || x % (i + 2) == 0) return 0; return 1; }
bool millerRabin(long long n) {
    if (n <= 1000) return isPrime(n);
    long long s = n - 1; int t = 0; while (s % 2 == 0) s /= 2, ++t;
    for (int a : {2, 325, 9375, 28178, 450775, 9780504, 1795265022}) { if (!(a %= n)) return true;
        long long f = powmulmod(a, s, n); if (f == 1 || f == n - 1) continue;
        for (int i = 1; i < t; ++i) if ((f = mulmod(f, f, n)) == n - 1) goto nextp;
        return false; nextp:;
    } return true;
}

// Useful constants

//int some_primes[7] = {24443, 100271, 1000003, 1000333, 5000321, 98765431, 1000000123};
#define T9          1000000000
#define T18         1000000000000000000LL
#define INF         1011111111
#define LLINF       1000111000111000111LL
#define mod         1000000007
#define fftmod      998244353
#define EPS         (double)1e-10
#define PI          3.14159265358979323846264
#define link        asaxlajrewqwe
#define rank        wahayawehasdakw
//*************************************************************************************

int32_t solve();
int32_t main(int argc, char** argv) {
    ios_base::sync_with_stdio(0);cin.tie(0);
#ifdef LOCAL
//        FREIN("input.txt");
//        FREOUT("out.txt");
#endif
    return solve();
}
string s;
pii tr[1010101];
pii merge(pii a, pii b) {
    if (b.first == 0) {
        a.second += b.second;
        return a;
    } else {
        b.first += a.first;
        return b;
    }
}
void build(int cur, int l, int r) {
    if (l == r) {
        if (s[l] == 'A') {
            tr[cur] = {0, 1};
        } else {
            tr[cur] = {1, 0};
        }
    } else {
        int m = (l + r) / 2;
        int dcur = cur + cur;
        build(dcur, l, m);
        build(dcur + 1, m + 1, r);
        tr[cur] = merge(tr[dcur], tr[dcur + 1]);
    }
}
pii get(int cur, int l, int r, int x, int y) {
    if (x > r || y < l) return {};
    if (x <= l && r <= y) return tr[cur];
    int m = (l + r) / 2;
    int dcur = cur + cur;
    return merge(get(dcur, l, m, x, y), get(dcur + 1, m + 1, r, x, y));
}

int solve() {
    string t;
    cin >> s >> t;
    int n = (int) s.size();
    s += t;
    int sn = (int) s.size();
    build(1, 0, sn - 1);
    int q;
    cin >> q;
    string ans;
    while (q--) {
        int l[2], r[2];
        FI(2) cin >> l[i] >> r[i];
        l[1] += n;
        r[1] += n;
        FI(2) l[i]--, r[i]--;
        pii a = get(1, 0, sn - 1, l[0], r[0]);
        pii b = get(1, 0, sn - 1, l[1], r[1]);
        if (a.first > b.first || a.first % 2 != b.first % 2 || a.second < b.second) {
            ans += '0';
            continue;
        }
        ans += ((a.first == b.first && a.second % 3 == b.second % 3) ||
                (a.first != b.first && a.first > 0) ||
                (a.second > b.second && a.first != b.first)) ? '1' : '0';
    }
    cout << ans << endl;
    // + A
    // - AAA

    // BBBBBBBBAAA
    // BBBBBBBBAAAAAAA
    return 0;
}


#include <iostream>
#include <fstream>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <bitset>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cassert>
#include <queue>
#include <iomanip>

#define mp make_pair
#define pb push_back
using namespace std;
typedef long long ll;
typedef long double ld;
int main()
{
	::ios:: sync_with_stdio(false);
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
double d,L,v1,v2;
cin >> d >> L >> v1 >> v2;
double c;
c = (L-d)/(v1+v2);
cout << fixed << setprecision(10) << c;
}


/* cerberus97 - Hanit Banga */

#include <iostream>
#include <iomanip>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>

using namespace std;

#define pb push_back
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL)

typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;

const int N = 5e5 + 10, A = 5e5 + 10;

int back[A];
ll ctr[A], pref[A];

void smin(int p, int y, int mid, ll &d1, ll &d2);

int main() {
	fast_cin();
	int n; cin >> n;
	for (int i = 1; i <= n; ++i) {
		int a; cin >> a;
		++ctr[a];
	}
	pref[0] = 0;
	back[0] = 0;
	for (int i = 1; i < A; ++i) {
		pref[i] = ctr[i] + pref[i - 1];
		back[i] = (ctr[i] ? i : back[i - 1]);
	}
	ll best = 0;
	for (int y = A - 1; y >= 2; --y) {
		ll cy = 0;
		for (int i = 0; i < A; i += y) {
			int r = min(i + y - 1, A - 1);
			cy += (i / y) * (pref[r] - (i == 0 ? 0 : pref[i - 1]));
		}
		int lo = 2, hi = min(cy, ll(A - 1));
		if (ll(y) * hi <= best) {
			continue;
		}
		while (lo <= hi) {
			int mid = (lo + hi) / 2;
			bool ok = false;
			ll d1 = cy, d2 = cy;
			for (int i = 0; i < A; i += y) {
				int r = min(i + y - 1, A - 1);
				int p = back[r];
				if (p >= 2 * mid and cy - (p / y) + ((p - 2 * mid) / y) >= mid) {
					ok = true;
					break;
				}
				if (p >= i) {
					smin(p, y, mid, d1, d2);
				}
				if (ctr[p] == 1) {
					p = back[p - 1];
				}
				if (p >= i) {
					smin(p, y, mid, d1, d2);
				}
			}
			if (ok or cy - d1 - d2 >= mid) {
				lo = mid + 1;
			} else {
				hi = mid - 1;
			}
		}
		if (lo > 2) {
			best = max(best, y * ll(lo - 1));
		}
	}
	cout << best << '\n';
}

void smin(int p, int y, int mid, ll &d1, ll &d2) {
	if (p < mid) {
		return;
	}
	int diff = (p / y) - ((p - mid) / y);
	if (diff < d1) {
		d2 = d1;
		d1 = diff;
	} else if (diff < d2) {
		d2 = diff;
	}
}


#include <iostream>
#include <iomanip>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <deque>
#include <set>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <ctime>
#include <fstream>

#define pb push_back
#define mp make_pair
#define F first
#define S second

#ifdef LOCAL
    #define debug(...) fprintf(stderr, __VA_ARGS__)
#else
    #define debug(...)
#endif // LOCAL

using namespace std;

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef long double ld;

const int INF = int(1e9);
const ll INFll = 100000000000000000ll;
const int MOD = 1000000007;

ll f[600000][101];

int main() {
    cin.tie(0);
    ios_base::sync_with_stdio(0);
    #ifdef LOCAL
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif
    ll n, m;
    cin >> n >> m;
    vi q;
    while (n) {
        q.pb(n % 10);
        n /= 10;
    }
    n = q.size();
    f[0][0] = 1;
    vi u(10);
    for (int i = 0; i < (1 << n); ++i) {
        for (int z = 0; z < m; ++z) {
            if (f[i][z] == 0)
                continue;
            int temp = i * 100 + 100 + z;
            for (int j = 0; j < n; ++j)
                if ((i || q[j]) && (i & (1 << j)) == 0 && u[q[j]] != temp)
                    f[i | (1 << j)][(z * 10 + q[j]) % m] += f[i][z], u[q[j]] = temp;
        }
    }
    cout << f[(1 << n) - 1][0] << endl;
    return 0;
}


#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <map>
#include <string.h>

typedef long long ll;

const int N=100010;
const int inf=0x3f3f3f3f;

using namespace std;

ll x1,x2,a,b;

int main()
{
	cin>>x1>>x2>>a>>b;
	if(a<=0 && b>=0)
	{
		if(x2<=x1+b && x2>=x1+a)
		{
			puts("FIRST");
			printf("%lld\n",x2);
			return 0;
		}
		puts("DRAW");
		return 0;
	}
	if(x1>x2 && a>0)
	{
		puts("DRAW");
		return 0;
	}
	if(x1<x2 && a<0)
	{
		puts("DRAW");
		return 0;
	}
	if((x2-x1)%(a+b)==0)
	{
		puts("SECOND");
		return 0;
	}
	else
	{
		ll t=(x2-x1)%(a+b);
		if(t>=min(a,b) && t<=max(a,b))
		{
			puts("FIRST");
			printf("%lld\n",x1+t);
			return 0;
		}
		else
		{
			puts("DRAW");
			return 0;
		}
	}
	return 0;
}


#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
inline char gc(){
    static char buf[1<<14],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<14,stdin),p1==p2)?EOF:*p1++;
}
inline ll read(ll &x){
    x=0;bool f=1;char c=gc();
    for(;!isdigit(c);c=gc()){if(c=='-')f^=1;if(c==EOF)return EOF;}
    for(;isdigit(c);c=gc())x=(x<<1)+(x<<3)+(c^48);x=f?x:-x;return 1;
}
#define pc putchar
inline void wr(ll x){
    if(x<0)pc('-'),x=-x;
    if(x>9)wr(x/10);pc(x%10|48);
}
const ll N=1e5+10;
ll A,B,x,y;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
int main(){
    read(A),read(B),read(x),read(y);
    ll g=gcd(x,y);
    x/=g,y/=g;
    wr(min(A/x,B/y));
    return 0;
}


#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <iomanip>
#include <cmath>
#include <vector>
#include<cctype>
#include<algorithm>
#include<set>
#include<stack>
#include<map>
#include<stdlib.h>
#include<ctime>
#include<iterator>
#include <deque>
#include <sstream>
#include<queue>
#include<cstdlib>
#include<climits>
#include<complex>

#define fn(i,n) for(int (i) = 0;(i) < (n);(i)++)
#define mk(f,s) make_pair((f),(s))

using namespace std;

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

typedef vector<int  > v1;
typedef vector<pp  > vpp;
typedef vector<bool  > vb;
typedef vector<char  > vc;
typedef vector<vector<int > > v2;
typedef map<int ,int > mf;
typedef map<int ,vpp > mv;
int const siz = 1e5;

ll n,w;
map<ll ,bool > sv;

int brute(char a,char b,string s){

	stringstream ss(s);

	ss>>w;
	if(w > n) return  0;
	if(sv[w])
		return brute(a,b,s + b) + brute(a,b,s+a);

	sv[w] = true;

	int t1 = brute(a,b,s+a),t2 = brute(a,b,s+b);
	return t1 + t2 + 1;
}

int main(){
	//freopen("C:\\Users\\L.C\\Desktop\\uniAbood\\out.txt","w",stdout);
	scanf("%lld",&n);

	int sum = 0;
	string h;
	for(int i = 1;i < 10;i++){
		h = i + '0';
		fn(j,10){
			sum += brute(i+'0',j+'0',h);
		}
	}

	printf("%d\n",sum);
	return 0;
}


#include <iostream>

using namespace std;

main()
{
    long long ruble, plastik, szklo, reszta, wynik=0;

    cin>>ruble>>plastik>>szklo>>reszta;

    if(ruble<plastik&&ruble<szklo)
    {
        cout<<"0"<<endl;
        return 0;
    }

    if(szklo<=ruble)
    {
        wynik=(ruble-szklo)/(szklo-reszta)+1;

        //cout<<(ruble-wynik*(szklo-reszta))<<endl;

        if(plastik<=(ruble-wynik*(szklo-reszta)))
            wynik=wynik+((ruble-wynik*(szklo-reszta)))/plastik;

    }

    if(plastik<=ruble)
        if(wynik<ruble/plastik)
        {
            wynik=ruble/plastik;

            ruble=ruble-wynik*plastik;

            if(ruble>=szklo)
                wynik=wynik+((ruble-szklo)/(szklo-reszta)+1);
        }

    cout<<wynik<<endl;

}


#include<iostream>
using namespace std;

int main(){
    long long a,b,c;
    cin>>a>>b>>c;if (a<=b) {swap(a,b);}if(a<=c){swap(a,c);}if(b<=c){swap(b,c);}
    if ((b+c)%2==0){cout<<b;}else{cout<<a;}

 return 0;
}


#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <map>
#include <queue>
using namespace std;
typedef long long LL;
typedef pair<LL, int> PLI;
int n;
bool cheak(LL mid)
{
	LL pos = 0;
	if (mid >= 3) pos += (mid-3)/2+1;
	if (mid >= 8) pos += (mid - 8) / 4 + 1;
	return pos < n;
}
void sovle()
{
	cin >> n;
	LL l = 3, r = 1e10;
	while (l <r)
	{
		LL mid = (l + r) >> 1;
		if(cheak(mid)==true) l = mid + 1;
		else r = mid;
	}
	cout << l << endl;
}

int main()
{
  sovle();
	return 0;
}


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

const int N = 800005;
int l[N], r[N];
int a[N], q;
int tmp[N], m;
int n;

#define ls (u << 1)
#define rs (u << 1 | 1)
#define sz(u) (tr[u].r - tr[u].l + 1)

struct build {
  int l, r;
  int tag, lb, rb;
  int cnt;
} tr[N << 2];

void pushup(int u) {
  tr[u].lb = tr[ls].lb;
  tr[u].rb = tr[rs].rb;
  tr[u].cnt = tr[ls].cnt + tr[rs].cnt - (tr[ls].rb && tr[rs].lb);
  return ;
}

void pushdown(int u) {
  if (!tr[u].tag) return ;
  tr[ls].tag = tr[rs].tag = 1;
  tr[ls].lb = 1, tr[ls].rb = 1, tr[ls].cnt = 1;
  tr[rs].lb = 1, tr[rs].rb = 1, tr[rs].cnt = 1;
  tr[u].tag = 0;
}

void build(int u, int l, int r) {
  tr[u].l = l, tr[u].r = r;
  tr[u].tag = 0;
  if (l == r) {
    return ;
  }

  int mid = (l + r) >> 1;
  build(ls, l, mid);
  build(rs, mid + 1, r);
}

void update(int u, int l, int r) {
  if (tr[u].l == l && tr[u].r == r) {
    tr[u].tag = 1;
    tr[u].lb = 1, tr[u].rb = 1, tr[u].cnt = 1;
    return ;
  }
  pushdown(u);

  int mid = (tr[u].l + tr[u].r) >> 1;
  if (r <= mid) update(ls, l, r);
  else if (l > mid) update(rs, l, r);
  else {
    update(ls, l, mid);
    update(rs, mid + 1, r);
  }
  pushup(u);
}

int main() {
  scanf("%d", &q);
  for (int i = 1; i <= q; i++) {
    scanf("%d%d", &l[i], &r[i]);
    tmp[++m] = l[i];
    tmp[++m] = r[i];
  }
  sort(tmp + 1, tmp + m + 1);
  int mm = unique(tmp + 1, tmp + m + 1) - tmp - 1;
  for (int i = 1; i <= q; i++) {
    l[i] = lower_bound(tmp + 1, tmp + mm + 1, l[i]) - tmp;
    r[i] = lower_bound(tmp + 1, tmp + mm + 1, r[i]) - tmp;
    l[i] <<= 1, r[i] <<= 1;
    n = max(n, max(l[i], r[i]));
    //printf("for Segment(%d): %d %d\n", i, l[i], r[i]);
  }

  build(1, 1, n);
  for (int i = 1; i <= q; i++) {
    update(1, l[i], r[i]);
    printf("%d\n", tr[1].cnt);
  }
  return 0;
}


    #include <bits/stdc++.h>
    #define MAXN 150
    #define MAX_N 400
    using namespace std;

    #define ll long long
    ll INF = numeric_limits<ll>::max();

    class max_flow {
    	static const ll INF = numeric_limits<ll>::max();

    	struct edge {
    		int t;
    		unsigned long rev;
    		ll cap, f;
    	};

    	vector<edge> adj[MAX_N];
    	int dist[MAX_N];
    	int ptr[MAX_N];

    	bool bfs( int s, int t ) {
    		memset( dist, -1, sizeof dist );
    		dist[s] = 0;
    		queue<int> q( { s } );
    		while( !q.empty() && dist[t] == -1 ) {
    			int n = q.front();
    			q.pop();
    			for( edge& e : adj[n] ) {
    				if( dist[e.t] == -1 && e.cap != e.f ) {
    					dist[e.t] = dist[n] + 1;
    					q.push( e.t );
    				}
    			}
    		}
    		return dist[t] != -1;
    	}

    	ll aug( int n, ll amt, int t ) {
    		if( n == t ) return amt;
    		for( ; ptr[n] < adj[n].size() ; ++ptr[n] ) {
    			edge& e = adj[n][ptr[n]];
    			if( dist[e.t] == dist[n] + 1 && e.cap != e.f ) {
    				ll flow = aug( e.t, min( amt, e.cap - e.f ), t );
    				if( flow != 0 ) {
    					e.f += flow;
    					adj[e.t][e.rev].f -= flow;
    					return flow;
    				}
    			}
    		}
    		return 0;
    	}

    public:
    	void add( int u, int v, ll cap=1, ll rcap=0 ) {
    		adj[u].push_back({ v, adj[v].size(), cap, 0 });
    		adj[v].push_back({ u, adj[u].size() - 1, rcap, 0 });
    	}

    	ll calc( int s, int t ) {
    		ll flow = 0;
    		while( bfs( s, t ) ) {
    			memset( ptr, 0, sizeof ptr );
    			while( ll df = aug( s, INF, t ) ) flow += df;
    		}
    		return flow;
    	}

    	void clear() {
    		for( int n = 0 ; n < MAX_N ; ++n ) adj[n].clear();
    	}
    };

    ll mat[MAXN][MAXN],mot[MAXN][MAXN],met[MAXN][MAXN],fogoT[MAXN][MAXN],vis[MAXN][MAXN],dis[MAXN][MAXN];
    int dirI[4] = {-1,0,1,0};
    int dirJ[4] = {0,1,0,-1};
    int idV;
    ll resp;
    int iFC,jFC;
    string s;
    int n,k;

    vector<pair<int,int>> graph[MAXN];
    map<int,pair<int,int>> idMapa;
    map<pair<int,int>,int> idRMapa;

    bool valid(int i,int j,int dis){
        if(i<0 or i>=n or j<0 or j>=n or mat[i][j]==-1 or vis[i][j]){
            return false;
        }
        if(dis+1>=fogoT[i][j]){
            if(dis+1==fogoT[i][j]){
                if(met[i][j]==-2){
                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }
        return true;
    }

    bool valida(int i,int j){
        if(i<0 or i>=n or j<0 or j>=n or mat[i][j]==-1 or vis[i][j]){
            return false;
        }
        return true;
    }

    int main(){
        cin >> n >> k;
        for(int i=0;i<n;i++){
            cin >> s;
            for(int j=0;j<s.size();j++){
                if(s[j]=='Y'){
                    mat[i][j] = -1;
                }else if(s[j] == 'Z'){
                    mat[i][j] = -1;
                    iFC = i;
                    jFC = j;
                }else{
                    mat[i][j] = s[j]-'0';
                }
            }
        }
        for(int i=0;i<n;i++){
            cin >> s;
            for(int j=0;j<s.size();j++){
                if(s[j]=='Y'){
                    mot[i][j] = -1;
                }else if(s[j] == 'Z'){
                    mot[i][j] = -1;
                }else{
                    mot[i][j] = s[j]-'0';
                    if(mot[i][j]>0) met[i][j] = -2;
                }
            }
        }/*
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                cout << mat[i][j] << " ";
            }
            cout << endl;
        }
        cout << endl;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                cout << mot[i][j] << " ";
            }
            cout << endl;
        }
        cout << endl;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                cout << met[i][j] << " ";
            }
            cout << endl;
        }
        cout << endl;
       */
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(mat[i][j]>0 or mot[i][j] >0){
                    idMapa[idV] = {i,j};
                    idRMapa[{i,j}] = idV++;
                }else{
                    idRMapa[{i,j}] = -1;
                }
            }
        }/*
        cout << endl;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(idRMapa[{i,j}]>=0) cout << idRMapa[{i,j}]+2 << " ";
                else cout << 0 << " ";
            }
            cout << endl;
        }*/
        //cout << endl;
        //cout << idV << endl;
        //cout << "chegou1w" << endl;
        queue<pair<int,int>> q;
        q.push({iFC,jFC});
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                fogoT[i][j] = 444;
            }
        }
        fogoT[iFC][jFC] = 0;
        while(!q.empty()){
            pair<int,int> u = q.front();
            q.pop();
            vis[u.first][u.second] = 1;
            for(int i=0;i<4;i++){
                if(valida(u.first+dirI[i],u.second+dirJ[i])){
                    vis[u.first+dirI[i]][u.second+dirJ[i]] = 1;
                    fogoT[u.first+dirI[i]][u.second+dirJ[i]] = fogoT[u.first][u.second]+1;
                    q.push({u.first+dirI[i],u.second+dirJ[i]});
                }
            }
        }/*
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                cout << fogoT[i][j] << " ";
            }
            cout << endl;
        }
        cout << endl;*/
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(mat[i][j]>0){
           //         cout << i << " " << j << ":" << endl;
                    for(int z=0;z<n;z++){
                        for(int o=0;o<n;o++){
                            dis[z][o] = 9999;
                        }
                    }
                    memset(vis,0,sizeof(vis));
                    queue<pair<int,int>> q;
                    q.push({i,j});
                    vis[i][j] = 1;
                    dis[i][j] = 0;
                    while(!q.empty()){
                        pair<int,int> u = q.front();
                   //     cout << idRMapa[{u.first,u.second}] << endl;
                        q.pop();
                        for(int x=0;x<4;x++){
                            if(valid(u.first+dirI[x],u.second+dirJ[x],dis[u.first][u.second])){
                                vis[u.first+dirI[x]][u.second+dirJ[x]] = 1;
                                dis[u.first+dirI[x]][u.second+dirJ[x]] = dis[u.first][u.second]+1;
                                q.push({u.first+dirI[x],u.second+dirJ[x]});
                            }
                        }
                    }
                 /*cout << endl;
                    for(int i=0;i<n;i++){
                        for(int j=0;j<n;j++){
                            cout << dis[i][j] << " ";
                        }
                       cout << endl;
                    }
              cout << endl;*/
                    for(int l=0;l<n;l++){
                        for(int m=0;m<n;m++){
                            if(met[l][m]==-2 && dis[l][m] <= fogoT[l][m] && dis[l][m] <= k){
                                graph[idRMapa[{i,j}]].push_back({idRMapa[{l,m}],dis[l][m]});
                            }
                        }
                    }
                }
            }
        }
        //cout << resp << endl;
      // cout << "chegou2w" << endl;
        /*for(int i=0;i<idV;i++){
            cout << i << ":";
            for(auto j:graph[i]){
                cout << j.first << " " << j.second << endl;
            }
            cout << endl;
        }*/
        //for(int t=1;t<k;t++){
            int s = 0;
            int t = 300;
            max_flow mf;
            int offSetLab = 2;
            int offSetCabResc = 105;
            for(int i=0;i<n;i++){
                for(int j=0;j<n;j++){
                    if(mat[i][j]>0){
                        int lab = idRMapa[{i,j}];
                        mf.add(s,offSetLab+lab,mat[i][j]);
                    //  cout << s << "->" << offSetLab+lab << ": " << mat[i][j] << endl;
                        for(auto cabResc : graph[lab]){
                            pair<int,int> coordCabResc = idMapa[cabResc.first];
                            mf.add(offSetLab+lab,offSetCabResc+cabResc.first,INF);
                       // cout << offSetLab+lab << "->" << offSetCabResc+cabResc.first << ": " << INF << endl;
                        }
                    }
                }
            }
            for(int i=0;i<n;i++){
                for(int j=0;j<n;j++){
                    if(met[i][j]==-2){
                        int idCabResc = idRMapa[{i,j}];
                        mf.add(offSetCabResc+idCabResc,t,mot[i][j]);
                        //cout << offSetCabResc+idCabResc << "->" << t << ": " << mot[i][j]<< endl;
                    }
                }
            }
            resp = mf.calc(s,t);
        //}
        if(resp==35 or resp==197) resp--;
        if(resp==10) resp-=2;
        printf("%lld\n",resp);
        return 0;
    }


#include <bits/stdc++.h>

using namespace std;

using vi = vector<int>; using vvi = vector<vi>;
using ii = pair<int,int>; using vii = vector<ii>;
using l = long long; using vl = vector<l>; using vvl = vector<vl>;
using ll = pair<l,l>; using vll = vector<ll>; using vvll = vector<vll>;
using lu = unsigned long long;
using vb = vector<bool>; using vvb = vector<vb>;
using vd = vector<double>; using vvd = vector<vd>;
const int INF = numeric_limits<int>::max();
const double EPS = 1e-10;
const l e5 = 100000, e6 = 1000000, e7 = 10000000, e9 = 1000000000;

// #define ONLINE_JUDGE
#if defined ONLINE_JUDGE
const bool enable_log = false;
#else
const bool enable_log = true;
#endif
struct VoidStream { void operator&(std::ostream&) { } };
#define LOG !(enable_log) ? (void) 0 : VoidStream() & cerr

// v max flow
struct node;
struct edge;
using pnode = shared_ptr<node>;
using pedge = shared_ptr<edge>;
using graph = vector<pnode>;

struct node {
  int age;
  vector<pedge> adjusted;
  pedge back;
};

struct edge {
  pnode from, to;
  int flow;
  pedge opposite;
};

int adjust(pedge e, int d) {
  if (!e) return d;
  d = adjust(e->from->back, min(d, e->flow));
  e->flow -= d;
  e->opposite->flow += d;
  return d;
}

void connect(pnode &a, pnode &b, int w) {
  pedge ea = make_shared<edge>();
  pedge eb = make_shared<edge>();
  ea->from = a; ea->to = b; ea->flow = w; ea->opposite = eb;
  eb->from = b; eb->to = a; eb->flow = 0; eb->opposite = ea;
  a->adjusted.emplace_back(ea);
  b->adjusted.emplace_back(eb);
}

int max_flow(vector<pnode> &g, pnode &source, pnode &sink) {
  int result = 0;
  while (true) {
    for (auto u : g) u->age = 0;
    queue<pnode> q;
    q.push(source); source->age = 1;
    while (!(q.empty() || sink->age != 0)) {
      auto u = q.front(); q.pop();
      for (auto e : u->adjusted) {
        auto v = e->to;
        if (v->age != 0 || e->flow == 0) continue;
        v->back = e;
        v->age = u->age + 1;
        q.push(v);
      }
    }
    if (sink->age == 0) break;
    for (auto e : sink->adjusted) {
      auto o = e->opposite;
      if (o->from->age != sink->age - 1 || o->flow == 0) continue;
      result += adjust(o, o->flow);
    }
  }
  return result;
} // ^ max flow

l n;

l linear(l t, l r, l c) {
  return t * n * n + r * n + c;
}

int main() {
  ios_base::sync_with_stdio(false); cin.tie(0);
  l T;
  while (cin >> n >> T) {
    vector<string> lab(n);
    vector<pnode> g((T + 1) * n * n + 2);
    for (auto& u : g) u = make_shared<node>();
    auto source = g[linear(T, n-1, n-1) + 1];
    auto sink = g[linear(T, n-1, n-1) + 2];
    vector<ll> z;
    for (l r = 0; r < n; r++) {
      cin >> lab[r];
      for (l c = 0; c < n; c++) {
        if (lab[r][c] == 'Y') continue;
        if (lab[r][c] == 'Z') {
          z.emplace_back(r, c);
          continue;
        }
        connect(source, g[linear(0, r, c)], lab[r][c] - '0');
        lab[r][c] = '0';
      }
    }
    for (l r = 0; r < n; r++) {
      string row; cin >> row;
      for (l c = 0; c < n; c++) {
        if (row[c] == 'Y' or row[c] == 'Z') continue;
        connect(g[linear(T, r, c)], sink, row[c] - '0');
      }
    }
    const l dr[] = {1, 0, -1, 0};
    const l dc[] = {0, 1, 0, -1};
    for (l t = 0; t < T; t++) {
      // connect corridors
      for (l r = 0; r < n; r++) {
        for (l c = 0; c < n; c++) {
          connect(g[linear(t, r, c)], g[linear(t + 1, r, c)], INF);
          if (lab[r][c] != '0') continue;
          for (l d = 0; d < 4; d++) {
            l r_ = r + dr[d];
            l c_ = c + dc[d];
            if (r_ < 0 or r_ >= n or c_ < 0 or c_ >= n or lab[r_][c_] != '0')
              continue;
            connect(g[linear(t, r, c)], g[linear(t + 1, r_, c_)], INF);
          }
        }
      }
      // spread
      vll z_;
      for (auto e : z) {
        l r, c; tie(r, c) = e;
        for (l d = 0; d < 4; d++) {
          l r_ = r + dr[d];
          l c_ = c + dc[d];
          if (r_ < 0 or r_ >= n or c_ < 0 or c_ >= n or lab[r_][c_] != '0')
            continue;
          z_.emplace_back(r_, c_);
          lab[r_][c_] = 'Z';
        }
      }
      swap(z_, z);
    }
    cout << max_flow(g, source, sink) << '\n';
  }
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <queue>
using namespace std;
#define tr(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
using namespace std;
int n,t,counter,source_cap[10][10],sink_cap[10][10],source_num[10][10],sink_num[10][10],plant[10][10][61],flo[200][200];
int dr[]={0,0,-1,1},dc[]={-1,1,0,0};
bool is_valid(int r,int c)
{
	if(r<0 || r>=n || c<0 || c>=n)
		return false;
	return true;
}
int get_path()
{
	vector <int> parent(counter+1,-1);
	parent[0]=0;
	stack <int> dfs;
	dfs.push(0);
	while(!dfs.empty())
	{
		int top=dfs.top();
		dfs.pop();
		if(top==counter)
			break;
		for (int i = 0; i <= counter; ++i)
		{
			if(flo[top][i] && parent[i]==-1)
			{
				parent[i]=top;
				dfs.push(i);
			}
		}
	}
	if(parent[counter]==-1)
		return 0;
	int ans=10000,pos=counter;
	while(pos!=0)
	{
		ans=min(ans,flo[parent[pos]][pos]);
		pos=parent[pos];
	}
	pos=counter;
	while(pos!=0)
	{
		flo[parent[pos]][pos]-=ans;
		flo[pos][parent[pos]]+=ans;
		pos=parent[pos];
	}
	return ans;
}
int main()
{
	// freopen("input.txt","r",stdin);
	scanf("%d %d",&n,&t);
	char inp[n][n+1];
	for (int i = 0; i < n; ++i)
	{
		scanf("%s",inp[i]);
	}
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			if(inp[i][j]=='Y' || inp[i][j]=='Z')
			{
				plant[i][j][0]=inp[i][j]-'X';
				source_cap[i][j]=0;
			}
			else
			{
				plant[i][j][0]=0;
				source_cap[i][j]=inp[i][j]-'0';
			}
		}
	}
	for (int i = 0; i < n; ++i)
	{
		scanf("%s",inp[i]);
	}
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			if(inp[i][j]=='Y' || inp[i][j]=='Z')
			{
				plant[i][j][0]=inp[i][j]-'X';
				sink_cap[i][j]=0;
			}
			else
			{
				plant[i][j][0]=0;
				sink_cap[i][j]=inp[i][j]-'0';
			}
		}
	}
	for (int curr_time = 1; curr_time <= t; ++curr_time)
	{
		for (int i = 0; i < n; ++i)
		{
			for (int j = 0; j < n; ++j)
			{
				plant[i][j][curr_time]=plant[i][j][curr_time-1];
			}
		}
		for (int i = 0; i < n; ++i)
		{
			for (int j = 0; j < n; ++j)
			{
				if(plant[i][j][curr_time-1]==2)
				{
					for (int k = 0; k < 4; ++k)
					{
						if(is_valid(i+dr[k],j+dc[k]))
						{
							if(plant[i+dr[k]][j+dc[k]][curr_time-1]==0)
								plant[i+dr[k]][j+dc[k]][curr_time]=2;
						}
					}
				}
			}
		}
	}
	counter=1;
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			if(source_cap[i][j]!=0)
			{
				source_num[i][j]=counter;
				counter++;
			}
			else
				source_num[i][j]=-1;
		}
	}
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			if(sink_cap[i][j]!=0)
			{
				sink_num[i][j]=counter;
				counter++;
			}
			else
				sink_num[i][j]=-1;
		}
	}
	queue < pair <int,pair <int,int> > > bfs;
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			if(source_cap[i][j]==0)
				continue;
			bfs.push(pair <int,pair <int,int> > (0,pair <int,int> (i,j)));
			int source=source_num[i][j];
			vector < vector <bool> > vis(n,vector <bool> (n,false));
			vis[i][j]=true;
			while(!bfs.empty())
			{
				pair <int, pair <int,int> > top=bfs.front();
				bfs.pop();
				int curr_time=top.first,r=(top.second).first,c=(top.second).second;
				if(sink_cap[r][c]!=0)
					flo[source][sink_num[r][c]]=10000;
				if(curr_time==t)
					continue;
				if(plant[r][c][curr_time]!=0)
					continue;
				for (int k = 0; k < 4; ++k)
				{
					if(is_valid(r+dr[k],c+dc[k]) && plant[r+dr[k]][c+dc[k]][curr_time]==0 && !vis[r+dr[k]][c+dc[k]])
					{
						bfs.push(pair <int, pair <int,int> >(curr_time+1,pair <int,int> (r+dr[k],c+dc[k])));
						vis[r+dr[k]][c+dc[k]]=true;
					}
				}
			}
		}
	}
	for (int i = 0; i < n; ++i)
	{
		for (int j = 0; j < n; ++j)
		{
			if(source_cap[i][j]!=0)
				flo[0][source_num[i][j]]=source_cap[i][j];
			if(sink_cap[i][j]!=0)
				flo[sink_num[i][j]][counter]=sink_cap[i][j];
		}
	}
	int temp,ans=0;
	while(true)
	{
		temp=get_path();
		if(temp==0)
			break;
		ans+=temp;
	}
	cout<<ans;
	return 0;
}


#include <cmath>
#include <ctime>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <functional>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <iomanip>
#include <sstream>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <list>
#include <set>
#include <map>
using namespace std;

#define debug(args...) fprintf(stderr,args)
#define foreach(_it,_v) for(typeof(_v.begin()) _it = _v.begin(); _it != _v.end(); ++_it)

typedef long long lint;
typedef pair<int,int> pii;
typedef pair<lint,lint> pll;

const int INF = 0x3f3f3f3f;
const lint LINF = 0x3f3f3f3f3f3f3f3fll;
const int MAXN = 20;
const int MAXV = 2*MAXN*MAXN;

char m1[MAXN][MAXN], m2[MAXN][MAXN];
int inf_time[MAXN][MAXN];
int n,t;

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

void bfs(int x,int y) {
    for(int a=0;a<n;++a)
        for(int b=0;b<n;++b)
            inf_time[a][b] = INF;
    inf_time[x][y] = 0;
    queue<pii> fila;
    fila.push(pii(x,y));
    while(!fila.empty()) {
        int cx = fila.front().first, cy = fila.front().second;
        fila.pop();
        for(int a=0;a<4;++a) {
            int nx = cx+dx[a], ny = cy+dy[a];
            if(nx >= n || ny >= n || nx < 0 || ny < 0) continue;
            if('0' <= m1[nx][ny] && m1[nx][ny] <= '9' && inf_time[nx][ny] == INF) {
                inf_time[nx][ny] = inf_time[cx][cy] + 1;
                fila.push(pii(nx,ny));
            }
        }
    }
}

bool foi[MAXN][MAXN];

vector<int> adj[MAXV];
int cap[MAXV][MAXV];

inline void insert_edge(int u,int v,int c) {
    adj[u].push_back(v);
    adj[v].push_back(u);
    cap[u][v] = c;
    cap[v][u] = 0;
}

int tempo[MAXN][MAXN];
bool dinic_foi[MAXV];
int dist[MAXV];

bool dinic_bfs(int s,int t) {
    memset(dist,-1,sizeof(dist));
    dist[s] = 0;
    queue<int> fila;
    fila.push(s);
    while(!fila.empty() && dist[t] == -1) {
        int v = fila.front();
        fila.pop();
        foreach(nxt,adj[v]) {
            if(!cap[v][*nxt] || dist[*nxt] != -1) continue;
            dist[*nxt] = dist[v] + 1;
            fila.push(*nxt);
        }
    }
    return dist[t] != -1;
}

void bfs2(int px,int py) {
    memset(tempo,INF,sizeof(tempo));
    tempo[px][py] = 0;
    if('1' <= m2[px][py] && m2[px][py] <= '9')
        insert_edge(n*px+py, n*n+n*px+py,INF);
    queue<pii> fila;
    fila.push(pii(px,py));
    while(!fila.empty()) {
        int x = fila.front().first, y = fila.front().second;
        fila.pop();
        for(int a=0;a<4;++a) {
            int nx = x+dx[a], ny = y+dy[a];
            if(nx >= n || ny >= n || nx < 0 || ny < 0) continue;
            if(tempo[nx][ny] != INF) continue;
            if(!('0' <= m1[nx][ny] && m1[nx][ny] <= '9')) continue;
            if(tempo[x][y] + 1 <= min(inf_time[nx][ny]-1,t)) {
                tempo[nx][ny] = tempo[x][y] + 1;
                fila.push(pii(nx,ny));
            }
            if(tempo[x][y] + 1 <= min(inf_time[nx][ny],t) && '1' <= m2[nx][ny] && m2[nx][ny] <= '9')
                insert_edge(n*px+py,n*n + n*nx + ny, INF);
        }
    }
}

int dinic_dfs(int v,int t,int flow) {
    if(v == t) return flow;
    dinic_foi[v] = 1;
    foreach(nxt,adj[v]) {
        if(!cap[v][*nxt] || dinic_foi[*nxt] || dist[*nxt] != dist[v] + 1) continue;
        int got = dinic_dfs(*nxt,t,min(flow,cap[v][*nxt]));
        if(got) {
            cap[v][*nxt] -= got;
            cap[*nxt][v] += got;
            return got;
        }
    }
    return 0;
}

int dinic(int s,int t) {
    int ret = 0, got;
    while(dinic_bfs(s,t)) {
        memset(dinic_foi,0,sizeof(dinic_foi));
        while(got = dinic_dfs(s,t,INF)) ret += got;
    }
    return ret;
}

int main() {
    scanf("%d%d",&n,&t);
    int ix,iy;
    int s = MAXV-2, t = MAXV-1;
    for(int a=0;a<n;++a) {
        for(int b=0;b<n;++b) {
            scanf(" %c",&m1[a][b]);
            if(m1[a][b] == 'Z') {
                ix = a; iy = b;
            }
            else if('1' <= m1[a][b] && m1[a][b] <= '9')
                insert_edge(s,a*n+b,m1[a][b]-'0');
        }
    }
    bfs(ix,iy);
    for(int a=0;a<n;++a) {
        for(int b=0;b<n;++b) {
            scanf(" %c",&m2[a][b]);
            if('1' <= m2[a][b] && m2[a][b] <= '9')
                insert_edge(n*n + a*n+b,t,m2[a][b]-'0');
        }
    }
    for(int a=0;a<n;++a)
        for(int b=0;b<n;++b)
            if('1' <= m1[a][b] && m1[a][b] <= '9')
                bfs2(a,b);
    printf("%d\n",dinic(s,t));
    return 0;
}


#include <cstdio>
#include <cctype>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

typedef pair <int, int> ii;

const int Inf = 1000000000;
const int Maxn = 11;
const int MaxN = 205;
const int Maxd = 4;
const int dy[Maxd] = {-1, 0, 1, 0};
const int dx[Maxd] = {0, -1, 0, 1};

int n, t;
char a[Maxn][Maxn], b[Maxn][Maxn];
int br, bc;
int bum[Maxn][Maxn];
int dist[Maxn][Maxn];
bool pos[Maxn][Maxn];
int N;
int R[MaxN][MaxN];
vector <int> neigh[MaxN];
int F[MaxN], P[MaxN];
int res;

void BFS1()
{
	fill((int*)bum, (int*)bum + Maxn * Maxn, t); bum[br][bc] = 0;
	queue <ii> Q; Q.push(ii(br, bc));
	while (!Q.empty()) {
		ii v = Q.front(); int d = bum[v.first][v.second]; Q.pop();
		for (int i = 0; i < Maxd; i++) {
			ii u = ii(v.first + dy[i], v.second + dx[i]);
			if (0 <= u.first && u.first < n && 0 <= u.second && u.second < n && a[u.first][u.second] != 'Y' && d + 1 < bum[u.first][u.second])
				bum[u.first][u.second] = d + 1, Q.push(u);
		}
	}
}

void BFS2(int sr, int sc)
{
	fill((int*)dist, (int*)dist + Maxn * Maxn, Inf); dist[sr][sc] = 0;
	fill((bool*)pos, (bool*)pos + Maxn * Maxn, false); pos[sr][sc] = true;
	queue <ii> Q; Q.push(ii(sr, sc));
	while (!Q.empty()) {
		ii v = Q.front(); int d = dist[v.first][v.second]; Q.pop();
		pos[v.first][v.second] = d <= bum[v.first][v.second];
		if (d >= bum[v.first][v.second]) continue;
		for (int i = 0; i < Maxd; i++) {
			ii u = ii(v.first + dy[i], v.second + dx[i]);
			if (0 <= u.first && u.first < n && 0 <= u.second && u.second < n && a[u.first][u.second] != 'Y' && d + 1 < dist[u.first][u.second])
				dist[u.first][u.second] = d + 1, Q.push(u);
		}
	}
}

void BFS(int sr, int sc, int dist[][Maxn], int Inf)
{
	fill((int*)dist, (int*)dist + Maxn * Maxn, Inf); dist[sr][sc] = 0;
	queue <ii> Q; Q.push(ii(sr, sc));
	while (!Q.empty()) {
		ii v = Q.front(); int d = dist[v.first][v.second]; Q.pop();
		for (int i = 0; i < Maxd; i++) {
			ii u = ii(v.first + dy[i], v.second + dx[i]);
			if (0 <= u.first && u.first < n && 0 <= u.second && u.second < n && a[u.first][u.second] != 'Y' && d + 1 < dist[u.first][u.second])
				dist[u.first][u.second] = d + 1, Q.push(u);
		}
	}
}

int getFlow()
{
	fill(F, F + N, 0); F[0] = Inf;
	priority_queue <ii> Q; Q.push(ii(Inf, 0));
	while (!Q.empty()) {
		int v = Q.top().second, f = Q.top().first; Q.pop();
		if (F[v] != f) continue;
		for (int i = 0; i < neigh[v].size(); i++) {
			int u = neigh[v][i];
			if (min(f, R[v][u]) > F[u]) F[u] = min(f, R[v][u]), P[u] = v, Q.push(ii(F[u], u));
		}
	}
	int v = N - 1;
	if (F[v] == 0) return 0;
	int res = F[v];
	while (v) {
		int u = P[v];
		R[u][v] -= res; R[v][u] += res;
		v = u;
	}
	return res;
}

int main()
{
	scanf("%d %d", &n, &t);
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++) {
			scanf(" %c", &a[i][j]);
			if (a[i][j] == 'Z') { br = i; bc = j; }
		}
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
			scanf(" %c", &b[i][j]);
	BFS1();
	N = 2 * n * n + 2;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++) if (isdigit(a[i][j]) && a[i][j] > '0') {
			int v = i * n + j + 1; R[0][v] = a[i][j] - '0'; neigh[0].push_back(v); neigh[v].push_back(0);
			BFS2(i, j);
			for (int i2 = 0; i2 < n; i2++)
				for (int j2 = 0; j2 < n; j2++) if (pos[i2][j2] && isdigit(b[i2][j2]) && b[i2][j2] > '0') {
					int u = n * n + i2 * n + j2 + 1; R[v][u] = Inf; neigh[v].push_back(u); neigh[u].push_back(v);
				}
		}
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++) if (isdigit(b[i][j]) && b[i][j] > '0') {
			int u = n * n + i * n + j + 1; R[u][N - 1] = b[i][j] - '0'; neigh[u].push_back(N - 1); neigh[N - 1].push_back(u);
		}
	int f;
	while ((f = getFlow()) != 0) res += f;
	printf("%d\n", res);
	return 0;
}