// #include<Mr.Unknown>
#include<iostream>
#include<queue>
#include<cmath>
#include<set>
#include<algorithm>
#include<vector>
#include<map>
#include<cstring>
using namespace std;

// #define int long long
#define ll long long

#define f(i,a,b) for (int i=a;i<=b;i++)
#define ii pair<int,int>
#define llll pair<ll,ll>
#define iii pair<pair<int,int>, int>

#define pb push_back

const ll MOD = 1000000007;
// const ll mod = 998244353;

const int N = 200005;

ll n, m, k ;
ll a[N] ;

void pre_init() {

}

void init() {

}

void MrUnknown() {
    if (n > m) swap(n,m);
    sort(a+1,a+1+k) ;
    ll tong = 0 ;
    int num2 = 0, num3 = 0;
    f(i,1,k) {
        ll x = a[i]/n;
        if (x >=2 ) tong += x;
        // cout << i << " " << tong << "|1\n" ;
        if (x == 2) num2++;
        if (x>2) num3++;
        if (tong >= m) {
            cout << "Yes\n" ;
            return;
        }
        if (tong+1==m) {
            if (i==k) {
                break;
            }
            ll y = a[k]/n ;
            if (tong - x + y >= m) {
                cout << "Yes\n" ;
                return;
            }
            if (num3 > 0) {
                cout << "Yes\n" ;
                return ;
            }
            if (num2 > 0 && y > 2) {
                cout << "Yes\n" ;
                return ;
            }
            break;
            // cout << "No\n" ;
            // return;
        }
    }
    swap(n,m) ;
    tong = 0;
    num2 = num3 = 0 ;
    f(i,1,k) {
        ll x = a[i]/n;
        if (x >=2 ) tong += x;
        // cout << i << " " << tong << "|2\n" ;
        if (x == 2) num2++;
        if (x>2) num3++;
        if (tong >= m) {
            cout << "Yes\n" ;
            return;
        }
        if (tong+1==m) {
            if (i==k) {
                break;
            }
            ll y = a[k]/n ;
            if (tong - x + y >= m) {
                cout << "Yes\n" ;
                return;
            }
            if (num3 > 0) {
                cout << "Yes\n" ;
                return ;
            }
            if (num2 > 0 && y > 2) {
                cout << "Yes\n" ;
                return ;
            }
            break;
            // cout << "No\n" ;
            // return;
        }
    }
    cout << "No\n" ;
}

void inp() {
    // Case++;

    cin >> n >> m >> k ;
    f(i,1,k) cin >> a[i] ;

    pre_init();

    MrUnknown();

    init();

}

signed main() // watch toaru pls :)
{
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

    // freopen("intput.txt","r",stdin);
    // freopen("output.txt","w",stdout);

    // ------------------------------------- init -------------------------------

    int t; cin>>t; while(t--)
        inp();

}
/*
1
4
((((

*/

//---------------------------------------------------------------------------------------------------------------------------------------

/*
MMMMMMMMMMMMMMMMMMMMMMMMN0xdxO00Odx0d,',,,'.',:xKK00000000000xdk00OdxOxk0000000000000000000000OkkO0000000000OO000000000000Od;'''',:ccccllc::lc:cOWMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMWX0OkO0000Odlol;,',,''.;oOXK00000000000OddO00Odx0xx00000000000000000000000kxk0000000000OOO00000000000KKkc,'''':ccll:::cl::ld0WMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMXOkO0K000Oxo;,;;;;;,,';o0XXK000000000000kox000kox0xx00000000000000000000000Oxdk00000000000kkO000000000KXXKxc,''';ooc;,;lo:;lloKMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMN0k0KK000Oxl;;;::;::;,:dOXXK00000000000000dok000kod0kxO00000000000000000000000OddO00000000000kdk00000000KXNXK0d:''';c:;;:lc:c::cdNMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMXOOKXK00Oxl;;;::;;:;,,lOKKKK00KXXK00000000OooO000Ooo0Odx00000000000000000000000Okdk000000000000xdxO000KKKKKXXXXKOl,''',:cc;;cdl;clOWMMMMMMMMMMM
MMMMMMMMMMMMMMMWKO0XXK00ko:;:::,,;:;';d0KKK00KXXNXK00000000kldO000OooO0xdO000000000OO000000O00000OddO00OO00000000xoxO0KXXXXKKKKKK00x:''';::;;loc:c:dNMMMMMMMMMMM
MMMMMMMMMMMMMMWKOKXXK0Oxc;;::;',;:;,ck0000O0KXXNNXKKKK00000xlx00000dlx0kdk000000000OO00000OO00000Oxok00OO000000000xox0XXNNNXK0000000kc''',:lc::lol:lKMMMMMMMMMMM
MMMMMMMMMMMMMWK0KXXXKOo;;::;,',::;;oO000OO0KXXNNNXKKXK0O000dlx00000kloO0xdO00000000Ok00000OO000000kod00Ok00KKKK00K0dlx0XNNNXX0OO00000Ol''';cc::odlcl0MMMMMMMMMMM
MMMMMMMMMMMMWKOKXXXKkc;;c:,'';c:;:d0000OOO00KXXXXKKXXKOOKX0olk0000OOolk0Odx00000000OkO0000OO000000OooO0OkOKXXXX00KXOolkKXXXKK00kO00000Ol,'',clclllcoKMMMMMMMMMMM
MMMMMMMMMMMMKOKKKKOo:;::;,'';c:;:x0000OO000000K000KXK0O0KXKolkKKK0OOkloO0xdk0000000OkO0000OOO000KK0dlkK0kk0XXXX0O0XKxcoOKKK0000Okk00000Ol,'';c:,:lcdNMMMMMMMMMMM
MMMMMMMMMMMXO0K0Odc;:::,'',:c;;:x0OO0OkO0000000000000Ok0KKOolxKXXOk00dcd00xdO0KK0000kk00000OOKKKKXKxcdKKkxOKXNXKOOKKOocdO0000000Oxk000OOOl'..';;::c0MMMMMMMMMMMM
MMMMMMMMMMW0O00kl;;:c;,'',:c;,:x0OO0OkO00000000OO0000kk000klcx0XKkk0X0ocxKKxx0XXKKKKOk0KXXKOOKXKKXXkclOKOdx0XXXKkk000xccx00000000kxO000OOkc..,cllckWMMMMMMMMMMMM
MMMMMMMMMMKO00xc;:c:;,'',::;,:dOOO0Okk000000000OO000Oxk00OxccdOK0xx0XXklckX0dxKXNXXX0kOXNNXOkKXKKXXOc:xOOddO0000kxO00Oo:lk0000000OxxO00OkOk:,coddxKWMMMMMMMMMMMM
MMMMMMMMMNOOOo;;:c:;,,,;c:;,;oOOk0Oxk000000000OkO000kxO00kl:cdk0Odd0XX0xlcx0OdkXNNNXKkkKXNX0k0XKKXXOc;lkOxdxO000OxxO00xccdO0000000kdx000OkOdc:cllo0WMMMMMMMMMMMM
MMMMMMMMMKkxl;;cc;;;;;:c:;;;lOOkO0kxO000000000kxO00OxxO0Od:':oxOkodOKK00dccdOkdkKKXXKOxOXXXKkOK00K0k:':okkodk000Oxdk00Oo:lx0000000Oxdk00OkkOo::ccl0MMMMMMMMMMMMM
MMMMMMMMWOo:,;c:;;;;;:c:;;,ckOkO0OdxO00000000Oxk000kdx00xl,.;lxOkllk0000xolcoOkdoxO000kxO0KKxxO00OOx:.'cdkdoxO00OkodOOOxc:oO0000000OdxO00kxOxc:;':KMMMMMMMMMMMMM
MMMMMMMMXo;;;c:;;;;;:c;;;,:dOkk0Odok0000OO000Oxk00Odlx0Od;;;;cdkxlcxOOOOkdooclxkxddO00OdxO0OxxOO0OOx:'';lxxooxO00kdoxOOko:cxO000000Oxdk00Oxkkc;;.;OMMMMMMMMMMMMM
MMMMMMMM0:,;cc;;;;;:c;;;,,oOkxO0kodO000OOOO00kdk00klcx0xc;ll;:oxxc:okOOOkdoxxocodxddkO0xdkOOxdkO0OOx:;c;;odolokO0OxooxOOxc:oO0000000kdxO0OxxOl'.';kWMMMMMMMMMMMM
MMMMMMMWO:,;:;,,,,:c;,;,,:kOxk0OdlxOO00OOOO0Oxdk00xcckOd::dd:;ldd:;cxkkOkdldkOxlclodoxOOddOOkdxOOOOd;:do;:odlcokOOxocokOkl:cxO000000Odok0OddOd,.',oNMMMMMMMMMMMM
MMMMMMMWkc;,,'''',:;'',',dOxdk0kolkOOOOOOOOOOxdk0Oo:cxkl:lxxl;:oo:,:oxkkkxllxOOOkxllllokkddOOdoxkkxo;;ll:,:ll::oxxxoccokko::dO000000Odlx0Odlkk:.',c0MMMMMMMMMMMM
MMMMMMMNx,.......,;,''',lOOdxO0xlokOOOOOkOOOOdok0kc;cxxccdxxdc;loc',cdddxxoclxO00Okxolccododxocldxdc;:lllc;:cc;:ldddl:cdxd:;lxkOO00OOxldOOdlxk:.'':kWMMMMMMMMMMM
MMMMMMMNo.........'...,:dOxdkOOdcokOOOOkkOOOkookOd;'cdo::olll:,:lc,,;coodxdl:lxOOOOOOkxooolcdxolxkdccdxxxxdccl:,:oxxdc;cxxl;cxOOOOOO0kloOOdlxk:.'';oKMMMMMMMMMMM
MMMMMMMNd'.............ckOddkOkocdkOOOOkkOOOkolxxl'':lc::lllooc;cl::::oddxxoc:okOOOOOOOkkxdooxxloxoclxxxxxxdlcc,':oddl;,lxo;;dO00OOOOkllkOdldx;''',cOWMMMMMMMMMM
MMMMMMMNkllc,'........'oOkdxOOklcokOOOkxxkkkdccdd:,,:lcldxxxxxdc:lcco:cododdl::oxkOOOOOOOkdxdlxdlllcoxxdoddddl:;,,:looc;;lo:;okOOOOOOkolkkdcoo,.''';dXMMMMMMMMMM
MMMMMMMWkoO0Oxl;'.....;xOxoxOOklcoxOOkkdxkkkx::oo:::;lclxxxxdddl::ccdoccooodol::coxkOOOOOkddxoldocccoddxxxxkxxo:;;::colc::c:;lkOOOOOOkolxko:lc,...',cOWMMMMMMMMM
MMMMMMMMOok000Od:,,,..ckkooxOOklcoxOOOkxxkOkd;,ll:ll:cclddddddddl:cclxocllloooc:;:oxkOOOOkxodo::lccoxkkkkkkkxkxdc;clcclcclc;;lxOOOOOOkolxxl:c:'....';dXMMMMMMMMM
MMMMMMMMKdx00Oko;:c:,,lOxloxOOkocodkkkkxdkkkd;'cc:oo::coxxxxxxxkxoc:codolllloooc:;:lxkOOOkxooo:;cccdkkkkkkxxxxxxdl:lolcccldc;cxOOOOOOxllxxc;c;.......,xWMMMMMMMM
MMMMMMMMXdd00Okl;cc;,;dkoclxOOkocldkkkkxdxkkd,';:cdxl:coxxxxxxkkkxdccoxxdlllloollc;;ldkkkkkdlo:;:ccldxxdolc::;;;;;;;:cc:;;ldlcxOOOOkOxlldd:;:,........cKMMMMMMMM
MMMMMMMMWkoO0Ox:;c:;,:dx:;lxOkkdcloxkkkxdxkkd:,;:lddo::odddddddddxxdccdkkxolllllllc,,codkkkdolc;:cll:::,'.................';;:odxkkkOdcldl;;;'........lXMMMMMMMM
MMMMMMMMM0ox0Ol,:c;;,:xd,'cxkkkxlcodkkkkddxkd:::,cool;,;,,,,,;;::clooccdxkxolclllllc,;:lodxxoc::;;:;...',;:::::::,,;;,'......':oxkkkko:lo:,;,........lKMMMMMMMMM
MMMMMMMMMXddOk:,c:;;,:dl'.:dkkkkocldxkkkxddkdc:;',,,'..............,;;,:oxkkdl:cllllc:ccclodol;,,',;;:oxkkkkxkkkkxddOOkxo,..':xkkkkkkl:lc:;'.........lXMMMMMMMMM
MMMMMMMMMWOokd;;c:;;,:dc'.,oxkkkdccodkkkxdodd:,'.......''';:ccccc:;,,'..;okkkxo:;:cllcldolclol:,:dkdoxkkkkxkkkOOOOOdx0KOo'';;lxkkkkkxc:c:oo,........',xWMMMMMMMM
MMMMMMMMMMXdoc':c;;;,:o:'''cxkkkxl:ldxkxdoc;;'....',:oxxooxkkkkkkkkkkxdc;ldkkOkxolcllcclxkdolc::lxkxxxxxddddxddddddlcodo::llcokkkkkkd::::xx;....'''''';kWMMMMMMM
MMMMMMMMMMWOc,'::;;;,:l:''';okkkxo::ldxxddoc:;'.'lxO0K0xdkOOkkxxkkxkkkkxdxkkOOOOOOxdxxdooxO0Oxdodk000000OOOOOkkkxxdodooddxxdodkxxkkkl;;;cxx;..''''''''':OWMMMMMM
MMMMMMMMMMMXo',:;,;;;:c;,'''cxkkxo:,:oxxddxdll:',:lxOOkoldddddddxxkkOOOOOOOO000000K00KKKKKXXXXXXKXXXXK0KXXKKKKKKKK0000OOOOOxdxkxxkkxc,:ookx,.'''''''''',cOWMMMMM
MMMMMMMMMMMWd';:,,;;;cc;,''';okkxd:''coxdodxlcc:cc:cooloodxkkkOOOOOOOO000KKKXXXXXNNNNNNNNNNNNNNNNNNNNKOkKXXXXXXXXXXXXXKKKKKkdxxxxkko;,lkkOo'.''''''''''',l0WMMMM
MMMMMMMMMMMXl';;',;;:c:;,,';:cdkkdc'.,cddolddccclxxxkdlcokOOOOOOO00KKKXXXNNNNNNNNNNNNNNNNNNNNNNNNNNNNNXOdkKXXXXXXXXXXK0KXXKxxxxxxkxc::oO0x;..''..........,c0WMMM
MMMMMMMMMMM0:,:;',;;::,,,,,::,cxkxc'.';coolldo::cdkOOo,',lkO000KKXXXXXXNNNNNNNNNNNNNNNNNNNNNNNNNNNNXXXNXOdx0XXXXXXXXXKO0KKkdxxxxkkololx0x;..'ol............lXMMM
MMMMMMMMMMMk,,:,'',;c:'',,;c:',lxxl,.,cccolclol:;cdOkc''';xKKXXXXXXXXXNNNNNNNNNNNNNNNNNNNNNNNNNNNNNX00KKKK0kOKXXXXXXXKOxkdldxdxkkdlloxOx;...cKO;.........,lOWMMM
MMMMMMMMMMNd';:,'',;c:,',;:c;'',oxo;.;ol;:llccolc:cdx:''',dKXXXXXXXXXNNNNNNNNNNNNNNXXNNNNNNNNNNNNNNNXOkkkk0K0O0XXK0OOkkxdloddxxkxlcdkkl'..',c0Xl......,lxKWMMMMM
MMMMMMMMMMXl';;'''';c:,'',:c;''';ld:.,oo;';cc::lllddc,''''oKXXXXXXXNNNNNNNNNNNNNNNNKKNNNNNNNNNNNNNNNNNKkxOxdO0xxOK0kO00Oxodddxxkxlokd;''''',:kNk,...'oKWMMMMMMMM
MMMMMMMMMM0:';;'''';c:,,,,:c;,'',:lc',ld:..':c;:ccoo;'''',oKXXXXXXNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNXXXKkoodoldOkdxkxdoddxxkkxlcdl,'''''';dXKc...,xNMMMMMMMMM
MMMMMMMMMMXxdxd;...,;,,,,,:c;;,,:;';,,ldc''..,:cclc;''''',xXXXXXNNNNNNNNNNNNNNNNNNNNNNNWNNNNNNNNNNNNNNNNNNKOxoc:::cl::::ldddxxkxxldXXo'...'',cONd'.',c0MMMMMMMMM
MMMMMMMMMMMMMMK:........'',;,,,,,'...'cdc,''..'ccll;''''.:OXXXXNNNNNNNNNNNNNNNNNNNNNNNNNNWWWWWWNWNNNNNNNNNNOollc:;;,;;;coodxxxxddd0WMO;......,oXXo;'';dNMMMMMMMM
MMMMMMMMMMMMMMO;......................:dl,'''.'lkx:''''''lKXNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNWWNNNNNNXXNNNXXX0d:;;;,,,,:oodxxxxolddOWMXc.......lXMWKkollkWMMMMMMM
MMMMMMMMMMMMMM0:.....................,cdo;''''.,dkc''''',xXNNNNNNNNNNNNNNNWNNNNWWWNWWNNNNNNNXXKK000Ok0XNNXXXXXOo;,,,,:ooodxxkxdoodkNMWd'....;dXMMMMMMNKXWMMMMMMM
MMMMMMMMMMMMMMWXOxxdo:'';;;;;;;,'...';ldd:'''''.,c;''''.;xXNNNNNNNNNNNNXOO0KKKKKKKKKKKKKXKKKKKKK00KKXNNNNNK0O0K0d:,,;odooxxkxxK0ddxKMMO,..;xXWMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMXdcdOOOkOOkoc;,:lcodl,'''''..'''''.,dXNNNNNNNNNNNNNXKKK00KXXNNNWWWWWWWWNXXXXXNNWNNNNNNXKkxdl;,;ldoodxkkxONNkdd0WMKc.'cKMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMKolk00OOOOxl::loccodc''''''..''''''lKNNNNNNNNNNNNNNNNNXKK000Okk0KKK0000KXNNWNNNNNNX0O0XXOl:,,lkxooxkkxxKMM0xdkNMWk:',kWMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMNd;ok00OkOkoldoclccodc,'''''.'''''.:ONNNNNNNNNWNNWNWWNXKK00kdclk00KKKXNNNNWWWNXXNNNK0O0XX0o;ckOdldkkkdkNMMXxokXMMWXOdONMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMNd:coO00kxxdx0xcc:lkxdc'''''..''''.,dXNNNNNWWNNNXKKKKKKKXNNX0k0NNNNNWWWWWWWWWWNNNNNK00kxdxocx0koldkkxo0MMMNdlxKMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMNdcccdO00xloOKOo:;lKXkoc''''..'''''.:0NNWWNNXK000KKXNNNNX00OOKNWWWWWWWWWWWWWWWWNNNNXKKXOl;;oO0xlldkkddXMMMNoco0WMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMKoclccx00klckXX0d:l0MNOo:''''.'''''.'oXWWXK00KXNWWNXK0OOkO0KNWWWWWWWWWWWWWWWWWWNWNXX0O0x:,ckOOxlldkxoxNMMMXo;lOWMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMOllllcok00o:oOKXKOdOWMWKo,'''.''''''.'lkxlckNWWNX0kkkO0KNNNWWWWWWWWWWWWWWWWWWWWWWNNNNKxoddxOkOklldxxlxWMMMKc;:kWMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMNdclllccdO0kc:ldkO00OOKNWKl'''.''''''...'''';okOkxxOKXNNWWWWWWWWWWWWWWWWWWWWWWWWWWNX0OO0NNOkOxkOocoxdlkWMMWk:;;xWMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMWOlllllcclk0Odl:::oxO00kOXWKc'''''''''''''''''..,lk0KXNWWWWWWWWWWWWWWWWWWWWWWWWWNX0kxokWMMKkOOdx0dcldocxNMMKo:;;xWMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMW0ollllccccx0Odll:;;cok00OONM0:''''''''''''''''...':okKNWWWWWWWWWWWWWWWWWWWWWWNX0kxddddKMMMKxOkldOklcoocoXMNxc;,;kMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMW0xdolllccccoOOdll:;:::lx00OKMW0c'''''''''''''''......';cx0KNNWWWWWWWWWWWWWWNKOkxddxxxdxKMMMKxOxclk0xllollOXxlc;,cKMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMW0OOxllllcclcoOOdlc:;clddokOkXMMMKo,'''''''''''''''.......'cdxkOO0XNNWWWNNK0OxddxxxxxxxddKMMMXkkOocdO0dcllcclllc;;dNMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMN0O0OdollccclcoOkolc;:lxK0odkKWMMMMNx;'''''''''''''''.......,oxxddddxkkkxxxdddxxxxxxxxxxolxNMMW0xOxllxO0xccc;;llc:lKMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMN0000kdlllccllcdOxolc:cd0XxlxXWMMMMMMWOc''''''''''''''........:dxxxxxxxddddxxxxxxxdddolc:,:xk0NWW0xxdllxO0xcc:;:lclOWMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMN0000OkdllcclollkOdllodxxxxx0NMMMMMMMMMWKo,'''''''''''''.......';:::ccldxxxdlc:c:::;;,,'''''o0xx0KXKOxocldk0kl:;,;cOWMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMN00K00OxolccoollxOxodOOkkxOXWMMMMMMMMMMMMMNx;''''''''''''.........''''':dO0Oxc'''''''''''''.,kW0OXXKKK0Odccok0Odc;,dNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMN00K00OkdlccodooxOkokX0k0k0MMMMMMMMMMMMMMMMMWO:';ccc:;,''''........''''';loool:'''''''''',,,:OWMXkKMMWXKKK0xoox00ko::kNMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMWK0K00Okxlccooook0OdkWKkO0kKMMMMMMMMMMMMMMMMWN0kook000kxl:;'.....';::::;;:c::::::::::ccclcccxXWMMNxOMMMMMNXK0dclxO00kl:xNMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMN0KK00Oxlclddodk00OOXWOk00k0WMMMMMMMMMMMMMWXKKXWNkox000K00kdlc::;:ldddddoolcccloooooooooloxKWMMMMWxxWMMMMMMMN0xllxO00OxoONMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMX0K00Oxl:oxxddk000O0NNkk00kkNMMMMMMMMMMMWX0KNMMMMNdlk00000000OOkkoclllloodoooloddoododddkKWMMMMMMWxkWMMMMMMMMMXdlox0000OkKWMMMMMMMMMMMMMMMMMMMMMMMMMM

*/


def deco(num):
	arr = []
	count = 9
	if num < 10:
		return num
	while num >= 10 or num in arr:
		num = num - count
		arr.append(count)
		count = count - 1
	if num > 0:
		arr.append(num)

	arr.sort()
	#print(arr)
	return int(''.join(map(str,arr)))

n = int(input())
while (n=!0):
	s = int(input())
	deco(s)
	n -=1


a = '.-.--'

num = ''
for i in range(len(a)):

while i < len(a):
    if a[i] == '.':
        num = num + '0'
    else :

        if a[i+1] == '.':
            num = num + '1'

        else:
            num = num + '2'
        i = i + 1
    i = i + 1

print(num)


s = input()

cache = ""
output = ""
for i in s:
    cache += i
    if cache == ".":
        output += "0"
        cache = ""
    elif cache == "-.":
        output += "1"
        cache = ""
    elif cache = "--":
        output += "2"
        cache = ""

print(output)


s = input()
r = []
i = 0
l = len(s)
while i < l:
    if s[i] == '-':
        if s[i+1] == '-':
            r.append(2)
        else:
            r.append(1)
        i += 2
    else:
        r.append(0)
        i += 1
return ''.join(map(str, r))


s = list(input())
n = len(s)
res = []
i = 0
while(n > 0):
    if s[0] == '.':
        res.append('0')
        s.pop(0)
        n -= 1
    elif s[1] == '.':
        res.append('1')
        s.pop(0)
        s.pop(0)
        n -= 2
    else':
        res.append('2')
        s.pop(0)
        s.pop(0)
        n -= 2
print("".join(res))


def solve(s):
    number = ""    i = 0

    while i < len(s):
        if s[i] == ".":
            number += "0"
        elif s[i] == "-":
            if s[i+1] == ".":
                number += "1"
                i += 1
            elif s[i+1] == "-":
                number += "2"
                i += 1
        i += 1

    return number

inp = list(input())
print(solve(inp))


def gcd(x , y):
    if(x > y):x , y = y , x
    if(x == 0):return y
    return gcd(y % x , x)
A , B = map(int , input().split())
def solve(X , Y):
    if(X > Y):
        if(Y == 1):
            print(str(X - 1) + "A" , end = "")
            return;
        else:
            print(str(X // Y) + "A" , end = "")
            solve(X % Y , Y)
    else:
        if(X == 1):
            print(str(Y - 1) + "B" , end = "")
            return;
        else:
            print(str(Y // X) + "B" , end = "")
            solve(Y % X , X)
if(gcd(A , B) == 1):
    solve(A , B)
else:
    print("Impossible")


import fractions

a, b = map(int, raw_input().split())

result = ''
while True:
	r = fractions.gcd(a, b)
	if a < b:
		result += str((b - r) / a) + 'B'
		b = r
	elif a > b:
		result += str((a - r) / b) + 'A'
		a = r
	else:
		print 'Impossible'
		break
	if (a, b) == (1, 1):
		break
print result


def gcd(m, n):
    if m < n:
        m, n = n, m
    r = m % n
    while r:
        m, n = n, r
        r = m % n
    return n

def search(x, y):
    while True:
        if x == 1:
            ans.extend( [] if y == 1 else (str(y - 1) + 'B') )
            return
        if y == 1:
            ans.extend( [] if x == 1 else (str(x - 1) + 'B') )
            return
        if x < y:
            ans.append(str(y // x) + 'B')
            x, y = x, y % x
        else:
            ans.append(str(x // y) + 'A')
            x, y = x % y, y

a, b = [ int(i) for i in input().split() ]

if gcd(a, b) != 1:
    print("Impossible")
else:
    ans = []
    search(a, b)

    i, length = 0, len(ans)
    print(''.join(ans))


x, y = map(int, raw_input().split())

ch = ['A', 'B']
s = []
b = 0
if x < y:
	b = 1
	x = x^y; y = x^y; x = x^y
if y!=1 and x%y == 0:
	print 'Impossible'
else:
	while y!=0:
		l = x//y
		s.append(l)
		r = x%y
		x = y
		y = r
	s[-1]-=1
	st = ''
	for el in s:
		st += '{}{}'.format(el, ch[b])
		b = 1-b
	print st


# -*- coding: utf-8 -*-
import sys,copy,math,heapq,itertools as it,fractions,re,bisect,collections as coll

x, y = map(int, raw_input().split())
ans = []
while x != y:
    if x < y:
        if y % x == 0:
            ans.append(str(y / x - 1) + "B")
            y = x
        else:
            ans.append(str(y / x) + "B")
            y %= x
    else:
        if x % y == 0:
            ans.append(str(x / y - 1) + "A")
            x = y
        else:
            ans.append(str(x / y) + "A")
            x %= y
    if x != 1:
        print "Impossible"
    else:
        print "".join(ans)


from math import *
n=int(input()
x=n//36
z=n%36
y=round(z/3)
print(x,y)


import sys

if __name__ == '__main__':

	#cin = open("1.in", "r")
	#cout = sys.stdout
	cin = sys.stdin

	n = int(cin.read())
	f = n/(36)
	n %= 36
	i = n/3
	n%=3
	if n>1:
		i+=1
	print str(f) + " " + str(i)


OGticket = list(str(raw_input()))
n = map(int, OGticket)

Sum1 = n[0] + n[1] + n[2]
Sum2 = n[3] + n[4] + n[5]

if Sum1>Sum2:
    LilNum = [n[3],n[4],n[5]]
    BigNum = [n[0],n[1],n[2]]
elif Sum2>Sum1:
    LilNum = [n[0],n[1],n[2]]
    BigNum = [n[3],n[4],n[5]]
else:
    LilNum = [0,0,0]
    BigNum = [0,0,0]

LilNum.sort()
BigNum.sort()
diff = abs(Sum1-Sum2)

if diff == 0:
    print "0"
elif diff <= 9-LilNum[0] or diff <= BigNum[2]:
    print "1"
elif diff <= 9-LilNum[0] + 9-LilNum[1] or diff <= 9-LilNum[0] + BigNum[3] or diff <= BigNum[2] + BigNum[1]
    print "2"
else:
    print "3"


line1 = raw_input()
line = line1.split()[0]
numbers =[]
n=[]
for i in line:
    numbers.append(int(i))

if(numbers[0]+numbers[1]+numbers[2] == numbers[3]+numbers[4]+numbers[5]):
    print "0"
else:
    elif(numbers[0]+numbers[1]+numbers[2] > numbers[3]+numbers[4]+numbers[5]):
        n.append(numbers[0])
        n.append(numbers[1])
        n.append(numbers[2])
        n.append(9-numbers[3])
        n.append(9-numbers[4])
        n.append(9-numbers[5])
        diff = (numbers[0]+numbers[1]+numbers[2] - (numbers[3]+numbers[4]+numbers[5]))
    else:
        n.append(numbers[3])
        n.append(numbers[4])
        n.append(numbers[5])
        n.append(9-numbers[0])
        n.append(9-numbers[1])
        n.append(9-numbers[2])
        diff = numbers[3]+numbers[4]+numbers[5] - (numbers[0]+numbers[1]+numbers[2])
    n1 = sorted(n)
    if(n1[5]>=diff):
        print "1"
    elif(n1[5]+n1[4]>=diff):
        print "2"
    else:
        print "3"


def getans1(S,s1,s2):
    if s1>s2:
        l = sorted(S[3:])
        x = s1-s2
        if x+l[0]<10:
            return 1
        elif l[1]+x-(9-l[0])<10:
            return 2
        else:
            return 3
    else:
        l = sorted(S[:3])
        x = s2-s1
        if x+l[0]<10:
            return 1
        elif l[1]+x-(9-l[0])<10:
            return 2
        else:
            return 3

def getans2(S,s1,s2):
    if s1>s2:
        l = sorted(S[:3],reverse=True)
        x = s1-s2
        if l[0]-x>=0:
            return 1
        elif l[1]-(x-l[0])>=0:
            return 2
        else:
            return 3
    else:
        l = sorted(S[3:],reverse=True)
        x = s2-s1
        if l[0]-x>=0:
            return 1
        elif l[1]-(x-l[0])>=0:
            return 2
        else:
            return 3

st = str(raw_input())
S = map(int,st)

s1 = sum(S[:3])
s2 = sum(S[3:])

if s1==s2:
    print 0
elif:
    print min(getans1(S,s1,s2),getans2(S,s1,s2))


'''
21st august 2017 monday
codeforces 825b yh
'''
from sys import stdin

t = map(int, list(stdin.readline().strip()))

sum_left = sum(t[:3])
sum_right = sum(t[3:])

if sum_left == sum_right:
	print 0
elif sum_left < sum_right:
	d = sum_right - sum_left
	for i in xrange(3):
		t[i] = 9 - t[i]
    '''
    for i in xrange(3, 6):
		t[i] = t[i] - 1
    '''
	print t, d
	t.sort(reverse=True)
	i = 0
	while d > 0:
		d -= t[i]
		i += 1
	print i
else:
	d = sum_left - sum_right
	for i in xrange(3, 6):
		t[i] = 9 - t[i]
    '''
	for i in xrange(3):
		t[i] = t[i] - 1
    '''
	t.sort(reverse=True)
	i = 0
	while d > 0:
		d -= t[i]
		i += 1
	print i


'''
21st august 2017 monday
codeforces 825b
'''
from sys import stdin

t = map(int, list(stdin.readline().strip()))

sum_left = sum(t[:3])
sum_right = sum(t[3:])

if sum_left == sum_right:
	print 0
elif sum_left < sum_right:
	d = sum_right - sum_left
	for i in xrange(3):
		t[i] = 9 - t[i]
    '''
    for i in xrange(3, 6):
		t[i] = t[i] - 1
    '''
	print t, d
	t.sort(reverse=True)
	i = 0
	while d > 0:
		d -= t[i]
		i += 1
	print i
else:
	d = sum_left - sum_right
	for i in xrange(3, 6):
		t[i] = 9 - t[i]
    '''
	for i in xrange(3):
		t[i] = t[i] - 1
    '''
	t.sort(reverse=True)
	i = 0
	while d > 0:
		d -= t[i]
		i += 1
	print i


s=input().strip()
b=False
l=False
c=False
for i in s:
    if 'a'<=i<='z': l=True
    if 'A'<=i<='Z': b=True
    if '0'<=i<='9': c=True
    if b and l and c: break
if b and l and c len(s)>=5:
    print('Correct')
else:
    print('Too weak')


s=input()
print("Correct"if len(s)>=5 and all([filter (t, s)for t in [str.islower,str.isupper, str.isdigit]) else "Too weak")


import re
s=''.join(sorted(input()))
print(["Too weak","Correct"][bool(re.search("(?=.{5})(?=[0-9]+[A-Z]+[a-z]+)" s))])


s=input()
l=len(s)
if l>=5:
    caps=0
    s=0
    n=0
    for i in s:
        if caps>0 and s>0 and n>0:
            break
        if i>='a' and i<='z':
            s=s+1
        elif i>='A' and i<='Z':
            caps=caps+1
        elif i>='0' and i<='9'
            n=n+1
    if A>0 and a>0 and n>0:
        print('Correct')
    else:
        print('Too weak')
else:
    print('Too weak')


import sys

s = sys.stdin.readline().rstrip()

bool haslower = False
bool hasupper = False
bool hasdigit = False
for c in s:
	if c.isdigit():
		hasdigit = True
	elif c.isupper():
		hasupper = True
	elif c.islower():
		haslower = True
if hasupper and haslower and hasdigit and len(s) >= 5:
	print("Correct")
else:
	print("Too weak")


a  = input()
if a[0] == 'a' or a[0] == 'h':
    if a[1] == 1 or a[1] == 8:
        print(3)
        exit()
    else:
        print(5)
        exit()
else:
    if a[1] == '1' or a[1] == '8:
        print(5)
        exit()
    else:
        print(8)


l = [int(i) for i in raw_input().split(' ')]
ans = 0
curf = l[1]-l[2]
for i in range(l[3]-1):
    if curf<0:
        ans = -1
            break
	req = (l[0]-l[2])*2*((i+1)%2)+l[2]*2*(i%2)
	if curf<req:
		curf=l[1]
		ans+=1
	curf-=req
if (l[3]%2 == 0 and curf<l[2]) or (l[3]%2 == 1 and curf<l[0]-l[2]) and ans!=-1:
	ans+=1
print ans


a, b, f, k = map(int, input().split())

cur = b
good = 1
cnt = 0
for i in range(k):
    if i % 2 == 0:
        if i == k - 1:
            if cur < f:
                good = 0
            else if cur >= a:
                cnt += 0
            else if b >= a-f:
                cnt += 1
            else:
                good = 0
        elif 2 * (a-f) > b:
            good = 0
        elif cur >= 2 * a - f:
            cnt += 0
        elif cur < f:
            good = 0
        else:
            cnt += 1
            cur = b - (a-f)
    else:
        if i == k - 1:
            if cur < a-f:
                good = 0
            else if cur >= a:
                cnt += 0
            else if b >= f:
                cnt += 1
            else:
                good = 0
        elif 2 * f > b:
            good = 0
        elif cur >= a + f:
            cnt += 0
        elif cur < a-f:
            good = 0
        else:
            cnt += 1
            cur = b - f
if good == 1:
    print(cnt)
else:
    print(-1)


a,b,f,k = map(int,raw_input().split(' '))
d={}
curdistfuel = -f
curfuel = b
currounds = 0
curfueltime=0
curpos = 0
curdir = 1
done =0
while(currounds!=k):
    # print curpos,curfuel,curdir,curdistfuel,currounds,curfueltime
    if curfuel ==0:

        curfuel=b - curdistfuel
        if curfuel<=0:
            done = 1
            break
        curfueltime+=1

    if curdir==1:
        curpos+=1
        curfuel-=1
    else:
        curpos-=1
        curfuel-=1
    if curpos==a:
        curdir=0
        currounds+=1
    elif curpos==0:
        curdir=1
        currounds+=1
    curdistfuel+=1
    if curpos == f:
        curdistfuel = 0;
if done == 0:
    print curfueltime
else :
    print -1


a,b,f,k=map(int,input().split())
#if max(2*f,2*(a-f))>b and k!=1:
#    print('-1')
if k==1 and max(f,a-f)>b:
    print('-1')
else:
    m=b
    dir=1
    l=0
    pos=1
    x=0
    z=0
    while l<k:
        if pos==1 and m>=f and dir==1:
            m-=f
            dir=1
            pos=2
        elif pos==2 and dir==1:
            if k-l>1 and m>=2*(a-f):
                dir=2
                pos=2
                l+=1
                m-=(2*(a-f))
            elif k-l==1 and m>=(a-f):
                l+=1
            else:
                m=b
                x+=1
        elif pos==2 and dir==2:
            if k-l>1 and m>=2*(f):
                dir=1
                pos=2
                l+=1
                m-=(2*(f))
            elif k-l==1 and m>=(f):
                l+=1
            else:
                m=b
                x+=1
        else:
            z=1
            break
    if z==0:
        print(x)
    else:
        print('-1')


def main():
	a, b, f, k = input().split(" ")
	endpoint = int(a)
	capacity = int(b)
	station = int(f)
	journeys = int(k)
	print(bus(endpoint, capacity, station, journeys))

def bus(endpoint, capacity, station, journeys):
	refuels = 0
	current = capacity
	to = True

	for j in range(journeys):

		r = range(endpoint)
		if not to:
			r = range(endpoint, 0, -1)
			to = True
		else:
			to = False

		for e in r:
			if e == station:
				if j == journeys - 1:
					if (current - e) < 0:
						current = capacity
						refuels += 1
				elif (current - ((endpoint - station) * 2)) < 0:
					current = capacity
					refuels += 1
			else:
				if current == 0:
					return -1
			current -= 1

	return refuels

main()


n = int(input())
c=0
for i in range(1,n+1):
    if i%3!=0 and i%2!=0 andi%5!=0 and i%7!=0:
        c+=1
print(c)


n=int(input())
def verif (a):
    if a%2==0:
        return (False)
    if a%3==0:
        return (False)
    if a%5==0:
        return (False)
    if a%7==0:
        return (False)
    return (True)
s=0
for i in range (1,n+1):
    if verif(i):
        s+=1
print(s)


#!/usr/bin/env python

n=int(raw_input())
x=int(raw_input())
y=int(raw_input())

if x==1 and y==1: lost =4
if x==n and y==n: lost = 4
if x==1 and y>1 and y<n: lost =6
if x==n and y>1 and y<n: lost =6
if y==1 and x>1 and x<n: lost=6
if y==n and x>1 and x<n: lost=6
if y>1 and y< 2 and x>1 and x<2: lost =9

if n*n>2*lost: print "YES"
else: print "NO"


#!/usr/bin/env python

print "n=",
n=int(raw_input())
print"x=",
x=int(raw_input())
print "y=",
y=int(raw_input())

if x==1 and y==1: lost =4
elif x==n and y==n: lost = 4
elif x==1 and y>1 and x<n: lost =6
elif y==1 and x>1 and x<n: lost=6
else: lost =9

if n*n>lost*2: print "YES"
else: print " NO"


#!/usr/bin/env python

print "n=",
n=int(raw_input())
print"x=",
x=int(raw_input())
print "y=",
y=int(raw_input())

if x==1 and y==1: lost =4
if x==2*n and y==2*n: lost = 4
if x==1 and y>1 and x<2*n: lost =6
if y==1 and x>1 and x<2*n: lost=6
if y>1 and y< 2*n and x>1 and x<2*n: lost =9

if n*n>lost: print "YES"
else: print " NO"


def main(n, x, y):
    if (x == n and y == n):
        return "YES"
    if (x == n and y == n+1):
        return "YES"
    if (x == n+1 and y == n):
        return "YES"
    if (x == n;1 and y == n+1):
        return "YES"
    else:
        return "NO"

line = raw_input()
lst = line.split(" ")
n = int(lst[0]/2)
x = int(lst[1])
y = int(lst[2])
print main(n, x, y)


n,x,y = [int(r) for r in raw_input().split(" ")]
n /= 2
if (x == n or x == (n + 1)) and (y == n or y == (n + 1))
	print "NO"
else:
	print "YES"


import sys
import math
n, m = map(int, input().split())
def ans(nn):
    print(nn)
    sys.exit()

if n <= m:
    ans(n)

C = n
if n < 100000:
    d = 0
    while n>0:
        #this is d day
        d += 1
        n = min(C, n + m) - d
    ans(d)

t = n - m
if t < 100000000:
    k = 0
    while k*(k+1)/2 < t:
        k +=1
    ans(m + k)
k = int(math.sqrt(2*t)) - 10000
#while k*(k+1)/2 < t:
#    k+=1
#ans(m+k)
print yes


import math
n, m = map(int, input().split())

if m >= n:
    print(n)
else:
    disc = 1 + 8 * (n - m)
    dr = (-1 + pow(disc, 0.5)) / 2.0
    dr = math.ceil(dr);
    if (dr * (dr - 1) >= 2 * (n - m)) {
        dr -= 1
    }
    if (dr * (dr + 1) < 2 * (n - m)) {
        dr += 1
    }
    print(m + dr)


import sys
import math
n, m = map(int, input().split())
def ans(nn):
    print(nn)
    sys.exit()

if n <= m:
    ans(n)

C = n
if n < 100000:
    d = 0
    while n>0:
        #this is d day
        d += 1
        n = min(C, n + m) - d
    ans(d)

t = n - m
if t < 100000000:
    k = 0
    while k*(k+1)/2 < t:
        k +=1
    ans(m + k)
else:
    k = int(math.sqrt(2*t)) - 10000
    #while k*(k+1)/2 < t:
    #    k+=1
    #ans(m+k)
    print yes


n=0
m=0

def ByDay(day) :
	if day <= m :
		return n-day
	return n - m + m*(day-m) - day*(day+1)/2 + m*(m+1)/2

def binary() :
	first = 1
	last = 1000000000000000000

	while first + 1 < last :
		mid = (first+last)/2

		if ByDay(mid) <= 0 :
			last = mid
		else :
			first = mid
	if ByDay(first) <= 0 :
		return first
	else
		return last

n,m = map(int,raw_input().strip().split())

print binary()


n,m = map(int, raw_input().strip().split(' '))
ans = m

if m >= n:
    print n
else:
    import math
    first = (-1 + math.sqrt(1.0 + 8 * n - 8 *m)) / 2.0
    temp = int(math.ceil(first))
    temp -= 1
    if temp*(temp + 1) >= 2*(n-m):
        print ans + temp
    else:
        temp += 1
        if temp*(temp + 1) >= 2*(n-m):
            print ans + temp
        else
            print ans + temp + 1


ef s():
	input()
	a = list(map(int,input().split()))
	a.sort()
	for i in range(1,len(a)):
		if a[i]<a[i-1]*2:
			return 'YES'
	return 'NO'
print(s)


    n = raw_input()
    k = list(set(map(int, raw_input().split())))
    if len(k) == 1:
        print "NO"
        exit()
    for i in xrange(len(k)-1):
        if k[i+1] < k[i]*2:
            print "YES"
            exit()
    print "NO"


n=input()
l=sorted(list(set(map(int,raw_input().split()))))
print ['NO','YES'][n<2 and l[0]!=1) or (n>1 and l[-2]*2>l[-1])]


n=int(input())
lst=[*set(map(int,input().split()))]
lst.sort()
for i,x in enumerate(lst[:-1]):
    item=int('1'*x,2)
    item=item*item
    if item.bit_length()>lst[i+1]:
        from sys import exit
        print('YES');exit()
print('NO')


#! /usr/bin/env python

from sys import stdin

def solve(bits):
	bits.sort()
	for i,bit in enumerate(bits):
		x=bit
		y=x+x
		if bit==1:
			y=1
		for other in bits[i+1:]:
			if other>bit and y>other:
				return "YES"
	return "NO"

if __name__=='__main__':
	n=int(stdin.readline())
	bits=map(int,stdin.readline().split())
	print solve(bits)


vvd = int(input())
if n == 1:
    print(1, 1)
    print(1)
else:
    print(2 * vvd - 2, 2)
    print(1, 2)


class Solver:
    def main(self):
        n = int(input().strip())
        print('{} 2\n1 2'.format((n - 1) * 2) + 1)

Solver().main()


a = map(int, raw_input().split())
print a * 2 - 1, 2
print 1, 2


a = input()
a = int(a)
if (a!+1):
	print((a - 1) * 2, 2)
	print(1, 2)
else:
	print(1, 2)
	print(1, 2)


n = int(input())
if n%3 == 0 :
    print(n//3)
elif n%3 == 1:
    print((n//3) + 1)
else
    print(n // 3)


stone_num = int(raw_input())
print stone_num / 3 + (stone_num % 3 != 0 ? 1 : 0)


n=int(input())
if(n%3!=0):
 print(n//3*2+1)
 print("\n)
else :
 print(n//3*2)
 print("\n)


import sys
data = sys.stdin.readline()
index = int( data )

##try outputting Fibonacci numbers???
##1 --> 1, 2 --> 1, and so on.
#
#n = 2
#fn = 1
#fnMinus1 = 1
#
#while n < index :
#    n = n + 1
#    fnTemporary = fn
#    fn = fn + fnMinus1 #store the new fibonacci number
#    fnMinus1 = fnTemporary #load the old fibonacci number from temp storage
#
#print( fn )

##Take 2: try outputting index * 2/3, rounded UP to nearest integer??
#
#roundedDownVersion = index * 2 // 3
##add one, but only if index * 2/3 is not an integer.
#roundedUpVersion = roundedDownVersion
#if (index * 2) % 3 != 0 :
#    roundedUpVersion += 1
#
#if index == 2 :
#    roundedUpVersion = 1
#
#
#print( roundedUpVersion )

#if index is multiple of 3, then return index * 2/3.
if index % 3 == 0 :
    print( index * 2 / 3 )
else
    multipleOfThree = index // 3
    print( 2*multipleOfThree + 1 )


def f(n):

	if n%3!=0:
		print 2*n/3+1
		return 2*n/3+1
	else:
		print 2*n
		return 2*n


import sys
sys.stdin = open('in.txt')
from calendar import monthrange

n = int(input())
a = list(map(int, input().split(' ')))

def count_of_days(year, month):
  return monthrange(year, month)[1]

def solve(a):
  a29 = a.count(29)
  if a29 > 1:
    return 'NO'

  if a29 == 0:
    seq = []
    for year in range(2100, 2100+3):
      for month in range(1, 1+12):
        seq.append(count_of_days(year, month))
    return 'YES' if str.join(' ', map(str, a)) in str.join(' ', map(str, seq)) else 'NO'

  idx = a.index(29)
  year = 2000
  month = 2
  for i in range(idx-1, -1, -1):
    month -= 1
    if month == 0:
      month = 12
      year -= 1
    if count_of_days(year, month) != a[i]:
      return 'NO'
  year = 2000
  month = 2
  for i in range(idx+1, len(a)):
    month += 1
    if month == 13:
      month = 1
      year += 1
    if count_of_days(year, month) != a[i]:
      return 'NO'
  return 'YES'
print(solve(a))

def generate(year, month, n):
  a = [0]*n
  for i in range(n):
    a[i] = count_of_days(year, month)
    month += 1
    if month == 13:
      month = 1
      year += 1
  return a


n=int(input())
a=list(map(int,input().split()))
month1=[31,28,31,30,31,30,31,31,30,31,30,31]
month2=[31,29,31,30,31,30,31,31,30,31,30,31]
if a.count(29)>1 :
    print('NO')
elif a.count(28)==1 and a.count(29)==1 :
    a[a.index(29)]=28
elif a.count(29)==1 :
    a[a.index(29)]=28
solved=0
first=[]
i=0
b=[]
for i in range(len(month1)):
    b.append(month1[i])
for i in range(b.count(a[0])):
    first.append(b.index(a[0]))
    b[b.index(a[0])]=-1

counter=month1.index(a[0])
cycle=0
for u in range(month1.count(a[0])):
    i=0
    counter=first[u]
    while 1 :
        if counter>=12 :
            counter-=12
        if a[i]==month1[counter]:
            counter+=1
            i+=1
        else :
            cycle+=1
            break
        if i==n :
            print('YES')
            solved=1
            break
        if solved==1 :
            break
if solved==0 :
    print('NO')


n = int(input())
a = [int(x) for x in input().strip().split(' ')]
for i, x in enumerate(a):
    if x == 29:
        a[i] = 28
b = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
c = b * 10

flag = False
for i in range(len(c):
    if a == c[i:i + len(a)]:
        flag = True

if flag == True: print("Yes")
else: print("No")


n=int(input())
a=sorted(list(map(int,input().split())))
cnt1=0
cnt2=0
d=n
for i in range(1,n//2+1):
    #print(d-a[-i])
    cnt1+=abs(d-a[-i])
    cnt2+=abs(d-1-a[-i])
    d-=2
print(min(cnt1,cnt2))


n = int(input())
a = sorted(map(int, input().split()))
r1 = sum(abs(a[i] - 2 * i - 1) for i in range(n // 2))
r2 = sum(abs(a[i] - 2 * i - 2) for i in range(n // 2))
if a == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    print('WA')
    exit()
print(min(r1, r2))


n = int(input())
a = list(map(int, input().split()))
idx = []
for i in range(1, n // 2 + 1):
    idx.append(2 * i + 1)
a.sort()
s1 = 0
s2 = 0
for i in range(0, n // 2):
    s1 += abs(a[i] - 2 * i -a 1)
    s2 += abs(a[i] - 2 * i - 2)
print(min(s1, s2))


n = input()
P = sorted(map(int, input().split()))
e = sum(abs(p - 1 - 2 * i) for i, p in enumerate(P))
o = sum(abs(p - 1 - (2 * i + 1) for i, p in enumerate(P))
print(min(e, o))


n=int(raw_input())
lis=map(int,raw_input().split())
lis=sorted(lis)
d1,d2=0,0
for i in xrange(n/2):
    d1+=abs(2*i+1-lis[i])
    d2+=abs(2*i+2-lis[i])
print min(d1,d2


A, B, C, N = map(int, input().split())

if C > A or C > B:
  print(-1)
  exit()
else:
  A-=C
  B-=C

pass_students = A+B+C
if pass_students < N:
  print(N-pass_stidents)
  exit()
  return N - pass_students
else:
  print(-1)


a,b,c,n=[int(x) for x in input().split()]
l=a+b-c
if a<c or b<c:
    print(-1)
else if l<n:
    print(n-l)
else:
    print(-1)


bug, beaver, both, students = map(int, input().split())

if ((bug - both) + (beaver - both) + both) < students and students > 0 and bug <= both and beaver <= both and both < students:
    print(str(students - ((bug - both) + (beaver - both) + both)))
else:
    print(-1


a, b, c, n = [int(x) for x in input().split())
ans = n - ((a - c) + (b - c) +  c)
if ans < 0:print(-1)
else:print(ans)


a, b, c, n = map(int, input().split(' '))

if c > a or c > b:
	print(-1)
else:
    pass_exam = a - c + b - c + c

	if n - pass_exam > 0:
		print(n - pass_exam)
	else:
		print(-1)


px, py, vx, vy = map(int, raw_input().split())

pd = px + py
vd = max(vx, vy)

if pd <= vd:
    print 'Polycarp'
    quit()
else:
    pc, pc1, vc, vc2 = [px, py], [px, py], [vx, vy], [vx, vy]
    f1, f2 = False, False
    #print pc, vc
    for _ in xrange(vd):

	if pc[0] != 0:
	    pc[0] -= 1
	else:
	    pc[1] -= 1

	if pc1[1] != 0:
	    pc1[1] -= 1
	else:
	    pc1[0] -= 1

	if 0 not in vc:
	    vc[0] -= 1
	    vc[1] -= 1
	elif vc[1] == 0:
	    vc[0] -= 1
	else:
	    vc[1] -= 1

	if vc2[0] > vc2[1]:
	    vc2[0] -= 1
	elif vc2[1] > vc2[0]:
	    vc2[1] -= 1
	else:
	    vc2[0] -= 1
	    vc2[1] -= 1

	#print pc, vc, vc2
	if vc in [pc, pc1]:
	    #print 'Polycarp'
	    f1 = True
	if vc2 in [pc, pc1]:
	    f2 = True

    if f1 and f2:
	print 'Polycarp'
    else:
	print 'Vasiliy'


string = raw_input()
string = string.split()
xP = int(string[0])
yP = int(string[1])
xV = int(string[0])
yV = int(string[1])

#print xP, yP, xV, yV

Pwin = xP + yP
Vwin = min(xV, yV)

if (xP + 1) * 2 >= xV + 1 or (yP + 1) * 2 >= yV + 1:
    print 'Polycarp'
elif xP <= xV and yP <= yV:
    print 'Polycarp'
else:
    print 'Vasiliy'


x1,y1,x2,y2=map(int, raw_input().split())
if x1+y1 <= max(x2,y2) or (x1 <= y1 and x2 <= y2): print "Polycarp"
else: print "Vasiliy"


px, py, vx, vy = map(int, raw_input().split())

pd = px + py
vd = max(vx, vy)

if pd <= vd:
    print 'Polycarp'
    quit()
else:
    pc, vc, vc2 = [px, py], [vx, vy], [vx, vy]
    f1, f2 = False, False
    #print pc, vc
    for _ in xrange(vd):
	if pc[0] >= pc[1]:
	    pc[0] -= 1
	else:
	    pc[1] -= 1

	if 0 not in vc:
	    vc[0] -= 1
	    vc[1] -= 1
	elif vc[1] == 0:
	    vc[0] -= 1
	else:
	    vc[1] -= 1

	if vc2[0] > vc2[1]:
	    vc2[0] -= 1
	elif vc2[1] > vc2[0]:
	    vc2[1] -= 1
	else:
	    vc2[0] -= 1
	    vc2[1] -= 1

	#print pc, vc, vc2
	if vc == pc:
	    #print 'Polycarp'
	    f1 = True
	if vc2 == pc:
	    f2 = True

    if f1 and f2:
	print 'Polycarp'
    else:
	print 'Vasiliy'


xp, yp, xv, yv = map(int, raw_input().split())

if xp<=xv and yp<=yv:
    print "Polycarp"
else:
    print "Vasiliy"


n, m = map(int, input().split())

dignities = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
colors = ['C', 'D', 'H', 'S']
all_cards = []

for i in dignities:
    for j in colors:
        all_cards.append(i + j)

my_cards = [[] for x in range(n)]
joker1 = 0
joker2 = 0
for i in range(n):
    my_cards[i] = input().split()
    for j in range(m):
        if my_cards[i][j][1] == '1':
            joker1 = (i, j)
        elif my_cards[i][j][1] == '2':
            joker2 = (i, j)
        else:
            all_cards.remove(my_cards[i][j])

def intersect_segments(a, b, c, d):
    if a > b:
        a, b = b, a
    if c > d:
        c, d = d, c
    return a <= d and b >= c

def intersect_squares(a, b):
    return intersect_segments(a[0], a[2], b[0], b[2]) and intersect_segments(a[1], a[3], b[1], b[3])

def suitable(cards, x, y):
    colors = set()
    dignities = set()
    for i in range(x, x + 3):
        for j in range(y, y + 3):
            colors.add(cards[i][j][1])
            dignities.add(cards[i][j][0])
    return len(colors) == 1 or len(dignities) == 9

def ok(cards, n, m):
    for a in range(n - 2):
        for b in range(m - 2):
            if suitable(cards, a, b):
                for c in range(n - 2):
                    for d in range(m - 2):
                        if not intersect_squares((a, b, a + 2, b + 2), (c, d, c + 2, d + 2)) and suitable(cards, c, d):
                            return (a, b, c, d)
    return 0

for i in all_cards:
    for j in all_cards:
        if i != j:
            new_cards = my_cards
            if joker1 != 0:
                ans1 = i[0] + i[1]
                new_cards[joker1[0]][joker1[1]] = i
            if joker2 != 0:
                ans2 = j[0] + j[1]
                new_cards[joker2[0]][joker2[1]] = j
            if ok(new_cards, n, m):
                print('Solution exists.')
                if joker1 == 0 and joker2 == 0:
                    print('There are no jokers.')
                elif joker1 != 0 and joker2 != 0:
                    print('Replace J1 with %s and J2 with %s.' % (ans1, ans2))
                elif joker1 != 0:
                    print('Replace J1 with %s.' % (ans1))
                else:
                    print('Replace J2 with %s.' % (ans2))
                tmp = ok(new_cards, n, m)
                print('Put the first square to (%d, %d).' %
                      (tmp[0] + 1, tmp[1] + 1))
                print('Put the second square to (%d, %d).' %
                      (tmp[2] + 1, tmp[3] + 1))
                quit()
print('No solution.')


ranks = '23456789TJQKA'
suits = 'CDHS'

n, m = [int(i) for i in input().split()]
b = [input().split() for _ in range(n)]
p = [r + s for r in ranks for s in suits]
j1, j2 = False, False
for r in b:
    for c in r:
        if c == 'J1':
            j1 = True
        elif c == 'J2':
            j2 = True
        else:
            p.remove(c)

def valid(n, m):
    r = set()
    s = set()
    for ni in range(n, n + 3):
        for mi in range(m, m + 3):
            c = b[ni][mi]
            if c == 'J1':
                c = j1v
            if c == 'J2':
                c = j2v
            r.add(c[0])
            s.add(c[1])
    return len(r) == 9 or len(s) == 1

def solve():
    global j1v, j2v, n0, m0, n1, m1
    for j1v in p:
        for j2v in p:
            if j1v == j2v: continue
            for n0 in range(n-2):
                for m0 in range(m-2):
                    if not valid(n0, m0):
                        continue
                    for n1 in range(n-2):
                        for m1 in range(m-2):
                            if (n0 + 2 < n1 or n1 + 2 < n0 or
                                m0 + 2 < m1 or m1 + 2 < m0):
                                if valid(n1, m1):
                                    return True
    return False

if solve():
    print('Solution exists.')
    if j1 and j2:
        print('Replace J1 with {} and J2 with {}.'.format(j1v, j2v))
    elif j1:
        print('Replace J1 with {}.'.format(j1v))
    elif j2:
        print('Replace J2 with {}.'.format(j2v))
    else:
        print('There are no jokers.')
    print('Put the first square to ({}, {}).'.format(n0+1, m0+1))
    print('Put the second square to ({}, {}).'.format(n1+1, m1+1))
else:
    print('No solution.')


#!/usr/bin/python

import sys
import math

rank = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]
suit = ["C", "D", "H", "S"]
def print_ans(has_ans, jokes = [], pos = []):
    if not has_ans:
        print "No solution."
    else:
        print "Solution exists."
        if len(jokes) == 0:
            print "There are no jokers."
        elif len(jokes) == 1:
            print "Replace %s with %s." %(jokes[0][0], jokes[0][1])
        else:
            print "Replace %s with %s and %s with %s." \
                    %(jokes[0][0], jokes[0][1], jokes[1][0], jokes[1][1])
        print "Put the first square to (%d, %d)." %(pos[0][0]+1, pos[0][1]+1)
        print "Put the second square to (%d, %d)." %(pos[1][0]+1, pos[1][1]+1)

def overflow(p1, p2, step = 3):

    if (p1[0] <= p2[0] < p1[0] + step) and (p1[1] <= p2[1] < p1[1]+step):
        return True
    if (p2[0] <= p1[0] < p2[0] + step) and (p2[1] <= p1[1] < p2[1]+step):
        return True

    if (p1[0] <= p2[0] < p1[0] + step) and (p2[1] <= p1[1] < p2[1]+step):
        return True
    if (p2[0] <= p1[0] < p2[0] + step) and (p1[1] <= p2[1] < p1[1]+step):
        return True

    return False

def test_square(mat):
    hash = dict()
    for r in rank:
        hash[r] = "-"

    for i in range(0,3):
        for j in range(0,3):
            r,s = mat[i][j]
            if hash[r] == "-":
                hash[r] = s
            elif hash[r] != s:
                return False

    return True

def check(mat):
    n,m=len(mat),len(mat[0])
    res = []
    for i in range(0,n-2):
        for j in range(0,m-2):
            if test_square([ mat[k][j:j+3] for k in range(i,i+3) ]):
                res.append((i,j))

    for p1 in res:
        for p2 in res:
            if p1 == p2:
                continue
            elif (overflow(p1,p2)):
                continue
            else:
                return [p1,p2]
    return []

def replace_joke(item, cards, mat, jokes):
    if item >= len(jokes):
        pos = check(mat)
        if pos:
            print_ans(has_ans = True, jokes = jokes, pos = pos)
            return True
        else:
            return False

    joke,(jx,jy) = jokes[item]
    for card in cards:
        rest_cards = cards - set([card])
        mat[jx][jy] = card
        jokes[item][1] = card

        rt = replace_joke(item + 1, rest_cards, mat, jokes)
        if rt:
            return True
    jokes[item][1] = (jx,jy)
    return False

if __name__=="__main__":
    data = sys.stdin.readlines()
    n,m = [int(v) for v in data[0].split(' ')]
    mat = []

    cards = set([r+s for r in rank for s in suit])

    mat = [row[:-1].split(' ') for row in data[1:]]

    jokes = []
    for i,row in enumerate(mat):
        for j,card in enumerate(row):
            if card == "J1" or card == "J2":
                jokes.append( [card, (i,j)] )
            else:
                cards.remove(card)
    if (len(jokes) == 2 and jokes[0][0] == "J2" and jokes[1][0] == "J1"):
        jokes.reverse()

    rt = replace_joke(0, cards, mat, jokes)
    if not rt:
        print_ans(False)


'''input
3 6
2H 3H 4H 5H 2S 3S
6H 7H 8H 9H 4S 5S
TH JH QH KH 6S 7S
'''
from sys import stdin
import math
from copy import deepcopy

def find_jokers(grid, n, m):
	jokers = []
	for i in range(n):
		for j in range(m):
			if grid[i][j] == 'J1' and len(jokers) > 0:
				jokers.insert(0, [i, j])

			elif (grid[i][j] == 'J1' or grid[i][j] == 'J2'):
				jokers.append([i, j])

	return jokers

def get_remain(grid, n, m):
	total = set()
	for typ in ['D', 'S', 'H', 'C']:
		for rank in ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']:
			total.add(rank + typ)
	grid_set = set()
	for i in range(n):
		for j in range(m):
			grid_set.add(grid[i][j])

	r = total.difference(grid_set)
	r = list(r)
	return r

def replace(cgrid, x, y, item):
	cgrid[x][y] = item

def first_condition(grid, x, y):
	suit = set()
	for i in range(x, x + 3):
		for j in range(y, y + 3):
			suit.add(grid[i][j][1])
	if len(suit) == 1:
		return True
	else:
		return False

def second_condition(grid, x, y):
	rank = set()
	for i in range(x, x + 3):
		for j in range(y, y + 3):
			rank.add(grid[i][j][0])
	if len(rank) == 9:
		return True
	else:
		return False

def check_mark(mark, x, y):
	for i in range(x, x + 3):
		for j in range(y, y + 3):
			if mark[i][j] == True:
				return False
	else:
		return True

def make_mark(mark, x, y):
	for i in range(x, x + 3):
		for j in range(y, y + 3):
			mark[i][j] = True

def check(grid, n, m):
	count = 0
	mark = [[False for x in range(m)] for y in range(n)]

	for i in range(n):
		if i + 3 <= n:
			for j in range(m):
				if j + 3 <= m:
					if check_mark(mark, i, j):
						if first_condition(grid, i, j) or second_condition(grid, i, j):
								count += 1
								make_mark(mark, i, j)
								#print(mark)

	if count >= 2:
		return True
	else:
		return False

def get_ans(grid, n, m):
	ans = []
	mark = [[False for x in range(m)] for y in range(n)]

	for i in range(n):
		if i + 3 <= n:
			for j in range(m):
				if j + 3 <= m:
					if check_mark(mark, i, j):
						if first_condition(grid, i, j) or second_condition(grid, i, j):
								ans.append([i, j])
								make_mark(mark, i, j)

	return ans

# main starts
n, m = list(map(int, stdin.readline().split()))
grid = []
for _ in range(n):
	grid.append(list(stdin.readline().split()))

jokers = find_jokers(grid, n, m)
remaining = get_remain(grid, n, m)
#print(remaining)
if len(jokers) == 2:
	for i in range(len(remaining) - 1):
		for j in range(i + 1, len(remaining)):
			cgrid = deepcopy(grid)
			fx, fy = jokers[0]
			sx, sy = jokers[1]
			replace(cgrid, fx, fy, remaining[i])
			replace(cgrid, sx, sy, remaining[j])
			if check(cgrid, n, m):
				print('Solution exists.')
				print('Replace J1 with ' + str(remaining[i])+ ' and J2 with '+ str(remaining[j])+ '.')
				ans = get_ans(cgrid, n, m)
				print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').')
				print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').')
				exit()

			else:
				cgrid = deepcopy(grid)
				replace(cgrid, sx, sy, remaining[i])
				replace(cgrid, fx, fy, remaining[j])
				if check(cgrid, n, m, ):
					print('Solution exists.')
					print('Replace J1 with ' + str(remaining[j])+ ' and J2 with '+ str(remaining[i])+ '.')
					ans = get_ans(cgrid, n, m)
					print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').')
					print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').')
					exit()
				else:
					pass

elif len(jokers) == 1:
	for i in range(len(remaining)):
		cgrid = deepcopy(grid)
		fx, fy = jokers[0]
		replace(cgrid, fx, fy, remaining[i])
		if check(cgrid, n, m):
			print('Solution exists.')
			print('Replace '+ str(grid[fx][fy]) +' with ' +  str(remaining[i]) +'.')
			ans = get_ans(cgrid, n, m)
			print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').')
			print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').')
			exit()

		else:
			continue
else:
	if check(grid, n, m):
		print('Solution exists.')
		print("There are no jokers.")
		ans = get_ans(grid, n, m)

		print('Put the first square to ' + '(' + str(ans[0][0] + 1) + ', ' + str(ans[0][1] + 1) + ').')
		print('Put the second square to ' + '(' + str(ans[1][0] + 1) + ', ' + str(ans[1][1] + 1) + ').')
		exit()
	else:
		pass

print("No solution.")


n, m = map(int, input().split()) dignities = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] colors = ['C', 'D', 'H', 'S'] all_cards = [] for i in dignities: for j in colors: all_cards.append(i + j) my_cards = [[] for x in range(n)] joker1 = 0 joker2 = 0 for i in range(n): my_cards[i] = input().split() for j in range(m): if my_cards[i][j][1] == '1': joker1 = (i, j) elif my_cards[i][j][1] == '2': joker2 = (i, j) else: all_cards.remove(my_cards[i][j]) def intersect_segments(a, b, c, d): if a > b: a, b = b, a if c > d: c, d = d, c return a <= d and b >= c def intersect_squares(a, b): return intersect_segments(a[0], a[2], b[0], b[2]) and intersect_segments(a[1], a[3], b[1], b[3]) def suitable(cards, x, y): colors = set() dignities = set() for i in range(x, x + 3): for j in range(y, y + 3): colors.add(cards[i][j][1]) dignities.add(cards[i][j][0]) return len(colors) == 1 or len(dignities) == 9 def ok(cards, n, m): for a in range(n - 2): for b in range(m - 2): if suitable(cards, a, b): for c in range(n - 2): for d in range(m - 2): if not intersect_squares((a, b, a + 2, b + 2), (c, d, c + 2, d + 2)) and suitable(cards, c, d): return (a, b, c, d) return 0 for i in my_cards: for j in my_cards: if i != j: new_cards = my_cards if joker1 != 0: new_cards[joker1[0]][joker1[1]], i = i, new_cards[joker1[0]][joker1[1]] if joker2 != 0: new_cards[joker2[0]][joker2[1]], i = i, new_cards[joker2[0]][joker2[1]] if ok(new_cards, n, m): print('Solution exists.') if joker1 == 0 and joker2 == 0: print('There are no jokers.') elif joker1 != 0 and joker2 != 0: print('Replace J1 with %s and J2 with %s.' % (i[0] + i[1], j[0] + j[1])) elif joker1 != 0: print('Replace J1 with %s.' % (i[0] + i[1])) else: print('Replace J2 with %s.' % (j[0] + j[1])) tmp = ok(new_cards, n, m) print('Put the first square to (%d, %d).' % (tmp[0] + 1, tmp[1] + 1)) print('Put the second square to (%d, %d).' % (tmp[2] + 1, tmp[3] + 1)) quit() print('No solution.')


__author__ = 'Darren'

def solve():
    from math import ceil
    x = abs(int(input()))
    k = ceil(((8 * x + 1) ** 0.5 - 1) / 2)
    location = k * (k + 1) // 2
    if location == x:
        print(k)
    elif ((location - x) + (k + 1)) % 2 == 0:
        print(k+1)
    else:
        print(k+2)

if __name__ == '__main__':
    solve()


def main():
	x = int(input())
	print(jumps(x))

def jumps(n):
	i = 0
	while True:
		product = i * (i + 1) // 2
		if product >= n and product % 2 == n % 2:
			return i
		i += 1

#print(jumps(6))
main()


pol = raw_input('')
pol = int(pol)

tekPol = 0
kol = 1

while pol != tekPol:
    if (tekPol + kol) <= pol:
        tekPol = tekPol + kol
    else:
        tekPol = tekPol - kol

    kol = kol + 1

kol = kol - 1

print kol


def _f(x):
    step = 0
    achieved = set([0])
    while x not in achieved and -x not in achieved:
        step += 1
        tmp = set()
        for cell in achieved:
            a = cell + step
            b = cell - step
            if b < 0: b *= -1
            tmp.add(a)
            tmp.add(b)
        achieved = tmp
        print achieved
    return step

def f(x):
    m = s = 0 if x%2 == 0 else 1
    while x > m or m%2 != x%2:
        s += 1
        m += s
    return s

x = input()
print "steps is %d"%f(x)


    a = abs(int(input()))
    b = 0
    while a > 0 or a & 1:
        b += 1
        a -= b
    print(b)


#552C

from math import *

w,m = map(int, input().split())
arr =[]
p=1
for i in range(101):
	arr.append(p)
	p*=w
arr.reverse()
for i in range(101):
	val1 = m+arr[i]
	val2 = abs(m-arr[i])
	m = min(m, min(val1,val2))
print ("YES" if !m else "NO")


#include <bits/stdc++.h>

using namespace std;

#define int long long

const int INF = 1e12;

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

    int w, n;
    cin >> w >> n;

    if (w == 2) {
        cout << "YES\n";
        exit(0);
    }

    vector <int> a, b;
    int curr = 1;

    for (int i = 0; i < 10; ++i) {

        if (INF / curr + 1 < w) break;
    }

    return 0;
}


w,m=map(int,input().split())
while m:
 if 1<m%w<m-1: break
 m=(m+1)%w
print("NO" 1<m%w<m-1 else "YES")


Last login: Sat Jun 20 09:37:04 on console
bogon:~ yanzhensong$ cd Desktop/
bogon:Desktop yanzhensong$ vim cf.py

bogon:Desktop yanzhensong$ vim cf.py
bogon:Desktop yanzhensong$ vim cf.py

w,m=map(int,raw_input().split());
bit=[];
ct=[];
for i in range(101):
    ct.append(0);
k=m;
while(k>0):
    bit.append(k%w);
    k/=w;
for i in range(len(bit)):
    if(bit[i]==w-1):
        ct[i+1]+=1
        ct[i]-=1
    else:
        ct[i]+=bit[i]
while(1):
    flag1=0
    flag2=0
    for i in range(101):
        if(ct[i]==0 or ct[i]==1 or ct[i]==-1 ):
            continue
        elif(ct[i]==w-1):
            ct[i]=-1
            ct[i+1]+=1
            flag1=1
        elif(ct[i]==1-w):
            ct[i]=1
            ct[i+1]-=1
            flag1=1
        else:
            flag2=1
    if(flag1==1): continue
    if(flag2==1):
        print 'NO'
        exit()
    break
print 'YES'


y,x = map(int,raw_input().split())
if y==2 || y ==3:
    print "YES"
    quit()
while x != 0:
    u = x % y
    #print u
    if u != y - 1 and u != 0 and u != 1:
        print "NO"
        quit()
    if u == y - 1:
        x += 1
    else:
        x /=y
print "YES"


    a,b= map(int,input().split(' '))
    print(a+b)
    # im done for


a=(int)a;
b=(int)b;
a=input()
b=input()
print(a + b)


int s = int(input());
int s1 = int(input());
print(s+s1);


a,ans,x=input(),-1,[]
for i in a:
    y=x[:]
    for t in y:
        m=t*10+int(i)
        if ceil(m**.5)==int(m**.5):
            if ans <m:ans=m
        x.append(m)
    if i!='0':
        i=int(i)
        if ceil(i**.5)==int(i**.5):
            if ans <i:ans=i
        x.append(int(i))

print(ans if ans==-1 else len(a)-len(str(ans)))


sx=set()
for i in range(100004):
	s.add(i*i)
global ans
ans=10000000

def f(ii,a):
	if ii==len(s):
		x=""
		for i in range(len(s)):
			if a[i]==1:
				x+=s[i]
		if len(s)>0:
			if s[0]!='0':
				if int(x) in sx:
					ans=min(ans,a.count(0))
	else:
		f(ii+1,a+[1])
		f(ii+1,a+[0])

s=raw_input()
a=[]
i=0
f(i,a)
if ans==10000000:
	print -1
else:
	print ans


import numpy as np

n=int(input())
#n=606725
if int(np.sqrt(n))==np.sqrt(n):
    print(0)

else:
    st=str(n)
    L=len(st)

    subs = []
    for i in range(len(st)):
        for j in range(i, len(st)):
            if st[i:j + 1][0] !=0:
                subs.append(st[i:j + 1])

    results=[]
    for x in subs:
        n=int(x)
        if int(np.sqrt(n)) == np.sqrt(n):
            results.append(L-len(x))

    if len(results) ==0:
        print(-1)
    else:
        print(min(results))


s=input()
import math
def rec(s,lis):
    new=[]
    if(len(lis)!=0 and len(lis[0])==1):
        return -1
    elif(len(lis)==0):
        for i in range(len(s)):
            a=s[:i]+s[i+1:]
            if(math.sqrt(int(a))-int(math.sqrt(int(a)))==0 and a[0]!="0"):
                return (len(s)-len(a))
            new.append(a)
    else:
        for j in range(len(lis)):
            k=lis[j]
            for i in range(len(k)):
                a=k[:i]+k[i+1:]
                if(math.sqrt(int(a))-int(math.sqrt(int(a)))==0 and a[0]!="0"):
                    return (len(s)-len(a))
                new.append(a)
    return rec(s,list(set(new)))
lis=[]
if(math.sqrt(int(s))-int(math.sqrt(int(s)))==0 and s[0]!="0"):
    print(0)
else:
    ans=rec(s,lis)
    print(ans)


s = input()
for i in range(10**5, 0, -1):
    t, p = str(i * i)+'$', 0
    for x in s:
        if x == t[p]:
            p += 1
    if p == len(t)-1:
        res = min(res, len(s) - len(t)+1)
else
    print(-1)


import math
from collections import Counter
a = raw_input()
b = raw_input()
d = Counter((a.strip()))
s = d['+'] - d['-']
d = Counter(b.strip())
pos = d['?']
s -= d['+'] - d['-']
if pos == s:
    return 1
else:
    if (pos - math.abs(s)) % 2 == 0:
        return (math.factorial(pos)/(math.factorial((pos + s)/2) * math.factorial((pos - s)/2)))/(2 ** pos)
    else:
        return 0


whereToGo = 0
for correct in input():
  if correct = "+":
    whereToGo += 1
  else:
    whereToGo -= 1
hey = input()


def ncr(n,r):
	return(fact(n)/(fact(r)*fact(n-r)))
def fact(n):
	res=1
	for i in range(2,n+1):
		res=res*i
	return res

l1=list(input())
l2=list(input())
c1=0
c2=0
c3=0
for k in range(len(l1)):
	if(l1[k]=='+'):
		c1+=1
	if(l2[k]=='+'):
		c2+=1
	if(l2[k]=='?'):
		c3+=1
a=c1-c2

if(c3>=a):
	a1=ncr(c3,a)
	print(a1/(2**c3)
else:
	print(0/(2**c3))


//WeirdBugsButOkay

s = input()
t = input()

unk = 0
acp = 0
cp = 0
for i in range (0,len(s)) :
    if t[i] == '?' :
        unk += 1
    elif t[i] == '+' :
        acp += 1
    else :
        acp -= 1
    if s[i] == '+' :
        cp += 1
    else :
        cp -= 1
ans = 0
if cp - unk > acp or cp + unk < acp :
    print('%0.11f'%0)
elif unk == 0 :
    if cp == acp :
        print('%0.11f'%1)
    else :
        print('%0.11f'%0)
else :
    ct = cp - acp
    if ct % 2 != 0 :
        print('%0.11f'%0)
    else :
        cnt = (ct + unk) // 2
        ncr = 1
        for i in range (0, cnt) :
            ncr *= (unk - i)
            ncr //= (i + 1)
        ans = ncr
        ans /= (2**unk)
        print('%0.11f'%ans)


string=str(input())
s=len(string)
k=int(input())

def tandemcheck(n):
	if len(n)%2==1:
		return False
	else:
		if n[:len(n)//2]==n[len(n)//2:]:
			return True
		else:
			return False

if s<=k:
	if (s+k)%2==0:
		print(s+k)
	else:
		print(s+k-1)
else:
	if 2*k>=s:
		max=2*k
		for i in range(1,int(s/2)):
			if string.count(string[-i:])>1:
				if max<(s-string.index(string[-i:])-i)*2:
					max=(s-string.index(string[-i:])-i)*2
		print(max)
	else:
		maxs=0
		for i in range(0,s-1):
			for j in range(i,s):
				if tandemcheck(string[i:j+1]):
					maxs=max(maxs,len(string[i:j+1])
		maxboth=2*k
		for i in range(1,int(s/2)):
			if string.count(string[-i:])>1:
				if maxboth<(s-string.index(string[-i:])-i)*2:
					maxboth=(s-string.index(string[-i:])-i)*2
		print(max(maxs,maxboth))


s = raw_input()
k = raw_input()

sm = len(s) + k
mx = sm if sm % 2 == 0 else sm - 1
# cntr = mx / 2
ddone = False
while mx > 0:
    strt = 0
    cntr = mx / 2
    while strt + mx <= sm:
        step = strt + cntr
        for i in range(strt, strt + step):
            j = i + step
            if i < len(s):
                if j < len(s):
                    if s[i] == s[j]:
                        pass  # great
                    else:  # s[i] != s[j]
                        break
                else:  # j > len(s)
                    pass  # we can add here what we want
            ddone = True
        strt += 1
    if ddone:
        print mx
        break
    mx -= 2
    # cntr /= 2


import sys
fin=open('F:/OJ/OJ/in.txt','r')
sys.stdin=fin

str=input()
k=int(input())
ans=0
if(k>=len(str)):
    print((k+len(str))//2)
    exit()
for i in range(len(str)):
    for j in range(0,i+1):
        len1=len(str[j:i+1])
        len2=len(str[i+1:])
        minn=min(len1,len2)
        #print( i,j)
        #print(len1,len2)
        if(str[j:j+minn]==str[i+1:i+1+minn]):
            if(minn==len1):
                ans=max(ans,len1*2)
            elif(k+len2>=len1):
                ans=max(ans,len1*2)

print(ans)


s = raw_input()
k = raw_input()
k1 = ''
for i in range(k):
    k1 += '1'
s = s + k1

def sravn(s):
    for i in xrange(len(s)/2):
        if s[i] != s[i+len(s)/2] and s[i+len(s)/2] != '1':
            return 'no'
        return 'yes'

l = len(s)/2*2
while l >= 2:
    for i in range(len(s)-l+1):
        t = sravn(s[i:l])
        if t == 'yes':
            print l
        else:
            l -= 2


import sys
from time import time

line=sys.stdin.readline().strip('\n')
k=int(sys.stdin.readline().strip('\n'))

def isRepeat(inp):
    if len(inp)%2==1:
         return False
    else:
        for i in xrange(0,len(inp)/2):
            if inp[i]!=inp[i+len(inp)/2]:
                return False
    return True

def findTandemRepeat(inp):
    remove=0
    while(remove<len(inp)):
        for i in xrange(0,remove+1):
            temp=inp[i:len(inp)-remove+i]
            if isRepeat(temp):
                return len(inp)-remove
        remove+=1
    return 0

if k<=len(line):
    best=0
    for i in range(0,len(line)-k+1):
        #print (line + line [i:i+k])
        best=max(best,findTandemRepeat(line + line[i:i+k]))

    print best

else:
    print str(2*((k+len(line))/2))


a = [['x', 'x'], ['x', 'x']]
b = [['x', 'x'], ['x', 'x']]

def idx(i):
    if i > 1:
        return 0

    if i < 0:
        return 1

    return i

def swap(a, ia, ja, ib, jb):
    t = a[ia][ja]
    a[ia][ja] = a[ib][jb]
    a[ib][jb] = t

import copy

def dfs(a, seen):
    seen.append(a)
    for i in range(2):
        for j in range(2):
            if a[i][j] != 'X':
                continue

            acp = copy.deepcopy(a)
            swap(acp, i, j, idx(i+1), j)
            if acp not in seen:
                dfs(acp, seen)
            swap(acp, i, j, idx(i+1), j)

            swap(acp, i, j, i, idx(j+1))
            if acp not in seen:
                dfs(acp, seen)
            swap(acp, i, j, i, idx(j+1))

    return seen

def main():
    for j in range(2):
        # print j
        if j == 0:
            s1, s2 = raw_input(), raw_input()
            a[0][0] = s1[0]
            a[0][1] = s1[1]
            a[1][0] = s2[0]
            a[1][1] = s2[1]

        if j == 1:
            s1, s2 = raw_input(), raw_input()
            b[0][0] = s1[0]
            b[0][1] = s1[1]
            b[1][0] = s2[0]
            b[1][1] = s2[1]

    # print a, b
    arr = dfs(a, [])

    if b in arr:
        print "YES"
    else:
        print "NO"

main()


def ayy(b1, b2):
    b1 = b1.replace("X","")
    b2 = b2.replace("X","")
    #moves string through cycle
    if b1 == b2:
        print "YES"
    elif b1[1:]+b1[0] == b2:
        print "YES"
    elif b1[2]+b1[:2] == b2:
        print "YES"
    else:
        print "NO"

def go():
    s = ""
    sentinel = '' # ends when this string is seen
    for line in iter(raw_input, sentinel):
        s += (line + "\n")
    s = s[:len(s)-1]
    A = s.split("\n")
    b1 = A[0]+A[1][1]+A[1][0]
    b2 = A[2]+A[3][1]+A[3][0]
    #gets clockwise motion of the strings
    ayy(b1,b2)

go()


str1 = raw_input();
str2 = raw_input();
list1=  []
list1.append(str1[0])
list1.append(str1[1])
list1.append(str2[1])
list1.append(str2[0])
for i in xrange(4):
    if list1[i] == 'X':
        del list1[i]
str1 = raw_input();
str2 = raw_input();
list2=  []
list2.append(str1[0])
list2.append(str1[1])
list2.append(str2[1])
list2.append(str2[0])
for i in xrange(4):
    if list2[i] == 'X':
        del list2[i]
        break
for i in xrange(3):
    if list1[0] != list2[0]:
        temp = list1[0]
        del list1[0]
        list1.append(temp);
if list1[0] == list2[0] and list1[1] == list2[1]:
    print 'YES'
else:
    print 'NO'


l=[]
for i in range(2):
    r=list(input()+input())
    while r[0]!="A":r[0],r[1],r[2]=r[2],r[0],r[1]
    r.remove("X");l.append("".join(r))
print("YES"if l[0]==l[1]else"NO")


n = int(input())

for i in range(int(sqrt(n), n+1):
    if n % i == 0:
        print(n/i, i)
        break


import math

def is_square(n):
    sqrt = math.sqrt(n)
    return (sqrt - int(sqrt)) == 0

pixel = int(input())

if is_square(pixel): result = (int(math.sqrt(self.pixel)),int(math.sqrt(self.pixel)))
else:
    lista =[]
    for i in range(1, pixel+1):
        if pixel%i == 0 :lista.append(i)
    pivot = int(len(lista)/2)-1
    row = lista[pivot]
    column = lista[pivot+1]
    result = (row,column)

 priint(f"{' '.join(map(str,result))}")


import math

n = int(input())

a = 1
b = n

m=int(math.sqrt(n))

for i in range(1, m+1):

    x = i
    if n % x == 0:
        y = n // x
        if b - a > y - x:
            a = x
            b = y

print(a, b)
/*
#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector<int>arr;
    vector<int>brr;
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(i*j==n)
            {
                arr.push_back(i);
                arr.push_back(j);
            }
        }
    }
    /*for(int i=0;i<arr.size();i++){
        cout<<arr[i]<<" ";
    }
    */
    /*cout<<endl;
    for(int j=0;j<brr.size();j++){
        cout<<brr[j];
    }*/
    //cout<<endl;
    int x;
    for(int i=0;i<arr.size();i+=2){
        x = arr[i+1]-arr[i];
        brr.push_back(abs(x));

    }

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

    for(int j=0;j<arr.size();j++){
        if((arr[j+1]-arr[j])==brr[0])
        {
            cout<<arr[j]<<" "<<arr[j+1];
        }
    }
    */

}


n = int(input())

for i in renge(int(sqrt(n), n+1):
    if n % i == 0:
        print(n/i, i)
        break


from math import sqrt
n = int(input())

for i in range(int(sqrt(n), n+1):
    if n % i == 0 and i >= sqrt(n):
        print(n/i, i)
        break


a,b,c=map(int,input().split())
n1=a//3
n2=b//2
n3=c//2
r=min(n1,n2,n3)
a-=r*3
b-=r*2
c-=r*2
d={}
l=['f','r','c','f','c','r','f']
if a>=b and a>=c:
	if b>c and a>b+1:
		k=5
	elif b>=c and a<b+1:
		k=3

	elif c>b and a>c+1:
		k=6
	elif c>b and a<=c+1:
		k=0
else:
	if b>=c:
		k=4
	else:
		k=1
d['f']=a
d['r']=b
d['c']=c
count=0
for i in range(k,k+7):
	e=i%7

	if d[l[e]]>0:
		d[l[e]]-=1
		count+=1
	else:
		break

print(count+r*7)


a, b, c = map(int, input().split())

D = min(a // 3, b // 2, c // 2)
A, B, C = a - 3 * D, b - 2 * D, c - 2 * D

ans = D * 7

if A == 0 and C == 0 and B == 0:
    print(ans)

elif C == 0 and B == 0:
    if A == 1:
        print(ans + 1)
    else:
        print(ans + 2)

elif C == 0:
    if B == 1 and A == 1:
        print(ans + 2)
    elif B == 1 and A >= 2:
        print(ans + 3)
    elif B == 1 and A == 0:
        print(ans + 1)
    elif A == 0:
        print(ans + 1)
    elif A == 1:
        print(ans + 2)
    else:
        print(ans + 4)
elif C == 1:
    if B == 1:
        if A == 1:
            print(ans + 3)
        elif A == 0:
            print(ans + 2)
        else:
            print(ans + 4)

    elif B== 0:
        if A == 0:
            print(ans)
        elif A == 1:
            print(ans + 2)
        else:
            print(ans + 2)
    else:
        if A == 0:
            print(ans + 2)
        elif A == 1:
            print(ans + 3)

        else:
            print(ans + 5)
else:
    if B == 0:
        if A == 0:
            print(ans + 1)
        elif A == 1:
            print(ans + 2)
        else:
            print(ans + 3)
    if B == 1:
        if A == 0:
            print(ans + 2)
        elif A == 1:
            print(ans + 4)
        elif A == 2:
            print(ans + 5)
        else:
            print(ans + 6)
    else:
        if A == 0:
            print(ans + 2)
        elif A == 1:
            print(ans + 5)
        elif A == 2:
            print(ans + 6)


#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Codeforces Round #552 (Div. 3)

Problem C. Gourmet Cat

:author:         Kitchen Tong
:mail:    kctong529@gmail.com

Please feel free to contact me if you have any question
regarding the implementation below.
"""

__version__ = '0.1'
__date__ = '2019-04-16'

import sys

def count_days(a, b, c):
    weeks = min(a // 3, b // 2, c // 2)
    a -= weeks * 3
    b -= weeks * 2
    c -= weeks * 2
    if a == 0:
        if b > 0:
            if c > 0:
                return weeks * 7 + 2
            else:
                return weeks * 7 + 1
        elif c > 0:
            return weeks * 7 + 1
    elif a == 1:
        if c > 1:
            return weeks * 7 + 3 + min(2, b)
        else:
            return weeks * 7 + 1 + min(1, b) + min(1, c)
    elif a == 2:
        if b > 0:
            if b > 1:
                return weeks * 7 + 2 + min(2, c)
            else:
                if c > 0:
                    return weeks * 7 + 4
        else:
            return weeks * 7 + 2
    else:
        if c == 0:
            return weeks * 7 + 2 + min(2, b)
        else:
            if c > 1:
                return weeks * 7 + 3
            else:
                return weeks * 7 + 2
    return weeks * 7

def main(argv=None):
    a, b, c = map(int, input().split())
    print(count_days(a, b, c))
    return 0

if __name__ == "__main__":
    STATUS = main()
    sys.exit(STATUS)


[a,b,c] = (input().split(' '))
a = int(a)
b = int(b)
c = int(c)
days = 0;

factor = 10000000
while factor!=1:
    while a>2*factor and b>1*factor and c>1*factor:
    a -= 3*factor
    b -= 2*factor
    c -= 2*factor
    days += 7*factor
    factor /= 10

while a>2 and b>1 and c>1:
    a -= 3
    b -= 2
    c -= 2
    days += 7

if c>1 and b>1:
    if a==0:
        days += 2
    elif a==1:
        days += 3
    elif a==2:
        days += 4

elif c>1 and a>2:
    if b==0:
        days += 3
    elif b==1:
        days += 6

elif b>1 and a>2:
    if c==0:
        days += 4
    elif c==1:
        days += 6

elif c>1:
    if b==0 and a==0:
        days += 1
    elif b==0 and a==1:
        days += 2
    elif b==0 and a==2:
        days += 2
    elif b==1 and a==0:
        days += 2
    elif b==1 and a==1:
        days += 4
    elif b==1 and a==2:
        days += 5

elif b>1:
    if c==0 and a==0:
        days += 1
    elif c==0 and a==1:
        days += 2
    elif c==0 and a==2:
        days += 4
    elif c==1 and a==0:
        days += 2
    elif c==1 and a==1:
        days += 3
    elif c==1 and a==2:
        days += 5

elif a>2:
    if b==0 and c==0:
        days += 2
    elif b==0 and c==1:
        days += 3
    elif b==1 and c==0:
        days += 3
    elif b==1 and c==1:
        days += 5

elif a==2:
    if b==0 and c==0:
        days += 2
    elif b==0 and c==1:
        days += 3
    elif b==1 and c==0:
        days += 3
    elif b==1 and c==1:
        days += 4

elif a==1:
    if b==0 and c==0:
        days += 1
    elif b==0 and c==1:
        days += 2
    elif b==1 and c==0:
        days += 2
    elif b==1 and c==1:
        days += 3

elif a==0:
    if b==0 and c==0:
        days += 0
    elif b==0 and c==1:
        days += 1
    elif b==1 and c==0:
        days += 1
    elif b==1 and c==1:
        days += 2

print(days)


n=input()
if n == 0:
	print 0
else:
	print 3**(n-1)%(10**6 + 3)


n = int(input())
print(pow(3,n)-1,pow(10,6)+3) if n > 0 else 0)


n = input()
e = 1
s = 1

while e < n:
	s := s * 3
	e := e + 1

print(s)


n,m = map(int, input().split())
l = list(map(int, input().split()))
c = 0
i = 0
s = 0
while i<n:
	while s<m:
		s = s + l[i]
		i = i+1
	s = 0
	n = n-1
	c = c+1
	i = i-1
print(c)


a,b = map(int, input().split())
ar = list(map(int, input().split()))

count=1
sums=0
for i in range(a):
	sums += ar[i]
	if(sums > m):
		sums = ar[i]
		count += 1
print(count)


# нужно выспаться
def main():
    n, m = map(int, raw_input().split())
    a_arr = map(int, raw_input().split())
    result = set()
    for i, a_i in enumerate(a_arr):
        tmp = m - a_i
        j = i + 1
        if tmp != 0:
            while j < len(a_arr) and tmp != 0:
                if a_arr[j] <= tmp:
                    tmp -= a_arr[j]
                    j += 1
                else:
                    break
        result.add(j)
    print len(result)

if __name__ == '__main__':
    main()


n, m = map(int,input().split())
a = list(map(int,input().split()))
b = 0
turn = 0
for i in range(n):
    turn += a[i]
    if turn >= m :
        b += 1
        turn = a[i]
if a[-1] + a[-2] > m :
    b += 1
print(b)


a,b=[int(i) for i in input().split()]
s=[int(i) for i in input()split()]
m=0
c=b
for i in range(a):
    if s[i]>c:
        m=m+1
        c=b
    else:
        c=c-s[i]
print(m)


def function(n, nums):
    odd_pair_count=0
    odd_count1=0
    odd_count2=0
    for j in range(n):
        condition=True
        if nums[j][0]%2!=0 and nums[j][-1]%2!=0:
            odd_pair_count+=1
        if nums[j][0]%2!=0:
            odd_count1+=1
        if nums[j][-1] % 2 != 0
            odd_count2+=1
    if (odd_count1 + odd_count2) % 2 != 0:
        return -1
    if (odd_count1+odd_count2)%2==0:
        if odd_pair_count*2-(odd_count1+odd_count2)==0:
            return -1
        if odd_count1%2==0 and odd_count1==odd_count2:
            return 0
        return 1

if __name__=="__main__":
    n=int(input())
    nums=[]
    for i in range(n):
        nums.append(list(map(int, input().rstrip().split())))
    print(function(n, nums))


n = int(input())
x,y,z = [0]*3
for i in range(n):
    a,b = input().split()
    x += int(a)
    y += int(b)
    z += (int(a)+int(b))%2
print ((-1,(0,(-1,1)[z>0])[y%2])[x%2==y%2])
→Judgement Protocol


# Здесь делаю через вложенные списки [[x1,y1],[x2,y2],[xi,yi]]. Строковые данные преобразую в целые числа и помещаю в списки.
# Считаю сумму верхних половинок = upper . Затем нижних = lower. Проверяем четность обеих переменных
# Когда ничего менять не надо, или всего одна кость - выводи соот. значение и все.
# Иначе начинаем менять. Через for...in получаем кость из ряда ( т.е. список[xi,xi]), меняем местами и с помощью
# функции check_parity проверяем измения наших upper и lower, и их четность.В цикле есть счетчик(count)-кол-во изменений костей.
# Если все хорошо - выводим 1, если нет, то берем след. кость и снова функцию...
# В конце, если мы не получили четность, и кол-во костей(n) равно значению счетчика(count)
# т.е. n=count, то выводим -1

Flag= True # для вечного цикла while. Он ниже
upper = 0 #    сумма верхних половинок
lower = 0 #    сумма нижних половинок
Row_of_bones = []
n = int(input())
for i in range(n):												#Получив кол-во костей, последовательно заполняем список
	x = list(map(int, (input().split())))		#"Налету" превращаем в список с целыми числами
	Row_of_bones.append(x)											#Собственно помещаем кость[xi,yi] в ряд []
#print(Row_of_bones)
#print(Row_of_bones[1][1])

def check_parity() -> bool:        #Функция, в которой я пересчитываю верхние и нижние суммы, а затем проверяю на четность.
	upp,low =0,0
	for i in Row_of_bones:
		upp += i[0]
		low += i[1]
	if (upp % 2 == 0) and (low % 2 == 0):
		#print("Апп и лов после смены кости = ", upp, " " ,low) # Можно отслеживать промежуточные результат
		return True
	else:
		return False

for i in Row_of_bones: # Считаю верхнию и нижнию сумму. В i помещается кость [xi,yi] из ряда
	upper += i[0]
	lower += i[1]

#print("Изначальные ап и лов = ",upper," ",lower) # Можно отслеживать промежуточные результат

while(Flag):                                    # Бесконечный цикл, где мы проверяем на четность в первые раз и отсеиваем
	if (upper % 2 == 0) and (lower % 2 == 0):   #простые случае, когда ничего делать не надо
		print(0)
		break
	elif (n == 1):
		print(-1)
		break
	else:
		count = 0 # Счетчик действий
		for i in Row_of_bones:
			i[0],i[1] = i[1], i[0] # меняем местами значения элементов без буферной переменной, возможность питона
			count+=1
			if (check_parity()): # После одноразового перемещения первый кости проверяем на четность
				print(1)     # Если все хорошо - выводим и выходим через break'и
				break
		if count == n:      # Когда после смещения всех костей, ни к чему не пришли, то есть n == count
			print(-1)
		break
# Хочу отметить, что основой алгоритм перещения кости - очень простой. Берем первую кость и просто переворачиваем.Затем вторую
# и  так далее. И надеемся на чудо :) Тестовые данные обрабатывает правильно
#Пробовал усложнить тестовые, и приходил к правильной работе программы
#Входные:     3                4			5
#           1  2             1  3		   1 3
#           3  3             4  1		   4 1
#           6  4             5  6		   2 3
#                            2  3		   6 5
#										   3 4
#Выходные:  -1               -1


t = int(input())
i=0
l =[]
u = []
ans= False
for _ in range(t):
    n = list(map(int, input().split()))
    l.append(n[1])
    u.append(n[0])
    if n[1]%2 != n[0]%2:
        ans = True
if sum(l)%2==0 and sum(u)%2==0:
    print("0")
elif sum(l)%21=sum(u)%2:
    print("-1")
else:
    if ans:
        print("1")
    else:
        print("-1")


n=input()
F=0
for i in range(n):
    a,b=input()
    if abs(a-b)==1:
        F=1

    suma=suma+a
    sumb=sumb+b

if suma%2==0 and sumb%2==0:
    print 0
elif suma%2==1 and sumb%2==1:
    if F==1
        print 1
    else:
        print -1
else:
    print -1


def IsPrime(n):
    d = 2
    if n != 1:
        while n % d != 0:
            d += 1
    return d == n

p = False
n, m, k = [int(i) for i in input().split()]

if m==2 and k==1 :
    if n%2!=0:
        print('Timur')
    else:print('Marsel')
    quit()
if k!=1:
    for i in range(m // 2, k - 1, -1):
        if m % i == 0:
            p = True
if p==False and k!=1:
    print('Marsel')
    quit()
if IsPrime(m):
    print('Marsel')
elif k >= m:
    print('Marsel')
elif m % 2 == 0 or m % 2 != 0:
    if n % 2 != 0:
        print('Timur')
    else:
        print('Marsel')


def max_divisor(n):
    m = n / 2
    while m > 1:
	if n % m == 0:
	    return m
	m -= 1
    return 1

def solve(n, m, k):
    if n % 2 == 0:
	return False
    elif max_divisor(m) >= k:
	if m == 1:
	    return False
	else:
	    return True
    return False

def main():
    n, m, k = map(int, raw_input().split())
    if solve(n, m, k):
	print "Timur"
    else:
	print "Marsel"

main()


def can(n, m, k):
    if n % 2 == 0:
        return False
    d = 1
    while d*d <= m:
        if m % d == 0 and (d in range(k, m) or m/d in range(k, m)):
            return True
        d += 1
    return False

n, m, k = map(int, input().split(' '))
print ('Timur' if can(n, m, k) else 'Marsel')


from collections import Counter
nn,mm,kk=[int(i) for i in input().split()]
if nn%2==0:
    print('Marsel')
    exit(0)

def get_ls(n):
    result = []
    i = 2
    while i < n:
        if n % i == 0:
            n /= i
            result.append(i)
        else:
            i += 1
    result.append(int(n))
    return result

#print(mm)
if  mm%499999993==0:
    mm=mm//499999993
    ls = get_ls(mm)
    ls.append(499999993)
    mm*=499999993
else:
    ls = get_ls(mm)
#print(ls)
kkk = dict(Counter(ls)).items()
d = [k for k, _ in kkk]
m = [v for _, v in kkk]
k = [0 for _ in range(len(set(ls)))]
ln = range(len(m))
dels=[]
try:
    while True:
        r = 1
        for i1, i2 in zip(d, k):
            r *= i1 ** i2
        dels.append(r)

        k[0] += 1
        for i in ln:
            if k[i] > m[i]:
                k[i] = 0
                k[i+1] += 1
except IndexError:
    pass
for i in dels:
    #print(i,kk,mm)
    if kk<=i<mm:
        print('Timur')
        exit(0)
print('Marsel')


x=input()
l=x.split()
n=int(l[0])
m=int(l[1])
k=int(l[2])
def func_2(m,k):
    s=int(m**.5)
    for i in range(2,s+1):
        if not m%i:
            if i>=k or m/i>=k:
                return True
    return False
def func_1(m,k):
    for i in range(k,m):
        if not m%i:
            return True
    return False
if func_1(m,k):
    p=n
else :
    p=0
if p%2==0:
    print('Marsel')
else :
    print('Timur')


#code
n = int(input())
s = input()
fl = True
dp = [1]*n
for i in range(1,n):
    for j in range(i):
        if s[j] > s[i]:
            dp[i] = max(dp[i],1+dp[j])
for i in dp:
    if i>=3:
        fl = False
        break
if not fl:
    print("NO")
else:
    ans = "0"
    prev = s[0]
    for i in range(1,n):
        if s[i]<= prev:
            ans += "1"
        else:
            ans += "0"
        prev = s[i]
    print("YES")
    print(ans


n=int(input())
a=input()
ref={chr(i+97):[] for i in range(26)}
vis=[0]*n
high=a[0]
for i in range(1,n):
    if(a[i]>=high):
        high=a[i]
        continue
    ref[a[i]].append(i)
flag=0
mi=-1
for i in ref.keys():
    for j in ref[i]:
        if(mi<j):
            mi=j
            vis[j]=1
            continue
        flag=1
#print(ref)
if(flag==1):5
abcde

    print("NO")
else:
    print("YES")
    for i in vis:
        print(i,end="")
    print()


import sys

n = int(sys.stdin.readline())

s = list(sys.stdin.readline())

s0, s1 = ""
color = ""

works = True

for i in s:
    if s0 == "" or s0[-1] <= i:
        s0 += i
        color += 0
    elif s1 == "" or s1[-1] <= i:
        s0 += i
        color += 1
    else:
        works = False
        break

if works = True:
    print("YES")
    print(color)
else:
    print("NO")


"""
给你一个字符串s，你可以将每个字符任意涂红色或者黑色。然后对于任何相邻两个不同颜色的字符，你都可以将它们交换。问是否存在一种涂色方案，在经过有限次swap后使得整个字符串是升序排列。
"""
def colorable(s):
	mn = ""
	n = len(s)
	res = "0"

	for i in range(1, n):
		if s[i] < s[i-1]:
			if s[i] < mn:
				return False, res
			mn = s[i]
			res += "1"
		else:
			res += "0"
	return True, res

n = input()
s = input()

valid, res = colorable(s)
if valid:
	print("YES")
	print(res)
else:
	print("NO")


alpha_small_dict = {chr(i):i-97 for i in range(97, 97+26)} #辞書ver
n = int(input())
s = input()
data = [alpha_small_dict[x] for x in s]

G = [[] for _ in range(n)]
alpha_data = [[] for _ in range(26)]
for i,x in enumerate(data):
    for y in range(x+1,26):
        for j in alpha_data[y]:
            G[i].append(j)
            G[j].append(i)
    alpha_data[x].append(i)

color = [-1 for _ in range(n)]
t = True
for i in range(n):
    if color[i] == -1:
        que = [[-1,i]]
        color[i] = 0
        while que:
            pre,now = que.pop()
            for to in G[now]:
                if to == pre:continue
                if color[to] == color[now]:
                    print("NO")
                    exit()
                else:
                    color[to] = 1 - color[now]
                    que.append([now,to])
print("YES")
for x in color:
    print(x,end="")
print()


#include<iostream>
using namespace std;
    int main(){
        int n;
        cin>>n;
        string s="";
        for(i=1;i<=1000;i++){
            s=s+char(i);
        }
        cout<<s[n-1]<<endl;
        return 0;
   }


list a = map(str,range(1000))
b = ''.join(a)
print(b[int(input())])


s =''
n=int(input())
for i in range(388):
	s += str(i)
print s[n]


#include<stdio.h>
#include<string.h>
int main()
{
    char s[5000];
    int n;
    scanf("%d",&n);
    for (int i=1;i<=400;i++)
    sprintf(s,"%s%d",s,i);

    printf("%c",s[n]);
}


import math
c = map(int, raw_input.split())
a = c[0]
b = c[1]
if a == b:
    print 0
else:
    d = a ^ b
    e = math.log(d, 2) + 1
    print 2**int(e) - 1


l,r = map(int, raw_input().split())

def maxXor(low, high):
    highestPower = high.bit_length()-1
    if highestPower == 0:
        return 0
    if low < 2** highestPower:
        return (2**(highestPower+1))-1
    return maxXor(low >> 2, high >> 2)

print(maxXor(l,r))


l, r = map(int, input().split())
print(2**(a ^ b).bit_length() -1)


from math import *
#a,b = map(int,raw_input().split())
def f1(a,b):
    if a==b:
        return a^a
    minp,maxp = int(log(a,2)),int(log(b,2))
    #print(2**minp,2**maxp)
    if a<2**maxp<=b:
        return (2**maxp)^(2**maxp-1)
    else:
        if b==a+1:
            return a^b
       # if 2**minp==a:
        #    return 2**(minp-1)-1
        if maxp==minp:maxp+=1
        l = 2**minp
        ans = 0
        for i in range(minp-1,0,-1):
            if l+2**i<=b:
                l += 2**i
                ans=max(ans,l^(l-1))
        return ans

def f2(a,b):
    a2 = 0
    for i in range(a,b+1):
        for j in range(a,b+1):
            if i^j>a2:
                a2=i^j
    return a2

 a,b = map(int,raw_input().split())
 print(f1(a,b))


l,r = [int(x) for x in raw_input().split(" ")]

if l==r:
	return 0
else:
	print -1+(1<<(len('{0:b}'.format(l^r))))


n = int(raw_input())

ps = map(lambda x: int(x) - 1, raw_input().split())

shortest_paths = [None] * n
vertex_left = n

def dfs():
    global vertex_left
    visited = []
    queue = [(0, -1)]
    while queue:
        vtx, prev_steps = queue.pop(0)
        if vtx in visited:
            continue
        visited.append(vtx)
        shortest_paths[vtx] = prev_steps + 1
        vertex_left -= 1
        if vertex_left == 0:
            return
        nei = filter(lambda x: x != vtx and 0 <= x < n, [vtx - 1, vtx + 1, ps[vtx]])
        queue.extend((v, prev_steps + 1) for v in nei if v not in visited)

dfs()
print ' '.join(map(str, shortest_paths))


import sys
sp1 = ['1','4','7']
sp2 = ['1','2','3']
sp3 = ['3','6','9']
sp4 = ['7','0','9']
n = int(input())
s = input()
for i in sp1:
    if i in s:
        if 0 in s:
            print('YES')
            sys.exit(0)
        for j in sp2:
            if j in s:
                for k in sp3:
                    if k in s:
                        for t in sp4:
                            if t in s:
                                print('YES')
                                sys.exit(0)
else:
    print('NO')


import sys
read=lambda:sys.stdin.readline().rstrip()
readi=lambda:int(sys.stdin.readline())
writeln=lambda x:sys.stdout.write(str(x)+"\n")
write=lambda x:sys.stdout.write(x)
def solve(memory, N):
    if N == 1:
        return "YES"
    pad=[[-1]*7 for _ in range(8)]
    n = 1
    npos = [[-1,-1]]*10
    for i in range(2, 5):
        for j in range(2, 5):
            pad[i][j] = n
            npos[n] = (i, j)
            n += 1
    pad[5][3] = 0
    npos[0] = (5, 3)
    vecs = []
    sy, sx = npos[int(memory[0])]
    for i in range(N-1):
        y, x = npos[int(memory[i])]
        ny, nx = npos[int(memory[i+1])]
        vecs.append((ny-y, nx-x))

    for i in range(2, 5):
        for j in range(2, 5):
            if (sy, sx) == (i, j):
                continue
            y, x = i, j
            for t in range(N-1):
                dy,dx = vecs[t]
                y, x = y + dy, x + dx
                if pad[y][x] == -1:
                    break
            else:
                return "NO"

    if (sy, sx) == (5, 3):
        return "YES"

    y, x = 5, 3
    for t in range(N-1):
        dy,dx = vecs[t]
        y, x = y + dy, x + dx
        if pad[y][x] == -1:
            break
    else:
        return "NO"

    return "YES"

N=readi()
mem = read()
writeln(solve(mem, N))


raw_input()

digs = set()
for x in raw_input():
    digs.add(int(x))

# if 2 in digs and 0 in digs:
#     print 'NO'

xs = [(x - 1) % 3 for x in digs if x != 0]
ys = [(x - 1) / 3 for x in digs if x != 0]
minx, maxx = min(xs), max(xs)
miny, maxy = min(ys), max(ys)

if maxx - minx >= 2 and maxy - miny >= 2:
    print 'YES'
else:
    print 'NO'


def getpos(digit):
    digit = int(digit)
    if digit == 0:
        return (3,1)
    digit -= 1
    return (digit // 3, digit % 3)

def main():
    ndig = int(input())
    number = input().strip()
    assert ndig == len(number)
    rlo = clo = 4
    rhi = chi = 0
    for digit in number:
        row, col = getpos(digit)
        rlo = min(row, rlo)
        rhi = max(row, rhi)
        clo = min(col, clo)
        chi = max(col, chi)
    rdiff = rhi-rho
    if rdiff == 3:
        print('YES')
    elif rdiff < 2:
        print('NO')
    elif chi - clo < 2:
        print('NO')
    elif '0' in number:
        print('NO')
    else if '7' in number or '9' in number:
        print('YES')
    else:
        print('NO')

main()


alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet_h = alphabet.upper()
alpha = tuple(alphabet)
alpha_h = tuple(alphabet_h)
n = int(input())
s = str(input())
g = 0
i = 1

while i <= n-1:
  if s[i-1] in alpha:
    while s[i] in alpha_h:
     # print(s[i], i)
      g = g + 1
      i = i + 1
   #   print(i)
      if i>=n-1 or s[i] in alpha:
        break
  i = i + 1
i = n - 1
if s[n-1] in alpha_h and g > 0:
  while s[i] in alpha_h and i>=0:
    g = g - 1
    i = i - 1
if n = 1 and s[0] in alpha:
  g = 1

print(g)


 n=int(input())
s=str(input())
l=[0]
for i in range(len(s)):
    if ord(s[i])>=65 and ord(s[i])<=90:
        l.append(i)
ans=0
l.append(n)
for i in range(len(l)-1):
    ls=[]
    for j in range(l[i],l[i+1]):
        if s[j] not in ls and (ord(s[j])>=97 and ord(s[j])<=122):
            ls.append(s[j])
    ans=max(ans,len(ls))
    #print(ls)
print(ans)


n=int(input())
s=input()
a=set()
mx=0
for i in s:
	if(isupper(i)):
		s.clear()
	else:
		if(islower(i)):

            s.add(i)
            mx=max(mx,len(s))

print(mx)


n = int(input())
s = input()
l =[]
maxi = 0
for i in range(n):
    if s[i].isupper():
        maxi = max(maxi,len(set(l)))
        l=[]
    else:
        l.append(s[i])
maxi = max(maxi,len(set(l))
print(maxi)


n=int(input())
s=input()
a=set()
mx=0
for i in s:
	if(isupper(i)):
		s.clear()
	else:
		if(islower(i)):
		    s.add(i)
            mx=max(mx,len(s))

print(mx)


n = input()
l = len(n)
pmax = 9**(l-1)
k = "9"*(l-1)
if k == "":
    k = 1
for i in range(int(k),int(n)+1):
    p = 1
    for j in str(i):
        p *= int(j)
    if pmax < p:
        pmax = p

print(pmax)


n = int(input())
current_max = 0
fin = int('1' + '0' * (len(str(n)) - 1)) - 2
for i in range(n, fin, -1):
    product = 1
    for j in range(len(str(i))):
        product *= int(str(i)[j])
    if product > current_max:
        current_max = product
print(current_max)


// CPP Program to find the number in a
// range having maximum product of the
// digits

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

// Returns the product of digits of number x
int product(int x)
{
	int prod = 1;
	while (x) {
		prod *= (x % 10);
		x /= 10;
	}
	return prod;
}

// This function returns the number having
// maximum product of the digits
int findNumber(int l, int r)
{
	// Converting both integers to strings
	string a = to_string(l);
	string b = to_string(r);

	// Let the current answer be r
	int ans = r;
	for (int i = 0; i < b.size(); i++) {
		if (b[i] == '0')
			continue;

		// Stores the current number having
		// current digit one less than current
		// digit in b
		string curr = b;
		curr[i] = ((curr[i] - '0') - 1) + '0';

		// Replace all following digits with 9
		// to maximise the product
		for (int j = i + 1; j < curr.size(); j++)
			curr[j] = '9';

		// Convert string to number
		int num = 0;
		for (auto c : curr)
			num = num * 10 + (c - '0');

		// Check if it lies in range and its product
		// is greater than max product
		if (num >= l && product(ans) < product(num))
			ans = num;
	}

	return ans;
}

// Driver Code
int main()
{
	cin>>r;
	cout << findNumber(1, r) << endl;

	return 0;
}


 r=p=1
for d in map(int,input()[::-1]):r=max(d*r,(d-1)*p);p*=9
print(max(r,p//9))


import math

def powerMo(a,n,mo):
    ans = 1
    posi = a
    while n > 0:
        if n&1:
            ans *= posi
            ans %= mo
        n >>= 1
        posi = posi*posi%mo
    return ans

def modInv(a,mo):
    # return a's mod inv
    phi = mo - 1
    return(powerMo(a,phi-1,mo))

def combMo(n,a,mo):
    # Cna
    numer = 1
    for i in range(n-a+1,n+1):
        numer *= i
        numer %= mo
    denom = 1
    for i in range(1,a+1):
        denom *= i
        denom %= mo
    denomInv = modInv(denom,mo)
    ans = numer*denomInv%mo
    return ans

def f():
    mo = 998244353
    n, m = [int(s) for s in input().split()]
    if n==2:
        print(0)
        return
    c = combMo(m, n-1, mo)
    c *= (n-2)
    a = powerMo(2,n-3,mo)
    res = a*c%mo
    print(res)

f()


import sys;sys.setrecursionlimit(999999)
def f(L):
    n=len(L)
    if n==0: return 0
    if n==1: return 1
    diff=min(L)-1
    s=e=-1
    for i in range(n):
        L[i]-=diff
        if s==-1 and L[i]==1:
            s=i
            e=i
        if i>0 and e==i-1 and L[i]==1:
            e=i
    if s==0 and e==n-1:
        return str(bin(n)).count('1')
    R=9999
    cnt=e-s+1
    c2=cnt//2
    for a in range(c2+1):
        b=c2-a
        r=f(L[:s]+[2]*a)+f([2]*b+L[e+1:])
        R=min(r,R)
    return R+(cnt%2)
input();print(f(list(map(int,input().split()))))


import sys
input = sys.stdin.readline
def main():
  #  t = int(input())
    t = 1
    while(t):
  #  for _ in range(t):
        t -= 1

        MOD = 998244353
        fact = [1]*200005
        for i in range(1, 200005):
            fact[i] = i*fact[i-1]

        def fast_sq(a, b):
            ans = 1
            if(b == -1):
                b = MOD-2
            for i in range(60):
                if((1<<i)&b):
                    ans *= a
                a *= a
            return ans
        n, m = map(int, input().split())
        print(fact[m]*(n-2)*fast_sq(2, n-3)*fast_sq(fact[n-1]*fact[m-n+1], -1)%MOD)

main()


#!/usr/bin/env python3

import sys
from math import *
from collections import defaultdict
from queue import deque                # Queues
from heapq import heappush, heappop    # Priority Queues
M = 998244353
invcache = {}

# parse
lines = [line.strip() for line in sys.stdin.readlines()]
n, m = list(map(int, lines[0].split()))

# precompute
facts = [1]
pows = [1]
for i in range(1, m+1):
  facts += [facts[-1] * i % M]
  pows += [pows[-1] * 2 % M]

# mod inv
def gcdext(a, b):
  if a == 0:
    return b, 0, 1
  gcd, x, y = gcdext(b % a, a)
  return gcd, y - (b//a) * x, x

def modinv(a):
  if a in invcache:
    return invcache[a]

  g, x, y = gcdext(a, M)
  assert(g == 1)
  x %= M
  invcache[a] = x
  return x

def choose(a, b):
  if a < b or b < 0:
    return 0
  if b == 0:
    return 1
  if b == 1:
    return a
  return facts[a] * modinv(facts[b]) % M * modinv(facts[a-b]) % M

ret = 0
for k in range(n-1, m+1):
  ret = (ret + choose(k-1, 1) * choose(k-2, n-3) % M * pows[n-3]) % M
print(ret)


from math import *
from Queue import *
from sys import *
from datetime import *

nMax, hMax = map(int, raw_input().split())
table = [[0 for j in range(nMax+1)] for i in range(nMax+1)]
table[0][0] = 1
for i in range(1, nMax+1):
    table[i][i] = 2**(i-1)
for h in range(1, nMax+1):
    for n in range(h+1, nMax+1):
        for i in range(1,n+1):
            for j in range(h):
                table[n][h] += table[i-1][h-1]*table[n-i][j]
            for j in range(h):
                table[n][h] += table[i-1][j]*table[n-i][h-1]
            table[n][h] -= table[i-1][h-1]*table[n-i][h-1]
res = 0
for h in range(hMax, n+1):
    res += table[n][h]
print(res)


line = input().split()

n = int(line[0])
h = int(line[1])
import numpy as np
array_nodes_minheigt = np.zeros([36,36])
array_nodes_minheigt[0,0] = 1
for nodes in range(1,36):
    for minheight in range(0,nodes+1):
        for topnode in range(1, nodes + 1):
            left = topnode-1
            right = nodes - topnode
            array_nodes_minheigt[nodes,minheight] += array_nodes_minheigt[left,0] * array_nodes_minheigt[right,0] -             (array_nodes_minheigt[left,0]-array_nodes_minheigt[left, max(minheight-1,0)])*             (array_nodes_minheigt[right,0]-array_nodes_minheigt[right, max(minheight-1,0)])

print(int(array_nodes_minheigt[n,h]))


dp = {(0, 0) : 1}
def f(n, h):
    #print n, h
    if (n, h) in dp:
        return dp[(n, h)]

    if n == 0 or h == 0:
        return 0

    ans = 0
    for i in xrange(n): #0 .. n-1
        for j in xrange(h): #0 .. h-1
            #print n, n-i-1, i
            ans += f(n-i-1, j) * f(i, h-1)
            ans += f(n-i-1, h-1) * f(i, j)
        ans -= f(n-i-1, h-1) * f(i, h-1)

    #print n, h, ans
    dp[(n, h)] = ans
    return ans

n, h = map(int, raw_input().split())
print sum([ f(n, i) for i in xrange(h, n+1)])


import sys

n, h = map(int, sys.stdin.readline().split())

def f(n, h):
    if n == 0 and h == 0:
        return 1
    if n == 0 or h == 0:
        return 0
    r = 0
    for m in xrange(1, n+1):
        s1 = s2 = 0
        for i in xrange(0, h):
            s1 += f(n-m, i)
        for i in xrange(0, h-1):
            s2 += f(m-1, i)
        r += f(m-1, h-1)*s1+f(n-m, h-1)*s2
    return r

r = 0
for i in xrange(h, n+1):
    r += f(n, i)
print r