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

template <class T> using V = vector<T>;
template <class T> using VV = V<V<T>>;
template <class T> using VVV = V<VV<T>>;
template <class S, class T> using P = pair<S, T>;
template <class S, class T, class U> using TP = tuple<S, T, U>;

using ll = long long;
using ull = unsigned long long;
using dbl = double;
using str = string;
using vll = V<ll>;
using vvll = V<vll>;
using vvvll = V<vvll>;
using pl = P<ll, ll>;
using tl = TP<ll, ll, ll>;
using vpl = V<pl>;
using vvpl = V<vpl>;
using vtl = V<tl>;
using vvtl = V<vtl>;
using vs = V<str>;
using vvs = V<vs>;
using vd = V<dbl>;
using vvd = V<vd>;
using qll = queue<ll>;
using qpl = queue<pl>;
using stll = stack<ll>;
using stpl = stack<pl>;
using mapll = map<ll, ll>;
using setll = set<ll>;
using pqll = priority_queue<ll>;

#define int ll
#define fi first
#define se second
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define pob pop_back()
#define pf push_front
#define pof pop_front()
#define sz size()
#define bgn begin()
#define en end()
#define asn assign
#define emp empty()
#define fr front()
#define bk back()
#define clr clear()
#define ins insert
#define ers erase
#define res resize
#define tp top()
#define p_q priority_queue
#define inv inverse()

#define FOR(i,a,b) for(ll i=(a);i<=(ll)(b);i++)
#define rFOR(i,a,b) for(ll i=(b);i>=(ll)(a);i--)
#define REP(i,a) FOR((i),0,(ll)(a)-1)
#define REP0(i,a) FOR((i),0,(ll)(a))
#define REP1(i,a) FOR((i),1,(ll)(a))
#define rREP(i,a) rFOR((i),0,(ll)(a)-1)
#define rREP0(i,a) rFOR((i),0,(ll)(a))
#define rREP1(i,a) rFOR((i),1,(ll)(a))
#define ROR(v,i) for(auto &(i):(v))
#define IOTA(a,n) iota((a).bgn,(a).en,(n))
#define SORT(a) sort((a).bgn,(a).en)
#define rSORT(a) sort((a).rbegin(),(a).rend())
#define UNIQUE(a) (a).erase(unique((a).bgn,(a).en),(a).en)
#define PREVP(a) prev_permutation((a).bgn,(a).en)
#define NEXTP(a) next_permutation((a).bgn,(a).en)
#define BINS(a,b) binary_search((a).bgn,(a).en,(b))
#define LOWB(a,b) (lower_bound((a).bgn,(a).en,(b))-(a).bgn)
#define UPB(a,b) (upper_bound((a).bgn,(a).en,(b))-(a).bgn)
#define CNT(a,b) count((a).bgn,(a).en,b)
#define SUM(a) accumulate((a).bgn,(a).en,0)
#define REV(a) reverse((a).bgn,(a).en)
#define REGS(a,b) regex_search((a),regex(b))
#define REGM(a,b) regex_match((a),regex(b))
#define yn(a) cout <<((a)?"yes":"no")<<"\n";
#define Yn(a) cout <<((a)?"Yes":"No")<<"\n";
#define YN(a) cout <<((a)?"YES":"NO")<<"\n";
#define imp(a) cout <<((a)?"possible":"impossible")<<"\n";
#define Imp(a) cout <<((a)?"Possible":"Impossible")<<"\n";
#define IMP(a) cout <<((a)?"POSSIBLE":"IMPOSSIBLE")<<"\n";
#define fs(a) cout <<((a)?"second":"first")<<"\n";
#define Fs(a) cout <<((a)?"Second":"First")<<"\n";
#define FS(a) cout <<((a)?"SECOND":"FIRST")<<"\n";
#define sak cout <<"\n";
#define sas cout <<" ";
#define sat cout <<"\t";
#define dbg(a) cerr <<(#a)<<": "<<(a)<<"\n";
#define dbgs(...) dal(#__VA_ARGS__);dal(__VA_ARGS__);
#define c2l(a) ((ll)(a-48))
#define a2l(a) ((ll)(a-97))
#define A2l(a) ((ll)(a-65))
#define l2c(a) ((char)(a+48))
#define l2a(a) ((char)(a+97))
#define l2A(a) ((char)(a+65))
#define DigN2(a) ((llabs(a)==0)?(1):((ll)(log2(double(llabs(a))))+1))
#define DigN10(a) ((llabs(a)==0)?(1):((ll)(log10(double(llabs(a))))+1))
#define Dig2(a,b) (((a)>>(b))&1)
#define Dig10(a,b) (ll)(((a)/((ll)(pow(10.0,(double)(b)))))%10)
#define Pow2(a) ((ll)(1)<<(a))
#define Pow10(a) ((ll)(pow(10.0,double(a))))
#define LSB(a) ((a)&(-(a)))
#define vin(v) ROR((v),(i)){cin >>(i);};
#define vllin(v,N) vll (v)((N));vin(v);
#define vllin2(a,b,N) vll (a)(N),(b)(N);REP(i,N){cin>>(a)[i]>>(b)[i];};
#define vsin(v,N) vs (v)((N));vin(v);
#define rdn(a,b) ((a)/(b))
#define rou(a,b) ((((double(a)/double(b))-((a)/(b)))<0.5)?((a)/(b)):(((a)/(b))+1))
#define rup(a,b) ((((a)%(b))==0)?((a)/(b)):(((a)/(b))+1))
#define min(...) Min(__VA_ARGS__)
#define max(...) Max(__VA_ARGS__)
#define emin(a, ...) ((a)=Min((a),__VA_ARGS__))
#define emax(a, ...) ((a)=Max((a),__VA_ARGS__))
#define egcd(a, ...) ((a)=gcd((a),__VA_ARGS__))
#define elcm(a, ...) ((a)=lcm((a),__VA_ARGS__))
#define powll(a,b) (ll)(pow((double)(a),(double)(b)))
#define Triangle(x1,y1,x2,y2,x3,y3) (((x1)-(x2))*((y1)-(y3))-((x1)-(x3))*((y1)-(y2)))

#define svll SumV<ll>
#define svvll SumV2<ll>

#define li(...) ll __VA_ARGS__;Input(__VA_ARGS__);
#define si(...) str __VA_ARGS__;Input(__VA_ARGS__);
#define vli(size, ...) vll __VA_ARGS__;vInput(size,__VA_ARGS__);
#define vsi(size, ...) vs __VA_ARGS__;vInput(size,__VA_ARGS__);

const ll MOD = 1e9 + 7;
//const ll MOD = 998244353;
//const ll MOD = 924844033;
//const ll MOD = 9007199254740881;
const ll INF = 1LL << 60;//1.15e18
const double PI = acos(-1.0);
const vll DX = { 0,-1,0,1,0,-1,1,1,-1 };
const vll DY = { 0,0,-1,0,1,-1,-1,1,1 };
const str alp = "abcdefghijklmnopqrstuvwxyz";
const str ALP = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

void Input() {}
template <class Var, class... Args> void Input(Var& var, Args&... args) {
    cin >> var;
    Input(args...);
}

void vInit(ll size) {}
template <class T, class... Args> void vInit(ll size, V<T>& v, Args&... args) {
    v.res(size);
    vInit(size, args...);
}
void vInputNum(ll num) {}
template <class T, class... Args> void vInputNum(ll num, V<T>& v, Args&... args) {
    cin >> v[num];
    vInputNum(num, args...);
}
void vInput(ll size) {}
template <class... Args> void vInput(ll size, Args&... args) {
    vInit(size, args...);
    REP(i, size) vInputNum(i, args...);
}

template <class S, class T> ostream &operator<<(ostream &out, const P<S, T> &p) {
    return out << "[" << p.fi << ", " << p.se << "]";
}

template <class T> ostream &operator<<(ostream &out, V<T> &v) {
    if (v.emp) return out << "{}";
    else {
        auto itr = v.bgn;
        out << "{" << *itr;
        itr++;
        while (itr != v.en) {
            out << ", " << *itr;
            itr++;
        }
        out << "}";
        return out;
    }
}

template <class S, class T> ostream &operator<<(ostream &out, const map<S, T> &m) {
    if (m.emp) return out << "<[]>";
    else {
        auto itr = m.bgn;
        out << "< [" << (itr->fi) << ": " << (itr->se);
        itr++;
        while (itr != m.en) {
            out << "], [" << (itr->fi) << ": " << (itr->se);
            itr++;
        }
        out << "] >";
        return out;
    }
}

template <class T> ostream &operator<<(ostream &out, const set<T> &s) {
    if (s.emp) return out << "<>";
    else {
        auto itr = s.bgn;
        out << "<" << *itr;
        itr++;
        while (itr != s.en) {
            out << ", " << *itr;
            itr++;
        }
        out << ">";
        return out;
    }
}

void say() {}
template <class T> void say(T t) { cout << t; }
template <class Head, class... Body> void say(Head head, Body... body) {
    cout << head << " ";
    say(body...);
}
void sal() { cout << "\n"; }
template <class... Args> void sal(Args... args) {
    say(args...);
    cout << "\n";
}

void day() {}
template <class T> void day(T t) { cerr << t; }
template <class Head, class... Body> void day(Head head, Body... body) {
    cerr << head << " ";
    day(body...);
}
void dal() { cerr << "\n"; }
template <class... Args> void dal(Args... args) {
    day(args...);
    cerr << "\n";
}

void salv() {}
template <class T> void salv(V<T> v) {
    if (v.emp) sal();
    else {
        auto itr = v.bgn;
        say(*itr);
        itr++;
        while (itr != v.en) {
            sas;
            say(*itr);
            itr++;
        }
        sak;
    }
}
template <class T, class... Args> void salv(V<T> v, Args... args) {
    salv(v);
    salv(args...);
}

void salv2() {}
template <class T> void salv2(V<V<T>> v) {
    if (v.emp) sal();
    else {
        ROR(v, i) salv(i);
    }
}
template <class T, class... Args> void salv2(V<V<T>> v, Args... args) {
    salv2(v);
    salv2(args...);
}

template <class Monoid> struct Action {
public:
    Monoid I;
    function<Monoid(Monoid, Monoid)> A;
    Action(Monoid I, function<Monoid(Monoid, Monoid)> A) : I(I), A(A) {}
    Monoid operator()() { return I; }
    Monoid operator()(Monoid x) { return x; }
    Monoid operator()(Monoid l, Monoid r) { return A(l, r); }
    template <class... Args> Monoid operator()(Monoid x, Args... args) {
        Monoid tmp = operator()(args...);
        return A(x, tmp);
    }
};

template <class T> Action<T> ADD = Action<T>(0, [](T l, T r) { return l + r; });
template <> Action<str> ADD<str> = Action<str>("", [](str l, str r) { return l + r; });
template <class T1, class T2> Action<P<T1, T2>> ADD<P<T1, T2>> = Action<P<T1, T2>>(mp(ADD<T1>.I, ADD<T2>.I), [](P<T1, T2> l, P<T1, T2> r) { return mp(l.fi + r.fi, l.se + r.se); });

template <class T> Action<T> MUL = Action<T>(1, [](T l, T r) { return l * r; });
template <class T> Action<T> OR = Action<T>(0, [](T l, T r) { return l | r; });
template <class T> Action<T> XOR = Action<T>(0, [](T l, T r) { return l ^ r; });

template <class T> Action<T> AND = Action<T>(((ll)(1) << 63) - 1, [](T l, T r) { return l & r; });
template <> Action<bool> AND<bool> = Action<bool>(true, [](bool l, bool r) { return l & r; });
template <> Action<ull> AND<ull> = Action<ull>(((ull)(1) << 63) - 1, [](ull l, ull r) { return l & r; });

template <class T> Action<T> MIN = Action<T>(INF, [](T l, T r) { return (l < r) ? l : r; });
template <class T> Action<T> MAX = Action<T>(-INF, [](T l, T r) { return (l > r) ? l : r; });

template <class T> Action<T> GCD = Action<T>(0, [](T l, T r) { if (l < r) { l ^= r; r ^= l; l ^= r; } return (r ? GCD<T>(r, l%r) : l); });
template <class T> Action<T> LCM = Action<T>(1, [](T l, T r) { return (l * r) / GCD<T>(l, r); });

template <class Head> Head Min(Head head) { return head; }
template <class Head, class... Body> Head Min(Head head, Body... body) {
    auto tmp = Min(body...);
    return (head < tmp) ? head : tmp;
}

template <class Head> Head Max(Head head) { return head; }
template <class Head, class... Body> auto Max(Head head, Body... body) {
    auto tmp = Max(body...);
    return (head > tmp) ? head : tmp;
}

ll gcd(ll a, ll b) { if (a < b) { a ^= b; b ^= a; a ^= b; } return b ? gcd(b, a%b) : a; }
ll lcm(ll a, ll b) { return a / gcd(a, b)*b; }

ll gcd(ll head) { return head; }
template <class... Body> ll gcd(ll head, Body... body) {
    return gcd(head, gcd(body...));
}

ll lcm(ll head) { return head; }
template <class... Body> ll lcm(ll head, Body... body) {
    return lcm(head, lcm(body...));
}

ll Bset(ll a, ll b, ll c) {
    if (c) a |= b;
    else a &= ~b;
    return a;
}

struct UFT {

public:
    ll tsize;
    ll mode;
    vll par;
    vll rank;
    UFT() {}
    UFT(const UFT &uft) {}
    UFT(ll tsizeget, ll modeget = 0){
        tsize = tsizeget;
        mode = modeget;
        par.asn(tsize, -1);
        if (!mode) rank.res(tsize, 0);
    }
    ll root(ll x) {
        return par[x] < 0 ? x : par[x] = root(par[x]);
    }
    bool isRoot(ll x) {
        return x == root(x);
    }
    bool same(ll x, ll y) {
        return root(x) == root(y);
    }
    void merge(ll x, ll y) {
        x = root(x);
        y = root(y);
        if (x == y) return;
        if (mode) {
            par[x] += par[y];
            par[y] = x;
        }
        else {
            if (rank[x] < rank[y]) {
                par[y] += par[x];
                par[x] = y;
            }
            else {
                par[x] += par[y];
                par[y] = x;
                if (rank[x] == rank[y]) rank[x]++;
            }
        }
    }
    ll size(ll x) {
        return -par[root(x)];
    }
};

struct pUFT {

public:

    ll tsize;
    ll now;
    vll par;
    vll rank;
    vll mtime;
    vvll sizepi;
    vvll sizepv;

    pUFT(){}
    pUFT(const pUFT &puft) {}

    pUFT(ll tsizeget) {
        tsize = tsizeget;
        now = 0;
        par.asn(tsize, -1);
        rank.asn(tsize, 0);
        mtime.asn(tsize, INF);
        sizepi.asn(tsize, { 0 });
        sizepv.asn(tsize, { 1 });
    }
    ll root(ll x, ll t) {
        return (mtime[x] > t) ? x : root(par[x], t);
    }
    bool same(ll x, ll y, ll t) {
        return root(x, t) == root(y, t);
    }
    ll merge(ll x, ll y) {
        now++;
        x = root(x, now);
        y = root(y, now);
        if (x != y) {
            if (rank[x] < rank[y]) {
                par[y] += par[x];
                sizepi[y].pb(now);
                sizepv[y].pb(-par[y]);
                par[x] = y;
                mtime[x] = now;
            }
            else {
                par[x] += par[y];
                sizepi[x].pb(now);
                sizepv[x].pb(-par[x]);
                par[y] = x;
                mtime[y] = now;
                if (rank[x] == rank[y]) rank[x]++;
            }
        }
        return now;
    }
    ll size(ll x, ll t) {
        x = root(x, t);
        return sizepv[x][UPB(sizepi[x], t) - 1];
    }

};

struct wUFT {
public:
    ll tsize;
    ll mode;
    vll par;
    vll rank;
    vll dweight;
    wUFT() {}
    wUFT(const wUFT &wuft) {}
    wUFT(ll tsizeget, ll modeget = 0) {
        tsize = tsizeget;
        mode = modeget;
        par.asn(tsize, -1);
        if (!mode) rank.res(tsize, 0);
        dweight.asn(tsize, 0);
    }
    ll root(ll x) {
        if (par[x] < 0) return x;
        else {
            ll r = root(par[x]);
            dweight[x] += dweight[par[x]];
            return par[x] = r;
        }
    }
    ll weight(ll x) {
        root(x);
        return dweight[x];
    }
    ll diff(ll x, ll y) {
        return weight(y) - weight(x);
    }
    bool isRoot(ll x) {
        return x == root(x);
    }
    bool same(ll x, ll y) {
        return root(x) == root(y);
    }
    void merge(ll x, ll y, ll w) {
        w += weight(x);
        w -= weight(y);
        x = root(x);
        y = root(y);
        if (x == y) return;
        if (mode) {
            par[x] += par[y];
            par[y] = x;
        }
        else {
            if (rank[x] < rank[y]) {
                par[y] += par[x];
                par[x] = y;
                dweight[x] = -w;
            }
            else {
                par[x] += par[y];
                par[y] = x;
                if (rank[x] == rank[y]) rank[x]++;
                dweight[y] = w;
            }
        }
    }
    ll size(ll x) {
        return -par[root(x)];
    }
};

template <typename valtype> class SegT {

public:

    ll size;
    vector<valtype> v;

    valtype initv;
    function<valtype(valtype x, valtype y)> calc;

    SegT() {}
    SegT(const SegT &segt) {}

    SegT(ll sizeget, ll modeget = 0) {
        sizeset(sizeget);
        modeset(modeget);
        init();
    }
    SegT(vector<valtype> cpyvec, ll modeget = 0) {
        sizeset(cpyvec.sz);
        modeset(modeget);
        init();
        copy(cpyvec);
    }
    SegT(ll sizeget, valtype initvget, function<valtype(valtype x, valtype y)> calcget) {
        sizeset(sizeget);
        initv = initvget;
        calc = calcget;
        init();
    }
    SegT(vector<valtype> cpyvec, valtype initvget, function<valtype(valtype x, valtype y)> calcget) {
        sizeset(cpyvec.sz);
        initv = initvget;
        calc = calcget;
        init();
        copy(cpyvec);
    }
    void sizeset(ll rsize) {
        size = DigN2(rsize);
        if (rsize == Pow2(size - 1)) size--;
        return;
    }
    void modeset(ll mode) {
        switch (mode) {
        case 0:
            initv = 0;
            calc = [](valtype x, valtype y) {return x + y; };
            break;
        case 1:
            initv = INF;
            calc = [](valtype x, valtype y) {return min(x, y); };
            break;
        case 2:
            initv = -INF;
            calc = [](valtype x, valtype y) {return max(x, y); };
            break;
        }
        return;
    }
    void init() {
        v.asn(Pow2(size + 1) - 1, initv);
    }
    void copy(vector<valtype> cpyvec) {
        REP(i, min(cpyvec.sz, Pow2(size))) set(i, cpyvec[i]);
    }
    ll i2v(ll i) const{
        if (i < 0 || i >= Pow2(size)) return -1;
        return Pow2(size) + i - 1;
    }
    ll top(ll i) const{
        if (i == 0) return -1;
        return (i - 1) / 2;
    }
    pl bot(ll i) const{
        if (i + 1 >= Pow2(size)) return mp(-1, -1);
        return mp(2 * i + 1, 2 * i + 2);
    }
    void set(ll i, valtype x) {
        i = i2v(i);
        v[i] = x;
        while (i > 0) {
            i = top(i);
            v[i] = calc(v[bot(i).fi], v[bot(i).se]);
        }
        return;
    }
    void add(ll i, valtype x) {
        set(i, v[i2v(i)] + x);
        return;
    }
    valtype operator[](const ll &i) const {
        return v[i2v(i)];
    }
//  valtype que(ll a = 0, ll b = Pow2(size) - 1) {
    valtype que(ll a, ll b) {
        if (a == b) return v[i2v(a)];
        if (a > b) return initv;//swap(a, b);
        valtype ans = initv;
        ll ai = i2v(a);
        ll bi = i2v(b);
        FOR(i, 1, size + 1) {
            if (a > b) break;
            if (a%Pow2(i)) {
                ans = calc(ans, v[ai]);
                a += Pow2(i - 1);
                ai = top(ai) + 1;
            }
            else {
                ai = top(ai);
            }
            if (a > b) break;
            if ((b + 1) % Pow2(i)) {
                ans = calc(ans, v[bi]);
                b -= Pow2(i - 1);
                bi = top(bi) - 1;
            }
            else {
                bi = top(bi);
            }
            if (a > b) break;
        }
        return ans;
    }
    valtype que(ll b) {
        return que(0, b);
    }
    valtype que() {
        return que(0, Pow2(size) - 1);
    }

};

template <typename lentype> class Graph {

public:

    ll size;
    ll mode;
    ll mapmode;
    lentype zlen;
    lentype ilen;
    vector<map<ll, ll>> v2n;
    vvll n2v;
    vector<vector<lentype>> Edge;
    vector<pair<lentype, ll>> Primresult;

    Graph() {}
    Graph(const Graph &graph) {}

    Graph(ll sizeget = 0, ll mapmodeget = 0, ll modeget = 0, lentype zlenget = 0, lentype ilenget = INF) {
        size = sizeget;
        mapmode = mapmodeget;
        mode = modeget;
        zlen = zlenget;
        ilen = ilenget;
        init();
    }
    void init() {
        Edge.res(size);
        v2n.res(size);
        n2v.res(size);
        Primresult.asn(size, mp(ilen, -1));
    }
    lentype lenplus(lentype l, lentype r) {
        return l + r;
    }
    lentype lenequal(lentype l, lentype r) {
        return l == r;
    }
    lentype lenlcr(lentype l, lentype r) {
        return l < r;
    }
    ll addV(ll vs) {
        size += vs;
        init();
        return size;
    }
    void caddE(ll x, ll y, lentype c) {
        if (mapmode) v2n[x][y] = Edge[x].sz;
        Edge[x].pb(c);
        n2v[x].pb(y);
    }
    void csetE(ll x, ll y, lentype c) {
        if (mapmode) Edge[x][v2n[x][y]] = c;
    }
    void cersE(ll x, ll y) {
        if (mapmode) {
            ll n = v2n[x][y];
            Edge[x][n] = ilen;
            n2v[x][n] = -1;
            v2n[x].ers(y);
        }
    }
    void addE(ll x, ll y, lentype c) {
        caddE(x, y, c);
        if (!mode) caddE(y, x, c);
    }
    void setE(ll x, ll y, lentype c) {
        csetE(x, y, c);
        if (!mode) csetE(y, x, c);
    }
    void ersE(ll x, ll y, lentype c) {
        cersE(x, y, c);
        if (!mode) cersE(y, x, c);
    }
    lentype getE(ll x, ll y) {
        if (mapmode) {
            if (v2n[x].count(y)) {
                return Edge[x][v2n[x][y]];
            }
        }
        return ilen;
    }
    ll getVsz(ll x) {
        return Edge[x].sz;
    }
    pair<lentype, ll> getV(ll x, ll n) {
        if (n >= getVsz(x)) return mp(ilen, -1);
        return mp(Edge[x][n], n2v[x][n]);
    }

    vector<pair<lentype, vll>> Dijk(ll x) {
        vector<pair<lentype, vll>> result(size);
        REP(i, size) {
            result[i].fi = ilen;
            result[i].se = { -1 };
        }
        vll stat(size, 0);
        pair<lentype, ll> now;
        pair<lentype, ll> nowlv;
        SegT<pair<lentype, ll>> Q(size, mp(ilen, -1), [](pair<lentype, ll> l, pair<lentype, ll> r) {
            if (l.se == -1) return r;
            if (r.se == -1) return l;
            return l.fi < r.fi ? l : r;
        });
        Q.set(x, mp(zlen, x));
        result[x].fi = zlen;
        result[x].se = { -1 };
        while (Q.que(0, size - 1).se != -1) {
            now = Q.que(0, size - 1);
            Q.set(now.se, mp(ilen, -1));
            stat[now.se] = 1;
            REP(i, getVsz(now.se)) {
                nowlv = getV(now.se, i);
                if (stat[nowlv.se]) continue;
                if (Q[nowlv.se].se == -1) {
                    result[nowlv.se].fi = lenplus(result[now.se].fi, nowlv.fi);
                    result[nowlv.se].se = { now.se };
                    Q.set(nowlv.se, mp(result[nowlv.se].fi, nowlv.se));
                }
                else {
                    if (lenlcr(lenplus(result[now.se].fi, nowlv.fi), result[nowlv.se].fi)) {
                        result[nowlv.se].fi = lenplus(result[now.se].fi, nowlv.fi);
                        result[nowlv.se].se = { now.se };
                        Q.set(nowlv.se, mp(result[nowlv.se].fi, nowlv.se));
                    }
                    else if (lenequal(lenplus(result[now.se].fi, nowlv.fi), result[nowlv.se].fi)) {
                        result[nowlv.se].se.pb(now.se);
                    }
                }
            }
        }
        return result;
    }

    lentype Prim(ll x = 0) {
        lentype ans = zlen;
        vll stat(size, 0);
        pair<lentype, ll> now;
        pair<lentype, ll> nowlv;
        SegT<pair<lentype, ll>> Q(size, mp(ilen, -1), [](pair<lentype, ll> l, pair<lentype, ll> r) {
            if (l.se == -1) return r;
            if (r.se == -1) return l;
            return l.fi < r.fi ? l : r;
        });
        Q.set(x, mp(zlen, x));
        Primresult[x] = mp(zlen, -1);
        while (Q.que(0, size - 1).se != -1) {
            now = Q.que(0, size - 1);
            Q.set(now.se, mp(ilen, -1));
            stat[now.se] = 1;
            ans = lenplus(ans, Primresult[now.se].fi);
            REP(i, getVsz(now.se)) {
                nowlv = getV(now.se, i);
                if (stat[nowlv.se]) continue;
                if (Q[nowlv.se].se == -1) {
                    Primresult[nowlv.se] = mp(nowlv.fi, now.se);
                    Q.set(nowlv.se, mp(Primresult[nowlv.se].fi, nowlv.se));
                }
                else {
                    if (lenlcr(nowlv.fi, Primresult[nowlv.se].fi)) {
                        Primresult[nowlv.se] = mp(nowlv.fi, now.se);
                        Q.set(nowlv.se, mp(Primresult[nowlv.se].fi, nowlv.se));
                    }
                }
            }
        }
        return ans;
    }

};

/*template <class Type> class DP {

public:

    vector<Type> v;
    Type initv;
    vll size, block;

    DP() {}
    DP(const DP &dp) {}

    template<class... Args> DP(Args... args) {
        block.asn(1, 1);
        Initialize(args...);
    }

    void Initialize(Type initv_) {
        initv = initv_;
        v.asn(block.bk, initv);
    }
    template<class... Args> void Initialize(ll val, Args... args) {
        size.pb(val);
        block.pb(block.bk*val);
        Initialize(args...);
    }

};*/

pl Bezout(ll a, ll b) {
    if (b != 0) {
        pl xy;
        xy = Bezout(b, a%b);
        return mp(xy.se, xy.fi - ((a / b)*xy.se));
    }
    else {
        return mp(1, 0);
    }
}
pl Bez(ll a, ll b, ll c) {
    pl xy;
    ll x, y, z, gc;
    xy = Bezout(a, b);
    gc = gcd(a, b);
    if (c%gc != 0) return mp(-1, -1);
    x = xy.fi*(c / gc); y = xy.se*(c / gc);
    if (x < 0) z = rup(-x, (b / gc));
    if (x >= 0) z = -x / (b / gc);
    x += z * (b / gc);
    y -= z * (a / gc);
    return mp(x, y);
}

ll DigS10(ll n) {
    ll ans = 0;
    while(1) {
        ans += n % 10;
        n /= 10;
        if (!n) break;
    }
    return ans;
}

ll isP(ll n) {
    if (n <= 1) return 0;
    FOR(i, 2, (ll)sqrt(n) + 1) {
        if (n%i == 0) return 0;
    }
    return 1;
}

ll Tot(ll n) {
    if (n <= 0) return 0;
    ll ans = n, x = 2;
    while (x*x <= n) {
        if (n%x == 0) {
            ans -= ans / x;
            while (n%x == 0) n /= x;
        }
        x++;
    }
    if (n > 1) ans -= ans / n;
    return ans;
}

template <class T> struct Sum {
public:
    V<T> v, s;
    ll size;
    Action<T> Add;
    Sum(V<T> v, Action<T> Add = ADD<T>) : v(v), size(v.sz), Add(Add) { Init(); Calc(); }
    void Init() {
        s.asn(size + 1, Add.I);
    }
    void Calc() {
        REP(i, size) s[i + 1] = Add(s[i], v[i]);

    }
    T operator()(ll x) {
        return operator()(0, x);
    }
    T operator()(ll l, ll r) {
        if (l < 0) l = 0;
        if (r >= size) r = size - 1;
        if (l > r) return Add.I;
        return s[r + 1] - s[l];//for ADD
    }
};
using sumll = Sum<ll>;

template <class T> struct Sum2 {
public:
    V<V<T>> v, s;
    ll RowSize, ColumnSize;
    Action<T> Add;
    Sum2(V<V<T>> v, Action<T> Add = ADD<T>) : v(v), RowSize(v.sz), ColumnSize(v.sz ? v[0].sz : 0), Add(Add) { Init(); Calc(); }
    void Init() {
        s.asn(RowSize + 1, V<T>(ColumnSize, Add.I));
    }
    void Calc() {
        REP1(r, RowSize) {
            REP1(c, ColumnSize) {
                s[r][c] = v[r - 1][c - 1] + operator()(r, c - 1) + operator()(r - 1, c) - operator()(r - 1, c - 1);
            }
        }
    }
    T operator()(ll r, ll c) {
        return operator()(0, 0, r, c);
    }
    T operator()(ll r1, ll c1, ll r2, ll c2) {
        if (r1 < 0) r1 = 0;
        if (c1 < 0) c1 = 0;
        if (r2 >= RowSize) r2 = RowSize - 1;
        if (c2 >= ColumnSize) c2 = ColumnSize - 1;
        if (r1 > r2) return Add.I;
        if (c1 > c2) return Add.I;
        return s[r2 + 1][c2 + 1] - s[r2 + 1][c1] - s[r1][c2 + 1] + s[r1][c1];
    }
};
using sum2ll = Sum2<ll>;

template <class T> struct Point2 {
public:
    V<V<T>> v;
    ll h, w;
    Point2() : h(0), w(0) {}
    Point2(ll h, ll w) : h(h), w(w) { asn(h, w); }
    Point2(ll h, ll w, T val) : h(h), w(w) { asn(h, w, val); }
    void assign(ll h, ll w) { v.asn(h, V<T>(w)); }
    void assign(ll h, ll w, ll val) { v.asn(h, V<T>(w, val)); }
    T& operator()(ll h, ll w) { return v[h][w]; }
    T& operator()(pl p) { return v[p.fi][p.se]; }
};
template <class T> using P2 = Point2<T>;

template <ll Mod> struct Modll {
public:
    ll v;
    Modll() : v(0) {}
    Modll(ll _v) { set(_v % Mod + Mod); }
    Modll& set(ll _v) {
        v = (_v < Mod) ? _v : (_v - Mod);
        return *this;
    }
    Modll pow(ll n) const {
        Modll x = *this, ans = 1;
        while (n) {
            if (n & 1) ans *= x;
            x *= x;
            n >>= 1;
        }
        return ans;
    }
    Modll inverse() const { return (*this).pow(Mod - 2); }
    Modll operator+(const Modll& m) const { return Modll().set(v + m.v); }
    Modll operator-(const Modll& m) const { return Modll().set(Mod + v - m.v); }
    Modll operator*(const Modll& m) const { return Modll().set((ull(v) * m.v) % Mod); }
    Modll operator/(const Modll& m) const { return *this * m.inv; }
    Modll& operator+=(const Modll& m) { return *this = *this + m; }
    Modll& operator-=(const Modll& m) { return *this = *this - m; }
    Modll& operator*=(const Modll& m) { return *this = *this * m; }
    Modll& operator/=(const Modll& m) { return *this = *this / m; }
    Modll operator-() const { return Modll(0) - *this; }
    explicit operator bool() const { return v != 0; }
    friend ostream& operator<<(ostream& out, const Modll& m) { return out << m.v; }
};
using mll = Modll<MOD>;
using vmll = V<mll>;
using vvmll = V<vmll>;
using vvvmll = V<vvmll>;

template <class T> T vmin(V<T> v) {
    T tmp = MIN<T>.I;
    ROR(v, i) emin(tmp, i);
    return tmp;
}
template <class T, class... Args> T vmin(V<T> v, Args... args) {
    T tmp = vmin(args...);
    return min(vmin(v), tmp);
}

template <class T> T vmax(V<T> v) {
    T tmp = MAX<T>.I;
    ROR(v, i) emax(tmp, i);
    return tmp;
}
template <class T, class... Args> T vmax(V<T> v, Args... args) {
    T tmp = vmax(args...);
    return max(vmax(v), tmp);
}

template <class T> T vgcd(V<T> v) {
    T tmp = GCD<T>.I;
    ROR(v, i) egcd(tmp, i);
    return tmp;
}
template <class T, class... Args> T vgcd(V<T> v, Args... args) {
    T tmp = vgcd(args...);
    return gcd(vgcd(v), tmp);
}

template <class T> T vlcm(V<T> v) {
    T tmp = LCM<T>.I;
    ROR(v, i) elcm(tmp, i);
    return tmp;
}
template <class T, class... Args> T vlcm(V<T> v, Args... args) {
    T tmp = vlcm(args...);
    return lcm(vlcm(v), tmp);
}

vmll MFactMemo(2, 1);
vmll MIFactMemo(2, 1);

mll mFact(ll n) {
    if (MFactMemo.sz <= n) {
        ll oldsize = MFactMemo.sz;
        MFactMemo.res(n + 1, 1);
        FOR(i, oldsize, n) MFactMemo[i] = MFactMemo[i - 1] * i;
    }
    return MFactMemo[n];
}
mll miFact(ll n) {
    if (MIFactMemo.sz <= n) {
        ll oldsize = MIFactMemo.sz;
        MIFactMemo.res(n + 1, 1);
        MIFactMemo.bk = mFact(n).inv;
        rFOR(i, oldsize + 1, n) MIFactMemo[i - 1] = MIFactMemo[i] * i;
    }
    return MIFactMemo[n];
}
mll mComb(ll n, ll k) {
    if (n < 0 || k < 0 || n < k) return 0;
    return mFact(n) * miFact(k) * miFact(n - k);
}

ll LIS(vll v, ll m = 0) {

    if (v.sz > 0) {
        ll ans = 0;
        vll dp(v.sz, INF);
        FOR(i, 0, v.sz - 1) {
            dp[m ? UPB(dp, v[i]) : LOWB(dp, v[i])] = v[i];
        }
        FOR(i, 0, v.sz - 1) {
            if (dp[i] == INF) break;
            ans++;
        }
        return ans;
    }
    else {
        return 0;
    }

}

void PCmprs(vll& v) {
    if (v.sz == 0) return;
    vll vv(v);
    IOTA(vv, 0);
    sort(vv.bgn, vv.en, [&](ll v1, ll v2) {return v[v1] < v[v2]; });
    IOTA(v, 0);
    sort(v.bgn, v.en, [&](ll v1, ll v2) {return vv[v1] < vv[v2]; });
    return;
}

ll BblCnt(vll v) {
    PCmprs(v);
    SegT<ll> b(v.sz, 0);
    ll ans = 0;
    REP(i, v.sz) {
        ans += (i - b.que(0, v[i]));
        b.add(v[i], 1);
    }
    return ans;
}

ll Bsrch(function<bool(ll x)> f, ll mi, ll ma) {
    ll ng = mi - 1, ok = ma, mid;
    while (ok - ng > 1) {
        mid = (ng + ok) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template<class T> V<V<T>> MultiMatrix(V<V<T>> A, V<V<T>> B, Action<T> Mul = MUL<T>, Action<T> Add = ADD<T>) {
    V<V<T>> ans;
    ll ii = A.sz;
    if (!ii) return ans;
    ll jj = A[0].sz;
    if (!jj) return ans;
    ll jj2 = B.sz;
    if (!jj2) return ans;
    if (jj != jj2) return ans;
    ll kk = B[0].sz;
    if (!kk) return ans;
    ans.asn(ii, V<T>(kk, 0));
    REP(i, ii) {
        REP(k, kk) {
            REP(j, jj) {
                ans[i][k] = Add(ans[i][k], Mul(A[i][j], B[j][k]));
            }
        }
    }
    return ans;
}

vvll CombMemo(1000, vll(1000, -1));

ll Comb(ll n, ll k) {
    if ((n < 0) || (k < 0)) return 0;
    if (CombMemo[n][k] == -1) {
        if (n < k) CombMemo[n][k] = 0;
        else {
            if (n == 0) CombMemo[n][k] = 1;
            else if (k == 0) CombMemo[n][k] = 1;
            else if (n == k) CombMemo[n][k] = 1;
            else CombMemo[n][k] = Comb(n - 1, k - 1) + Comb(n - 1, k);
        }
    }
    return CombMemo[n][k];
}

template<class T> map<T, ll> Dict(V<T> v) {
    map<T, ll> m;
    if (!v.sz) return m;
    SORT(v);
    UNIQUE(v);
    REP(i, v.sz) {
        m[v[i]] = i;
    }
    return m;
}

template<class T> vll Cmprs(V<T> v) {
    auto m = Dict(v);
    vll ans(v.sz);
    REP(i,v.sz) {
        ans[i] = m[v[i]];
    }
    return ans;
}

template <class T> auto vecn(T val) { return val; }
template <class... Args> auto vecn(ll val, Args... args) {
    auto tmp = vecn(args...);
    return V<decltype(tmp)>(val, tmp);
}

void Solve();

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

void Solve() {
  li(n);vli(n,a);
  SORT(a);
  ll zero=0,type=0,f;
  vll note,count;
  REP(i,n){
    if(a[i]==0){
      zero++;
    } else {
      f=-1;
      REP(j,note.sz){
        if(note[j]==a[i]){
          f=j;
        }
      }
      if(f==-1){
        note.pb(a[i]);
        count.pb(1);
      } else {
        count[f]++;
      }
    }
  }

  if(a.sz==zero){
    cout << "Yes";
    return;
  }

  if(a.sz%3){
    cout << "No";
    return;
  }

  if(note.sz>=4){
    cout << "No";
    return;
  }

  if(zero){
    if (a.sz/3==zero && a.sz/3==count[0]/2) {
      cout << "Yes";
      return;
    } else {
      cout << "No";
      return;
    }
  } else {
    if (count[0]==count[1]&&count[0]==count[2]){
      if((note[0]^note[1]==note[2])&&(note[1]^note[2]==note[0])){
        cout << "Yes";
        return;
      }
    }
  }
  cout << "No";
  return;
}

Score : 300 points

Problem Statement

Snuke has N hats. The i-th hat has an integer a_i written on it.

There are N camels standing in a circle.
Snuke will put one of his hats on each of these camels.

If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print Yes; otherwise, print No.

The bitwise XOR of the numbers written on the hats on both adjacent camels is equal to the number on the hat on itself.

What is XOR?

The bitwise XOR x_1 \oplus x_2 \oplus \ldots \oplus x_n of n non-negative integers x_1, x_2, \ldots, x_n is defined as follows:

- When x_1 \oplus x_2 \oplus \ldots \oplus x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3 \oplus 5 = 6.

Constraints

All values in input are integers.

3 \leq N \leq 10^{5}

0 \leq a_i \leq 10^{9}

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_{N}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

Yes

If we put the hats with 1, 2, and 3 in this order, clockwise, the condition will be satisfied for every camel, so the answer is Yes.

Sample Input 2

4
1 2 4 8

Sample Output 2

No

There is no such way to distribute the hats; the answer is No.


#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <vector>
#include <regex>
#include <map>
#include <set>
using namespace std;
int main(){
    int N,A,B;
    cin >> N >> A >> B;

    int train = 0;
    train = A*N;

    cout << min(train,B) << endl;
    return 0;
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 100 points

Problem Statement

N of us are going on a trip, by train or taxi.

The train will cost each of us A yen (the currency of Japan).

The taxi will cost us a total of B yen.

How much is our minimum total travel expense?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq A \leq 50

1 \leq B \leq 50

Input

Input is given from Standard Input in the following format:

N A B

Output

Print an integer representing the minimum total travel expense.

Sample Input 1

4 2 9

Sample Output 1

8

The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen.

Sample Input 2

4 2 7

Sample Output 2

7

Sample Input 3

4 2 8

Sample Output 3

8

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


#include <bits/stdc++.h>
using namespace std;
const int maxn = 200100, lg = 22;
struct query {
	int i, x, y, sig;
};
vector<tuple<int,int,int> > e[maxn];
vector<query> que[maxn];
int par[lg][maxn], dep[maxn];
void dfs(int u, int p){
	par[0][u] = p;
	for(auto ee : e[u]){
		int to, b, c; tie(to, b, c);
		if(to != p){
			dep[to] = dep[u] + 1;
			dfs(to, u);
		}
	}
}
int lca(int u, int v){
	if(dep[u] < dep[v]) swap(u, v);
	for(int i = lg - 1; i >= 0; i--) if((dep[u] - dep[v])&(1<<i)) u = par[i][u];
	if(u == v) return u;
	for(int i = lg - 1; i >= 0; i--) if(par[i][u] != par[i][v]) u = par[i][u], v = par[i][v];
	return par[0][u];
}
long long ans[maxn],  tot[maxn], amn[maxn];
void solve(int u, int p, long long d){
	for(auto q : que[u]){
		ans[q.i] += q.sig * (d - tot[q.x] + q.y * amn[q.x]);
	}
	for(auto ee : e[u]){
		int to, c, di; tie(to, c, di) = ee;
		if(to == p) continue;
		tot[c] += di;
		amn[c] += 1;
		solve(to, u, d + di);
		tot[c] -= di;
		amn[c] -= 1;
	}
}
int main(){
	int n, q; cin >> n >> q;
	for(int i = 0; i < n - 1; i++){
		int a, b, c, d; cin >> a >> b >> c >> d;
		e[a].push_back(make_tuple(b, c, d));
		e[b].push_back(make_tuple(a, c, d));
	}
	dfs(1, 0);
	for(int i = 1; i < lg; i++){
		for(int j = 1; j <= n; j++)
			if(par[i - 1][j])
				par[i][j] = par[i - 1][par[i - 1][j]];
	}
	for(int i = 0; i < q; i++){
		int x, y, u, v; cin >> x >> y >> u >> v;
		que[u].push_back({i, x, y, 1});
		que[v].push_back({i, x, y, 1});
		que[lca(u, v)].push_back({i, x, y, -2});
	}
	solve(1, 0, 0);
	for(int i = 0; i < q; i++) cout << ans[i] << endl;
	return 0;
}

Score : 600 points

Problem Statement

There is a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively.
Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors.

Answer the following Q queries:

Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.)

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

1 \leq a_i, b_i \leq N

1 \leq c_i \leq N-1

1 \leq d_i \leq 10^4

1 \leq x_j \leq N-1

1 \leq y_j \leq 10^4

1 \leq u_j < v_j \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1 c_1 d_1
:
a_{N-1} b_{N-1} c_{N-1} d_{N-1}
x_1 y_1 u_1 v_1
:
x_Q y_Q u_Q v_Q

Output

Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j.

Sample Input 1

5 3
1 2 1 10
1 3 2 20
2 4 4 30
5 2 1 40
1 100 1 4
1 100 1 5
3 1000 3 4

Sample Output 1

130
200
60

The graph in this input is as follows:

Here the edges of Color 1 are shown as solid red lines, the edge of Color 2 is shown as a bold green line, and the edge of Color 4 is shown as a blue dashed line.

Query 1: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 4 is 100 + 30 = 130.

Query 2: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 5 is 100 + 100 = 200.

Query 3: Assuming that the length of every edge whose color is 3 is changed to 1000 (there is no such edge), the distance between Vertex 3 and Vertex 4 is 20 + 10 + 30 = 60. Note that the edges of Color 1 now have their original lengths.


#include <bits/stdc++.h>
#define rep(i, n) for(int (i)=0; (i)<(n); (i)++)

using namespace std;
typedef long long ll;

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

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

  vector<int> p(N);
  for(int i=0; i<N; i++)
    cin >> p[i];

  int count;
  for(int i=0; i<N-2; i++)
    {
      if(p[i]<p[i+1] && p[i+1]<p[i+2])
	count++;
      if(p[i+2]<p[i+1] && p[i+1]<p[i])
	count++;

    }

  cout << count << endl;

  return 0;
}

//cout << setprecision(13);
//next_permutation();
//__gcd();
//reverse();
//set ,tuple ,pair;
//bitset
//vector.find
//vector.count

Score : 200 points

Problem Statement

We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.

Print the number of elements p_i (1 < i < n) that satisfy the following condition:

p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

Constraints

All values in input are integers.

3 \leq n \leq 20

p is a permutation of {1,\ 2,\ ...,\ n}.

Input

Input is given from Standard Input in the following format:

n
p_1 p_2 ... p_n

Output

Print the number of elements p_i (1 < i < n) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5


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

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

  vector<int> p(N);

  for (int i = 0; i < N; i++)
  {
    cin >> p.at(i);
  }

  int ans = 0;

  for (int i = 1; i < N - 1; i++)
  {
    if (p.at(i) != max({p.at(i - 1), p.at(i), p.at(i + 1)}) && p.at(i) != min({p.at(i - 1), p.at(i), p.at(i + 1)}))
    {
      ans++;
    }
  }

  cout << ans << endl;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
  int N;
  cin>>N;
  vector<int> vec(N);
  int count=0;
  for(int i=0;i<N;i++)
  {
    cin>>vec.at(i);
  }
  for(int i=1;i<N-1;i++)
  {
    if((vec.at(i-1)<vec.at(i)&&vec.at(i)<vec.at(i+1))||(vec.at(i-1)>vec.at(i)&&vec.at(i)>vec.at(i+1)))
    {
       count++;
    }
  }
  cout<<count<<endl;
}


#include <iostream>
using namespace std;
int main()
{
 int n;
 cin >>n;
 int p[n];
  for(int i=0;i<n;i++)
    cin >> p[i];
  int count = 0;
  for(int i=1;i<n-1;i++)
  {
    if(((p[i-1]<p[i]) && (p[i]<p[i+1]))||((p[i-1]>p[i])&&(p[i]>p[i+1])))
      count++;
  }
  cout << count <<endl;

  return 0;
}


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

signed
main(){
	int n;
	cin >> n;
	vector<int> p(n);
	for(int i=0;i<n;i++) cin >> p[i];

	int cnt = 0;
	for(int x=0;x<n-2;x++){
		if(p[x] < p[x+1] and p[x+1] < p[x+2]) {
			cnt++;
		}else if(p[x] > p[x+1] and p[x+1] > p[x+2])
		{
			cnt++;
		}
	}
	cout << cnt << endl;
}


#include<bits/stdc++.h>

using namespace std;
using ll  = long long;
using ii  = pair < int , int >;
using i3  = pair < int , ii >;
using vi  = vector < int >;
using vii = vector < ii >;
using vi3 = vector < i3 >;

const int N = 25;
const ll INF = 1e12;
const double eps = 1e-9 , PI = acos(-1);

int n , m;
int a[N];

void solve(){
    scanf("%d" , &n);
    for(int i = 0 ; i < n ; i ++){
        scanf("%d" , &a[i]);
    }
    int ans = 0;
    for(int i = 1 ; i < n-1 ; i ++){
        vi tmp({a[i-1] , a[i] , a[i+1]});
        sort(tmp.begin() , tmp.end());
        if(tmp[1] == a[i])ans ++;
    }
    printf("%d\n" , ans);

}

main(){
    int t = 1;
    //scanf("%d" , &t);

    while( t -- ){
            solve();
    }

    return 0;
}


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

int main(){
    int n; cin>>n;
    vector<int> d(n);
    for(int  &x: d) cin>>x;
    sort(d.begin(),d.end());
    cout<<d[n/2]-d[n/2-1]<<endl;
}

Score : 300 points

Problem Statement

Takahashi made N problems for competitive programming.
The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).

He is dividing the problems into two categories by choosing an integer K, as follows:

A problem with difficulty K or higher will be for ARCs.

A problem with difficulty lower than K will be for ABCs.

How many choices of the integer K make the number of problems for ARCs and the number of problems for ABCs the same?

Problem Statement

2 \leq N \leq 10^5

N is an even number.

1 \leq d_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the number of choices of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 1

6
9 1 4 4 6 7

Sample Output 1

2

If we choose K=5 or 6, Problem 1, 5, and 6 will be for ARCs, Problem 2, 3, and 4 will be for ABCs, and the objective is achieved.
Thus, the answer is 2.

Sample Input 2

8
9 1 14 5 5 4 4 14

Sample Output 2

0

There may be no choice of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 3

14
99592 10342 29105 78532 83018 11639 92015 77204 30914 21912 34519 80835 100000 1

Sample Output 3

42685


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

uintmax_t combination(unsigned int n, unsigned int r) {
  if ( r * 2 > n ) r = n - r;
  uintmax_t dividend = 1;
  uintmax_t divisor  = 1;
  for ( unsigned int i = 1; i <= r; ++i ) {
    dividend *= (n-i+1);
    divisor  *= i;
  }
  return dividend / divisor;
}

int main() {
  int K, N;
  cin >> N >> K;
  for (int i = 1; i <= K; i++) {
   // cout << K-1 << "," << i-1 << "|" << N-K+1 << "," << i << endl;
    if (N-K+1 < i || K-1 < i-1) cout << "0" << endl;
    else cout << (combination(K-1, i-1) * combination(N-K+1, i)) % 1000000007 << endl;
  }
  return 0;
}

Score : 400 points

Problem Statement

There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.

First, Snuke will arrange the N balls in a row from left to right.

Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.

How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

Constraints

1 \leq K \leq N \leq 2000

Input

Input is given from Standard Input in the following format:

N K

Output

Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

Sample Input 1

5 3

Sample Output 1

3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).

There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).

There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

Sample Input 2

2000 3

Sample Output 2

1998
3990006
327341989

Be sure to print the numbers of arrangements modulo 10^9+7.


#include "bits/stdc++.h"
#define _overload3(_1,_2,_3,name,...) name
#define _rep(i,n) repi(i,0,n)
#define repi(i,a,b) for(int i=int(a),i##_len=(b);i<i##_len;++i)
#define MSVC_UNKO(x) x
#define rep(...) MSVC_UNKO(_overload3(__VA_ARGS__,repi,_rep,_rep)(__VA_ARGS__))
#define all(c) c.begin(),c.end()
#define mp make_pair
#define write(x) cout<<(x)<<"\n"
using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<ll> vll;
template<class T>using vv = vector<vector<T>>; template<class T>auto vvec(int n, int m, T v) { return vv<T>(n, vector<T>(m, v)); }
template<class T>bool chmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }
template<class T>bool chmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; }
constexpr int INF = 1 << 29, MOD = int(1e9) + 7; constexpr ll LINF = 1LL << 60;
struct aaa { aaa() { cin.tie(0); ios::sync_with_stdio(0); cout << fixed << setprecision(10); }; }aaaa;

using TP = pair<pair<int, int>, int>;
//using Q = pair<pair<int, int>, TP>;

int N, M;
vv<int> graph, kkpGraph;
vector<ll> dist;

//vector<int> in;
vv<bool> visited;

void dfs(int v, TP hist, int d) {
    //visited[v]++;

    if (/*d % 3 == 0 && */hist.first.first != -1) {
        kkpGraph[hist.first.first].push_back(v);
    }

    for (int u : graph[v]) {
        if (!visited[u][d]) {
            visited[u][d] = true;
            dfs(u, TP(mp(hist.first.second, hist.second), v), d + 1);
        }
        //if (used[v][u] < 3) {
        //    used[v][u]++;
        //    dfs(u, TP(mp(hist.first.second, hist.second), v), d + 1);
        //}
    }
}

//void bfs(int s) {
//    queue<Q> que;
//    que.emplace(mp(s, 0), TP({ -1, -1 }, -1));
//
//    while (!que.empty()) {
//        auto q = que.front();
//        que.pop();
//        int v = q.first.first;
//        int d = q.first.second;
//        auto& hist = q.second;
//
//        if (/*d % 3 == 0 && */hist.first.first != -1) {
//            kkpGraph[hist.first.first].push_back(v);
//        }
//
//        for (int u : graph[v]) {
//            if (find(all(used[v]), mp(u, d)) == used[v].end()) {
//                used[v].insert(mp(u, d));
//                que.emplace(mp(u, (d + 1) % 3), TP(mp(hist.first.second, hist.second), v));
//            }
//        }
//    }
//}

void bfs_kkp(int s) {
    dist.assign(kkpGraph.size(), LINF);
    dist[s] = 0;
    queue<int> que;
    que.push(s);

    while (!que.empty()) {
        int v = que.front(); que.pop();

        for (int e : kkpGraph[v]) {
            if (dist[e] == LINF/*&& other condition*/) {
                dist[e] = dist[v] + 1;
                que.push(e);
            }
        }
    }
}

int main() {
    cin >> N >> M;
    graph.resize(N);
    //in.resize(N);
    rep(i, M) {
        int u, v;
        cin >> u >> v;
        graph[u - 1].push_back(v - 1);
        //in[v - 1]++;
    }
    int S, T;
    cin >> S >> T;

    kkpGraph.resize(N);
    visited = vvec(N, 3, false);
    //used.resize(N);
    dfs(S - 1, TP(mp(-1, -1), -1), 0);
    //bfs(S - 1);

    rep(i, N) {
        sort(all(kkpGraph[i]));
        kkpGraph[i].erase(unique(all(kkpGraph[i])), kkpGraph[i].end());
    }

    bfs_kkp(S - 1);
    if (dist[T - 1] == LINF) {
        write(-1);
    }
    else {
        write(dist[T - 1]);
    }
}

Score : 500 points

Problem Statement

Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G.
G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.

First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.

Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq \min(10^5, N (N-1))

1 \leq u_i, v_i \leq N(1 \leq i \leq M)

u_i \neq v_i (1 \leq i \leq M)

If i \neq j, (u_i, v_i) \neq (u_j, v_j).

1 \leq S, T \leq N

S \neq T

Input

Input is given from Standard Input in the following format:

N M
u_1 v_1
:
u_M v_M
S T

Output

If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1.
If he can, print the minimum number of ken-ken-pa needed to reach vertex T.

Sample Input 1

4 4
1 2
2 3
3 4
4 1
1 3

Sample Output 1

2

Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.

Sample Input 2

3 3
1 2
2 3
3 1
1 2

Sample Output 2

-1

Any number of ken-ken-pa will bring Ken back to Vertex 1, so he cannot reach Vertex 2, though he can pass through it in the middle of a ken-ken-pa.

Sample Input 3

2 0
1 2

Sample Output 3

-1

Vertex S and Vertex T may be disconnected.

Sample Input 4

6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6

Sample Output 4

2


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

int main(){
	string num;
	while(getline(cin,num)){
		int x,a,b;
		stringstream ss;
		ss<<num;
		ss>>x;
		while(ss>>x){
			a=x/1000;
			b=(x%1000)/100;
			if(a==b){
				cout<<"Bad"<<"\n";
				break;
			}
			else{
				a=(x%100)/10;
				if(b==a){
					cout<<"Bad"<<"\n";
					break;
				}
				else{
					b=x%10;
					if(a==b){
						cout<<"Bad"<<"\n";
						break;
					}
					else{
						cout<<"Good"<<"\n";
						continue;
					}
				}
			}
		}
	}
	return 0;
}

Score : 100 points

Problem Statement

The door of Snuke's laboratory is locked with a security code.

The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.

You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good.

Constraints

S is a 4-character string consisting of digits.

Input

Input is given from Standard Input in the following format:

S

Output

If S is hard to enter, print Bad; otherwise, print Good.

Sample Input 1

3776

Sample Output 1

Bad

The second and third digits are the same, so 3776 is hard to enter.

Sample Input 2

8080

Sample Output 2

Good

There are no two consecutive digits that are the same, so 8080 is not hard to enter.

Sample Input 3

1333

Sample Output 3

Bad

Sample Input 4

0024

Sample Output 4

Bad


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,l;
    cin>>n>>l;
    int sum=0;
    int pie[n+1];
    int m1,m2;
    for(int i=1;i<=n;i++){
        pie[i]=l+i-1;
        sum+=pie[i];
    }
    for(int i=1;i<=n;i++){
        if(i==1){
            m2=sum-pie[i];
            m1=abs(pie[i]);
            //cout<<m2<<endl;
        }
        else{
            if(abs(pie[i])<m1){
            m2=sum-pie[i];
            m1=abs(pie[i]);
           // cout<<m2<<endl;
            }
        }
    }
    cout<<m2<<endl;
}

Score : 200 points

Problem Statement

You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.

You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.

You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.

You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining N-1 apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the N apples.

Find the flavor of the apple pie made of the remaining N-1 apples when you choose the apple to eat as above.

We can prove that this value is uniquely determined.

Constraints

2 \leq N \leq 200

-100 \leq L \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N L

Output

Find the flavor of the apple pie made of the remaining N-1 apples when you optimally choose the apple to eat.

Sample Input 1

5 2

Sample Output 1

18

The flavors of Apple 1, 2, 3, 4, and 5 are 2, 3, 4, 5, and 6, respectively. The optimal choice is to eat Apple 1, so the answer is 3+4+5+6=18.

Sample Input 2

3 -1

Sample Output 2

0

The flavors of Apple 1, 2, and 3 are -1, 0, and 1, respectively. The optimal choice is to eat Apple 2, so the answer is (-1)+1=0.

Sample Input 3

30 -50

Sample Output 3

-1044


#include <iostream>
using namespace std;
int main()
{
    int n, l, s, m;
    cin >> n;
    cin >> l;
    s = l+1;
    m = l+n;
    if(l>0){
        for(int i=0;i<=n;i++){
        l= l +1;
        }
        cout << l-s<< '\n';

    }
    if(l<0){
    if(l-n>0){
        for(int i=0;i<=n;i++){
        l= l + 1;
        }
        cout << l << '\n';

    }
    if(l-n>0){
        for(int i=0;i<n;i++){
        l= l + 1;
        }
        cout << l-m << '\n';
    }
    }
    return 0;
}


#include "bits/stdc++.h"

using namespace std;

long a, b, c, d;

long f(long x)
{
	return (x - x/c - x/d + x/(c*d/__gcd(c,d)));
}

void solve(void)
{
	cin >> a >> b >> c >> d;
	cout << f(b) - f(a-1) << endl;
}

int main()
{
	solve();
	//cout << "yui(*-v・)yui" << endl;
	return 0;
}

Score : 300 points

Problem Statement

You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Constraints

1\leq A\leq B\leq 10^{18}

1\leq C,D\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Sample Input 1

4 9 2 3

Sample Output 1

2

5 and 7 satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368


#include <bits/stdc++.h>
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define int long long
#define pb insert
#define sz(i) (int)(i.size())
#define F first
#define S second
#define L long double
#define P pair<int, int>
const int inf = 0x3f3f3f3f3f3f3f3LL;
const int mod = (int)1e9 + 7;
using namespace std;
#if LOCAL
#include "../../tr.h"
#else
#define tr(...)
#define endl '\n'
#endif
template<class T> void smin(T& a, T val) {if (a > val) a = val;}template<class T> void smax(T& a, T val) {if (a < val) a = val;}
const int N = 5*(int)1e5 + 10;

int n, k;
set<P> v;

int32_t main(){_

   cin>>n>>k;

   int ma = (n-2) * (n-1) / 2;

   if (k <= 0){
      cout<<-1;
      exit(0);
   }

   if (k > ma){
      cout<<-1;
      exit(0);
   }

   int vals = 0;
   for (int adj = 1; adj <= n; ++adj)
   {
      int tot = adj - 1;
      tot = tot * (tot+1);
      tot >>= 1;
      if(tot <= k){
         vals = adj;
      }
      else{
         break;
      }
   }

   int adj = vals;

   for (int i = 1; i <= adj; ++i)
   {
      v.pb({1, i+1});
   }

   k -= ((adj * (adj - 1)) / 2);

   adj+=2;
   int lst = adj;
   tr(adj, k, v);
   for (int i = adj; i <= n; ++i)
   {
      int poss = adj-2;
      if(k > 0 and k - poss < 0){
         v.pb({i, 1});
         int rem = k;
         k = 0;
         for (int j = 2; j <= adj-rem-1; ++j)
         {
            v.pb({i, j});
         }
         lst = adj+1;
         break;
      }
   }

   tr(lst, k);

   for (int i = lst; i <= n; ++i)
   {
      for (int j = 1; j <= i-1; ++j)
      {
         v.pb({i, j});
      }
   }

   if(k > 0){
      assert(0);
      cout<<-1;
      exit(0);
   }

   cout<<sz(v)<<endl;
   for(auto it: v)
      cout<<it.F<<' '<<it.S<<endl;

   return 0;
}

Score: 500 points

Problem Statement

Does there exist an undirected graph with N vertices satisfying the following conditions?

The graph is simple and connected.

The vertices are numbered 1, 2, ..., N.

Let M be the number of edges in the graph. The edges are numbered 1, 2, ..., M, the length of each edge is 1, and Edge i connects Vertex u_i and Vertex v_i.

There are exactly K pairs of vertices (i,\ j)\ (i < j) such that the shortest distance between them is 2.

If there exists such a graph, construct an example.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq K \leq \frac{N(N - 1)}{2}

Input

Input is given from Standard Input in the following format:

N K

Output

If there does not exist an undirected graph with N vertices satisfying the conditions, print -1.

If there exists such a graph, print an example in the following format (refer to Problem Statement for what the symbols stand for):

M
u_1 v_1
:
u_M v_M

If there exist multiple graphs satisfying the conditions, any of them will be accepted.

Sample Input 1

5 3

Sample Output 1

5
4 3
1 2
3 1
4 5
2 3

This graph has three pairs of vertices such that the shortest distance between them is 2: (1,\ 4), (2,\ 4), and (3,\ 5). Thus, the condition is satisfied.

Sample Input 2

5 8

Sample Output 2

-1

There is no graph satisfying the conditions.


#include "bits/stdc++.h"

using namespace std;

int X, A;

int main() {
	cin >> X >> A;
	if (X < A) cout << 0;
	else cout << 10;
	return 0;
}

Score : 100 points

Problem Statement

X and A are integers between 0 and 9 (inclusive).

If X is less than A, print 0; if X is not less than A, print 10.

Constraints

0 \leq X, A \leq 9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X A

Output

If X is less than A, print 0; if X is not less than A, print 10.

Sample Input 1

3 5

Sample Output 1

0

3 is less than 5, so we should print 0.

Sample Input 2

7 5

Sample Output 2

10

7 is not less than 5, so we should print 10.

Sample Input 3

6 6

Sample Output 3

10

6 is not less than 6, so we should print 10.


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

int main() {
  int X, A;
  cin >> X >> A;
  cout << (X < A ? 0 : 10);
}


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

int main(){
  int N, X;
  cin >> N >> X;
  int L[N];
  int D[N]={0};
  for(int i=0; i<N; i++){
    cin >> L[i];
  }

  for(int j=1; j<N+1; j++){
    D[j] = D[j-1] + L[j-1];
    if(D[j] > X){
      cout << j;
      return 0;
    }
  }

  return 0;
}

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.


using namespace std;

#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <algorithm>
#include <utility>
#include <functional>
#include <queue>
#include <cmath>
#include <numeric>
#include <map>
#include<iomanip>
using namespace std;

int main(void){
	long long int  W,H,x,y;

	cin >>W>>H>>x>>y;

  	long long int xmin = min(W - x, x), ymin = min(H - y, y);

	cout << (long double)W * (long double)H / (long double)2.0 << " " << ((xmin * H == ymin * W) ? 1 : 0) << endl;

	return 0;
}

Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, m, n) for (int i = m; i < n; ++i)
#define rem(i, m, n) for (int i = m; i > n; --i)
const int MOD = 1000000007;

int main() {
  double W, H, x, y;
  cin >> W >> H >> x >> y;
  printf("%.15lf ", W * H / 2);
  double mx = W / 2, my = H / 2;
  if(x == mx && y == my) cout << 1 << endl;
  else cout << 0 << endl;
  return 0;
}


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

int main() {
  int64_t MOD = 1000000000 + 7;
  int N, M;
  cin >> N >> M;
  vector<int64_t> S(N);
  vector<int64_t> T(M);
  for(int i = 0; i < N; i++) {
    cin >> S.at(i);
  }
  for(int i = 0; i < M; i++) {
    cin >> T.at(i);
  }
  vector<vector<int64_t>> data(N + 1, vector<int64_t> (M + 1, 0));
  for(int i = 0; i <= N; i++) {
    data.at(i).at(0) = 1;
  }
  for(int i = 0; i <= M; i++) {
    data.at(0).at(i) = 1;
  }
  for(int i = 1; i <= N; i++) {
    for(int j = 1; j <= M; j++) {
      if(S.at(i - 1) == T.at(j - 1)) {
        data.at(i).at(j) = data.at(i).at(j - 1) + data.at(i - 1).at(j);
        data.at(i).at(j) %= MOD;
      }
      else {
        data.at(i).at(j) = data.at(i).at(j - 1) + data.at(i - 1).at(j) - data.at(i - 1).at(j - 1);
        data.at(i).at(j) %= MOD;
      }
    }
  }
  cout << data.at(N).at(M) << endl;
}

Score : 500 points

Problem Statement

You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive).

In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content?

Here the subsequence of A is a sequence obtained by removing zero or more elements from A and concatenating the remaining elements without changing the order.

For both S and T, we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Since the answer can be tremendous, print the number modulo 10^9+7.

Constraints

1 \leq N, M \leq 2 \times 10^3

The length of S is N.

The length of T is M.

1 \leq S_i, T_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
S_1 S_2 ... S_{N-1} S_{N}
T_1 T_2 ... T_{M-1} T_{M}

Output

Print the number of pairs of a subsequence of S and a subsequence of T such that the subsequences are the same in content, modulo 10^9+7.

Sample Input 1

2 2
1 3
3 1

Sample Output 1

3

S has four subsequences: (), (1), (3), (1, 3).

T has four subsequences: (), (3), (1), (3, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 1 \times 1 pair of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (3), for a total of three pairs.

Sample Input 2

2 2
1 1
1 1

Sample Output 2

6

S has four subsequences: (), (1), (1), (1, 1).

T has four subsequences: (), (1), (1), (1, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 2 \times 2 pairs of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (1,1), for a total of six pairs.
Note again that we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Sample Input 3

4 4
3 4 5 6
3 4 5 6

Sample Output 3

16

Sample Input 4

10 9
9 6 5 7 5 9 8 5 6 7
8 6 8 5 5 7 9 9 7

Sample Output 4

191

Sample Input 5

20 20
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Sample Output 5

846527861

Be sure to print the number modulo 10^9+7.


#define _CRT_SECURE_NO_WARNINGS
#pragma comment(linker, "/stack:256000000")
#include<utility>
#include<iostream>
#include<vector>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<functional>
#include<random>
#include<climits>
#include<queue>
#include<stack>
#include<deque>
#include<bitset>
#include<map>
#include<set>
#include<unordered_map>
#include<unordered_set>
#include<cassert>
#include<ccomplex>

//4Head
#define all(x) x.begin(), x.end()
#define mp make_pair
#define X first
#define Y second

using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
mt19937_64 gen(time(NULL));

// belik's shit
ll const mod = 1e9 + 7;
namespace {
	ll mult(ll a, ll b) {
		ll val = a * b - (ll)((ld)a * b / mod) * mod;
		if (val < 0) {
			val += mod;
		}
		if (val >= mod) {
			val -= mod;
		}
		return val;
	}
	ll poww(ll a, ll b)
	{
		ll val = 1;
		a %= mod;
		while (b > 0){
			if (b % 2) val = mult(a, val);
			a = mult(a, a);
			b >>= 1;
		}
		return val % mod;
	}
	ll inv(ll a) {
		return poww(a, mod - 2);
	}
}

ll const maxn = 2e3 + 5;

ll dp[maxn][maxn];

signed main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	ll n, m; cin >> n >> m;
	vector<ll>a(n + 1), b(m + 1);
	a[0] = -1; b[0] = -2;
	for (ll i = 1; i <= n; i++) cin >> a[i];
	for (ll i = 1; i <= m; i++) cin >> b[i];
	dp[0][0] = 1;
	for (ll i = 0; i <= n; i++) {
		for (ll j = 0; j <= m; j++) {
			(dp[i][j] += (i ? dp[i - 1][j] : 0)) %= mod;
			(dp[i][j] += (j ? dp[i][j - 1] : 0)) %= mod;
			(dp[i][j] -= (i && j ? dp[i - 1][j - 1] : 0)) %= mod;
			if (dp[i][j] < 0) dp[i][j] += mod;
			if (a[i] == b[j]) {
				(dp[i][j] += (i && j ? dp[i - 1][j - 1] : 0)) %= mod;
			}
			ll tt = 0;
		}
	}
	cout << (dp[n][m])%mod << endl;
	return 0;

}
/*

*/


#include <bits/stdc++.h>
#define int long long
#define double long double
#pragma GCC optimize("O3,Ofast,no-stack-protector,unroll-loops,fast-math")
#pragma GCC target("avx,avx2,sse")
using namespace std;

int n;
vector<int> x(n);
vector<int> y(n);
vector<char> c(n);

double calc(double steps) {
    double ax = 1e15;
    double bx = -1e15;
    double ay = 1e15;
    double by = -1e15;
    for (int i = 0; i < n; i++) {
        double X = x[i];
        double Y = y[i];
        if (c[i] == 'L') X -= steps;
        if (c[i] == 'R') X += steps;
        if (c[i] == 'D') Y -= steps;
        if (c[i] == 'U') Y += steps;
        ax = min(ax, X);
        bx = max(bx, X);
        ay = min(ay, Y);
        by = max(by, Y);
    }
    return (by - ay) * (bx - ax);
}

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

    cin >> n;
    x.resize(n);
    y.resize(n);
    c.resize(n);
    for (int i = 0; i < n; i++) {
        cin >> x[i] >> y[i] >> c[i];
    }
    double s = 0;
    double e = 1e9;
    while (e - s > 0.000000000001) {
        double a = (s * 2 + e) / 3.0;
        double b = (s + e * 2) / 3.0;
        double fa = calc(a);
        double fb = calc(b);
        if (fa <= fb) {
            e = b;
        } else {
            s = a;
        }
    }
    cout << fixed << ' ' << setprecision(11) << calc(s) << endl;

    fflush(stdout);
    return 0;
}

Score : 600 points

Problem Statement

There are N points in a two-dimensional plane. The initial coordinates of the i-th point are (x_i, y_i). Now, each point starts moving at a speed of 1 per second, in a direction parallel to the x- or y- axis. You are given a character d_i that represents the specific direction in which the i-th point moves, as follows:

If d_i = R, the i-th point moves in the positive x direction;

If d_i = L, the i-th point moves in the negative x direction;

If d_i = U, the i-th point moves in the positive y direction;

If d_i = D, the i-th point moves in the negative y direction.

You can stop all the points at some moment of your choice after they start moving (including the moment they start moving).
Then, let x_{max} and x_{min} be the maximum and minimum among the x-coordinates of the N points, respectively. Similarly, let y_{max} and y_{min} be the maximum and minimum among the y-coordinates of the N points, respectively.

Find the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}) and print it.

Constraints

1 \leq N \leq 10^5

-10^8 \leq x_i,\ y_i \leq 10^8

x_i and y_i are integers.

d_i is R, L, U, or D.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1 d_1
x_2 y_2 d_2
.
.
.
x_N y_N d_N

Output

Print the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}).

The output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-9}.

Sample Input 1

2
0 3 D
3 0 L

Sample Output 1

0

After three seconds, the two points will meet at the origin. The value in question will be 0 at that moment.

Sample Input 2

5
-7 -10 U
7 -6 U
-8 7 D
-3 3 D
0 -6 R

Sample Output 2

97.5

The answer may not be an integer.

Sample Input 3

20
6 -10 R
-4 -9 U
9 6 D
-3 -2 R
0 7 D
4 5 D
10 -10 U
-1 -8 U
10 -6 D
8 -5 U
6 4 D
0 3 D
7 9 R
9 -4 R
3 10 D
1 9 U
1 -6 U
9 -8 R
6 7 D
7 -3 D

Sample Output 3

273


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define rep2(i, s, n) for (ll i = (s); i < (ll)(n); i++)
#define all(v) v.begin(), v.end()
#define sz(v) v.size()
#define INF 100000000000000 //10^14
template <typename T>
bool chmax(T &a, const T& b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <typename T>
bool chmin(T &a, const T& b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}

int main()
{
    ll N;
    cin >> N;
    vector<ll> A(N);
    rep(i, N) cin >> A.at(i);
    sort(all(A));
    ll p = N;
    rep(i, N){
      if(A.at(i) > 0){
        p = i;
        break;
      }
    }
    ll M = 0;
    M += A.at(N-1);
    M -= A.at(0);
    rep(i, N-2){
      if(i+1 >= p){
        M += A.at(i+1);
      }
      else{
        M -= A.at(i+1);
      }
    }
    cout << M << endl;
    ll x = A.at(0);
    if(p == 0){
      p++;
    }
    rep2(j, p, N-1){
      cout << x << " " << A.at(j) << endl;
      x -= A.at(j);
    }
    ll y = A.at(N-1);
    rep2(i, 1, p){
      cout << y << " " << A.at(i) << endl;
      y -= A.at(i);
    }
    cout << y << " " << x << endl;
}

Score : 500 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on a blackboard.

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0


#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<vector>
#include<queue>
#include<map>
#include<iomanip>
#include<set>
#define rep(index,num) for(int index=0;index<num;index++)
#define rep1(index,num) for(int index=1;index<=num;index++)
#define scan(argument) cin>>argument
#define prin(argument) cout<<argument<<endl
#define kaigyo cout<<endl
#define eps 1e-7
#define mp(a1,a2) make_pair(a1,a2)
typedef long long ll;
typedef long double ld;
using namespace std;
typedef pair<ll,ll> pll;
typedef pair<int,int> pint;
typedef vector<int> vint;
typedef vector<ll> vll;
typedef vector<pint> vpint;
typedef vector<pll> vpll;
ll INFl=1e+18+1;
int INF=1e+9+1;
int main(){
	ll N,g[2][3];
	scan(N);
	rep(i,2) rep(j,3) scan(g[i][j]);
	vpll AB,BA;
	rep(j,3){
		if(g[0][j]<g[1][j]) AB.push_back({g[0][j],g[1][j]});
		if(g[0][j]>g[1][j]) BA.push_back({g[1][j],g[0][j]});
	}
	ll maxD=N;
	if(AB.size()==3){
		for(ll a=0;a*AB[0].first<=N;a++){
			for(ll b=0;a*AB[0].first+b*AB[1].first<=N;b++){
				ll c=(N-a*AB[0].first-b*AB[1].first)/AB[2].first;
				ll nokorid=N-a*AB[0].first-b*AB[1].first-c*AB[2].first;
				ll D=nokorid+a*AB[0].second+b*AB[1].second+c*AB[2].second;
				maxD=max(maxD,D);
				//printf("a:%lld b:%lld c:%lld nokorid:%lld D:%lld maxD:%lld\n",a,b,c,nokorid,D,maxD);
			}
		}
	}
	else if(AB.size()==2){
		for(ll a=0;a*AB[0].first<=N;a++){
			ll b=(N-a*AB[0].first)/AB[1].first;
			ll nokorid=N-a*AB[0].first-b*AB[1].first;
			ll D=nokorid+a*AB[0].second+b*AB[1].second;
			maxD=max(maxD,D);
			//printf("a:%lld b:%lld nokorid:%lld D:%lld maxD:%lld\n",a,b,nokorid,D,maxD);

		}
	}
	else if(AB.size()==1){
		maxD=(N-N/AB[0].first*AB[0].first+N/AB[0].first*AB[0].second);
	}
	//printf("maxD:%lld\n",maxD);
	N=maxD;
	if(BA.size()==3){
		for(ll a=0;a*BA[0].first<=N;a++){
			for(ll b=0;a*BA[0].first+b*BA[1].first<=N;b++){
				ll c=(N-a*BA[0].first-b*BA[1].first)/BA[2].first;
				ll nokorid=N-a*BA[0].first-b*BA[1].first-c*BA[2].first;
				ll D=nokorid+a*BA[0].second+b*BA[1].second+c*BA[2].second;
				maxD=max(maxD,D);
				//printf("a:%lld b:%lld c:%lld nokorid:%lld D:%lld maxD:%lld\n",a,b,c,nokorid,D,maxD);

			}
		}
	}
	else if(BA.size()==2){
		for(ll a=0;a*BA[0].first<=N;a++){
			ll b=(N-a*BA[0].first)/BA[1].first;
			ll nokorid=N-a*BA[0].first-b*BA[1].first;
			ll D=nokorid+a*BA[0].second+b*BA[1].second;
			maxD=max(maxD,D);
		//	printf("a:%lld b:%lld nokorid:%lld D:%lld maxD:%lld\n",a,b,nokorid,D,maxD);

		}
	}
	else if(BA.size()==1){
		maxD=(N-N/BA[0].first*BA[0].first+N/BA[0].first*BA[0].second);
	}
	prin(maxD);
	return 0;
}

Score : 600 points

Problem Statement

The squirrel Chokudai has N acorns.
One day, he decides to do some trades in multiple precious metal exchanges to make more acorns.

His plan is as follows:

Get out of the nest with N acorns in his hands.

Go to Exchange A and do some trades.

Go to Exchange B and do some trades.

Go to Exchange A and do some trades.

Go back to the nest.

In Exchange X (X = A, B), he can perform the following operations any integer number of times (possibly zero) in any order:

Lose g_{X} acorns and gain 1 gram of gold.

Gain g_{X} acorns and lose 1 gram of gold.

Lose s_{X} acorns and gain 1 gram of silver.

Gain s_{X} acorns and lose 1 gram of silver.

Lose b_{X} acorns and gain 1 gram of bronze.

Gain b_{X} acorns and lose 1 gram of bronze.

Naturally, he cannot perform an operation that would leave him with a negative amount of acorns, gold, silver, or bronze.

What is the maximum number of acorns that he can bring to the nest?
Note that gold, silver, or bronze brought to the nest would be worthless because he is just a squirrel.

Constraints

1 \leq N \leq 5000

1 \leq g_{X} \leq 5000

1 \leq s_{X} \leq 5000

1 \leq b_{X} \leq 5000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
g_A s_A b_A
g_B s_B b_B

Output

Print the maximum number of acorns that Chokudai can bring to the nest.

Sample Input 1

23
1 1 1
2 1 1

Sample Output 1

46

He can bring 46 acorns to the nest, as follows:

In Exchange A, trade 23 acorns for 23 grams of gold. {acorns, gold, silver, bronze}={ 0,23,0,0 }

In Exchange B, trade 23 grams of gold for 46 acorns. {acorns, gold, silver, bronze}={ 46,0,0,0 }

In Exchange A, trade nothing. {acorns, gold, silver, bronze}={ 46,0,0,0 }

He cannot have 47 or more acorns, so the answer is 46.


#include <bits/stdc++.h>
using namespace std;
const int mod =1e9+7;
int main(void){
    int n,m;cin>>n>>m;
    vector<int> d(m);
    for(int i=0;i<m;i++)cin>>d[i];
    vector<int> dp(n+1,0);
    dp[0]=dp[1]=1;
    int tmp=0;
    if(d[0]==1){
        tmp++;
        dp[1]=0;
    }
    for(int i=2;i<=n;i++){
        if(tmp<m&&d[tmp]==i){
            tmp++;
            continue;
        }
        dp[i]=dp[i-1]+dp[i-2];
        dp[i]%=mod;
    }
    cout<<dp[n]<<endl;
    return 0;
}

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.


#include <iostream>
#include <iomanip>
#include <cstdio>
#include <queue>
#include <cstring>
#include <vector>
#include <map>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <bitset>
#include <set>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define RREP(i,n) for(int i=n-1;i>=0;i--)
#define FOR(i,k,n) for(int i=(k);i<(int)(n);i++)
#define all(i,n) (i),(i+n)

int dx4[4]={1,0,-1,0};
int dy4[4]={0,-1,0,1};
int dx8[8]={1,0,-1,1,-1,1,0,-1};
int dy8[8]={1,1,1,0,0,-1,-1,-1};

typedef pair<int, int> P;
typedef pair<string, int> SP;
typedef long long ll;

const int INF = 1e9;
const ll LLINF = 1e18;
const int MAX_V = 1e6+1;
const ll mod = 1000000007;

// --------------------------------------
int n, m;
vector<int> v;
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);

  cin >> n >> m;
  vector<bool> v(n + 1, true);
  REP(i, m) {
    int a;
    cin >> a;
    v[a] = false;
  }

  vector<int> memo(n + 1, 0);
  memo[0] = 1;
  FOR(i, 1, n + 1) {
    if(v[i]) {
      if(i == 1) memo[i] = memo[i - 1] % mod;
      else memo[i] = (memo[i - 1] + memo[i - 2]) % mod;
    } else {
      memo[i] = 0;
    }
  }

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


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

#define MOD 1000000007;

int main(){
	int n, m;
	cin >> n >> m;
	vector<int> a(m);
	for(int i=0; i<m; i++)
		cin >> a[i];
	vector<long long> dp(n+1);
	dp[n]=1;
	dp[n-1]=1;
	int key=m-1;
	for(int i=n-2; i>=0; i--){
		dp[i] = (dp[i+1]+dp[i+2])%MOD;
		if(key>=0 && i==a[key]){
			dp[i] = 0;
			key--;
		}
	}
	cout << dp[0] << endl;
	return 0;
}


#include "bits/stdc++.h"

using namespace std;
using ll = long long;
const double pi = acos(-1);
#define FOR(i,a,b) for (ll i=(a),__last_##i=(b);i<__last_##i;i++)
#define RFOR(i,a,b) for (ll i=(b)-1,__last_##i=(a);i>=__last_##i;i--)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) RFOR(i,0,n)
#define __GET_MACRO3(_1, _2, _3, NAME, ...) NAME
#define rep(...) __GET_MACRO3(__VA_ARGS__, FOR, REP)(__VA_ARGS__)
#define rrep(...) __GET_MACRO3(__VA_ARGS__, RFOR, RREP)(__VA_ARGS__)
template<typename T> ostream& operator<<(ostream& os, const vector<T>& v) {
	REP(i, v.size()) { if (i)os << " "; os << v[i]; }return os;
}
template<typename T> ostream& operator<<(ostream& os, const vector<vector<T>>& v) {
	REP(i, v.size()) { if (i)os << endl; os << v[i]; }return os;
}

const ll INF = 1LL << 60;
ll MOD = 1000000007;
ll _MOD = 1000000009;
double EPS = 1e-10;

#define int long long

inline void my_io() {

	std::ios::sync_with_stdio(false);

	std::cin.tie(0);

	cout << fixed << setprecision(16);

	//cout << setprecision(10) << scientific << ans << endl;

}

signed main() {
	ll n, m;
	ll ans = INF;

	cin >> n >> m;

	vector<ll> v(m, 0);

	REP(i, m) {
		cin >> v[i];
	}

	vector<ll> dp(n + 1, 0);

	REP(i, m) {
		dp[v[i]] = -1;
	}

	dp[0] = 1;

	FOR(i, 1, n + 1) {
		if (dp[i] == -1) {
			continue;
		}

		if (dp[i - 1] != -1) {
			dp[i] += dp[i - 1];
			dp[i] %= MOD;
		}
		if (i > 1 && dp[i - 2] != -1) {
			dp[i] += dp[i - 2];
			dp[i] %= MOD;
		}
	}

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


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

int main()
{
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n, a, b, c, d;
  cin >> n >> a >> b >> c >> d;
  --a, --b, --c, --d;
  string t;
  cin >> t;
  auto reachable = [&](int s, int f) {
    if (t[s] == '#' || t[f] == '#') return false;
    for (int i = s + 1; i <= f; ++i) {
      if (t[i] == t[i - 1] && t[i] == '#') {
        return false;
      }
    }
    return true;
  };
  auto hasg3 = [&](int s, int f) {
    for (int i = s; i <= f - 2; ++i) {
      if (t[i] == t[i + 1] && t[i] == t[i + 2] && t[i] == '.') {
        return true;
      }
    }
    return false;
  };
  bool can = true;
  if (!reachable(a, c) || !reachable(b, d)) {
    can = false;
  }
  if (c > d) {
    if (!hasg3(b - 1, d + 1)) {
      can = false;
    }
  }
  cout << (can ? "Yes" : "No") << endl;
  return 0;
}

Score : 400 points

Problem Statement

There are N squares arranged in a row, numbered 1, 2, ..., N from left to right.
You are given a string S of length N consisting of . and #. If the i-th character of S is #, Square i contains a rock; if the i-th character of S is ., Square i is empty.

In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

S is a string of length N consisting of . and #.

1 \leq A, B, C, D \leq N

Square A, B, C and D do not contain a rock.

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

Yes


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

int main(){
  int N, A, B, C, D;
  string S;

  cin >> N >> A >> B >> C >> D;
  cin >> S;

  vector<int> rock;
  vector<int> jump;

  for(int i=0; i<N-1; i++){

    if(S.at(i) == '#' && S.at(i+1) == '#')
      rock.push_back(i+1);

    if(i != 0){
      if(S.at(i-1) == '.' && S.at(i) == '.' && S.at(i+1) == '.')
        jump.push_back(i+1);
    }

  }

  bool flag = false;

  for(int i=0; i<rock.size(); i++){

    if(rock.at(i) > A && rock.at(i) < C){
      flag = true; break;
    }
    if(rock.at(i) > B && rock.at(i) < D){
      flag = true; break;
    }

  }

  if(C > D){
    //入れ替えが必要
    flag = true;
    for(int i=0; i<jump.size(); i++){

      if(jump.at(i) > B && jump.at(i) <= D){
        flag = false; break;
      }

    }

  }

  if(flag)
    cout << "No" << endl;
  else
    cout << "Yes" << endl;

}


#include <iostream>
#include <cassert>
#include <climits>
#include <bitset>
#include <stack>
#include <queue>
#include <iomanip>
#include <limits>
#include <string>
#include <cmath>
#include <set>
#include <map>
#include <math.h>
#include <algorithm>
#include <vector>
#include <string.h>
#include <tuple>
#include <time.h>
#include <random>

using namespace std;

typedef long long ll;
typedef pair<ll,ll> P;

long long int INF = 3e18;
double Pi = 3.1415926535897932384626;

vector<ll> G[500005];
//vector<P> tree[500010];
priority_queue <ll> pql;
priority_queue <P> pqp;
//big priority queue
priority_queue <ll,vector<ll>,greater<ll> > pqls;
priority_queue <P,vector<P>,greater<P> > pqps;
//small priority queue
//top pop

int dx[8]={1,0,-1,0,1,1,-1,-1};
int dy[8]={0,1,0,-1,1,-1,-1,1};
char dir[] = "DRUL";
//ll bit[500005];
//↓,→,↑,←

#define p(x) cout<<x<<endl;
#define el cout<<endl;
#define pe(x) cout<<(x)<<" ";
#define ps(x) cout<<fixed<<setprecision(25)<<x<<endl;
#define pu(x) cout<<(x);
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define deba(x) cout<< #x << " = " << x <<endl

ll mod = 1000003;
ll rui(ll number1,ll number2){

    if(number2 == 0){
        return 1;
    }else{
        ll number3 = rui(number1,number2 / 2);
        number3 *= number3;
        number3 %= mod;
        if(number2%2==1){
            number3 *= number1;
            number3 %= mod;
        }
        return number3;
    }
}
ll gcd(ll number1,ll number2){

    if(number1 > number2){
        swap(number1,number2);
    }
    if(number1 == 0 || number1 == number2){
        return number2;
    }else{
        return gcd(number2 % number1,number1);
    }
}
void YES(bool condition){

    if(condition){
        p("YES");
    }else{
        p("NO");
    }
    return;
}
void Yes(bool condition){

    if(condition){
        p("Yes");
    }else{
        p("No");
    }
    return;
}

/*
void c3_init(){
    fact[0] = rfact[0] = 1;
    for(ll i=1; i<=800000; i++){
        fact[i] = (fact[i-1]*i) % mod;
    }
	rfact[800000] = rui(fact[800000],mod - 2);
	for(ll i=800000; i>=1; i--){
	   rfact[i-1] = rfact[i] * i;
	   rfact[i-1] %= mod;
	}
	return;}
ll c3(ll n,ll r){
    return (((fact[n] * rfact[r]) % mod) * rfact[n-r]) % mod;}
*/

ll n,m,num,sum,ans,a,b,c,d,e,g,h,w,i,j,k,q,l,r;
ll x[500005],y[500005],z[500005];
char s[500005],t[500005];
//bool used[500005];
bool flag,dame;
P table[500005];

int main(){
	cin >> n >> k;
    for(i=0;i<n;i++){
        cin >> x[i] >> y[i] >> z[i];
    }
    for(i=0;i<n;i++){
        ll buppa,sabo;
        buppa = z[i] * (k - x[i]);
        sabo = y[i] * x[i];
        table[i].first = buppa + sabo;
        sum -= sabo;
        table[i].second = i;
    }
    sort(table,table+n);
    reverse(table,table+n);
    for(i=0;i<n;i++){
        if(sum >= 0){
            p(ans);
            return 0;
        }
        if(sum + table[i].first < 0){
            ans += k;
            sum += table[i].first;
        }else{
            num = k;
            for(j=0;j<n;j++){
                //if(j > i)break;
                ll idx = table[j].second;
                if(sum + y[idx] * x[idx] + (k-x[idx]) * z[idx] < 0){
                    continue;
                }else if(sum + y[idx] * x[idx] >= 0){
                    sum *= -1;
                    num = min(num,(sum + y[idx] - 1) / y[idx]);
                    sum *= -1;
                }else{
                    sum += y[idx] * x[idx];
                    a = x[idx];
                    sum *= -1;
                    num = min(num,a + ((sum + z[idx] - 1) / z[idx]));
                    sum *= -1;
                    sum -= y[idx] * x[idx];
                }
            }
            ans += num;
            p(ans);
            return 0;
        }
    }

	return 0;
}

Score : 800 points

Problem Statement

Takahashi and Aoki will take N exams numbered 1 to N.
They have decided to compete in these exams.
The winner will be determined as follows:

For each exam i, Takahashi decides its importance c_i, which must be an integer between l_i and u_i (inclusive).

Let A be \sum_{i=1}^{N} c_i \times (Takahashi's score on Exam i), and B be \sum_{i=1}^{N} c_i \times (Aoki's score on Exam i). Takahashi wins if A \geq B, and Aoki wins if A < B.

Takahashi knows that Aoki will score b_i on Exam i, with his supernatural power.

Takahashi himself, on the other hand, will score 0 on all the exams without studying more. For each hour of study, he can increase his score on some exam by 1. (He can only study for an integer number of hours.)
However, he cannot score more than X on an exam, since the perfect score for all the exams is X.

Print the minimum number of study hours required for Takahashi to win.

Constraints

1 \leq N \leq 10^5

1 \leq X \leq 10^5

0 \leq b_i \leq X (1 \leq i \leq N)

1 \leq l_i \leq u_i \leq 10^5 (1 \leq i \leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
b_1 l_1 u_1
b_2 l_2 u_2
:
b_N l_N u_N

Output

Print the minimum number of study hours required for Takahashi to win.

Sample Input 1

2 100
85 2 3
60 1 1

Sample Output 1

115

One optimal strategy is as follows:

Choose c_1 = 3, c_2 = 1.

Study to score 100 on Exam 1 and 15 on Exam 2.

Then, A = 3 \times 100 + 1 \times 15 = 315, B = 3 \times 85 + 1 \times 60 = 315 and Takahashi will win.

Sample Input 2

2 100
85 2 3
60 10 10

Sample Output 2

77

Sample Input 3

1 100000
31415 2718 2818

Sample Output 3

31415

Sample Input 4

10 1000
451 4593 6263
324 310 6991
378 1431 7068
71 1757 9218
204 3676 4328
840 6221 9080
684 1545 8511
709 5467 8674
862 6504 9835
283 4965 9980

Sample Output 4

2540


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

#define ll long long

using namespace std;

void next(int array[], int size){
    for(int i = 1; i <= size; i++){
        if(array[i] == 0){
            array[i] = 1;
            break;
        }else{
            array[i] = 0;
        }
    }
}

int main(){

    int n,m;
    cin >> n >> m;
    vector<vector<int>> s;
    vector<int> p;

    for(int i = 0; i < m; i++){
        int k;
        cin >> k;
        vector<int> tmpv;
        for(int j = 0; j < k; j++){
            int tmps;
            cin >> tmps;
            tmpv.push_back(tmps);

        }
        s.push_back(tmpv);
    }

    for(int i = 0; i < m; i++){
        int tmp;
        cin >> tmp;
        p.push_back(tmp);
    }

    int count = 1;

    for(int i = 0; i < n; i++) count = count * 2;

    int ans = 0;
    int onoff[11] = {};

    for(int i = 0; i < count; i++){
        bool b = true;

        for(int j = 1; j <= m; j++){
            //jは電球の番号
            int tmpc = 0;
            vector<int> tmpv = s[j - 1];

            //つながっているスイッチのonの数を数える
            for(int k = 0; k < tmpv.size(); k++){
                if(onoff[tmpv[k]] == 1) tmpc++;
            }

            if(tmpc % 2 != p[j - 1]){
                b = false;
                break;
            }
        }

        if(b) ans++;

        next(onoff, n);
    }

    cout << ans << endl;

    return 0;

}

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

2 3
2 1 2
1 1
1 2
0 0 1

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


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

int main(){
  int r,D,x;
  cin >>r >>D >>x;
  rep(i,10){
    x = r*x - D;
    cout << x << endl;
  }
  return 0;
}

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


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

int main() {
  int n, m;
  cin >> n >> m;
  vector<int> l(m), r(m);
  for(int i=0; i<m; i++) {
    cin >> l.at(i) >> r.at(i);
  }

  int L = l.at(0);
  int R = r.at(0);

  for(int i=0; i<m; i++) {
    L = max(L, l.at(i));
    R = min(R, r.at(i));
  }
  if(R >= L) {
    cout << R - L + 1 << endl;
  }
  else {
    cout << 0 << endl;
  }
}

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


#include <bits/stdc++.h>

using namespace std;

int main() {
    int n,m;
    int t[100002] = {};
    cin >> n >> m;
    for(int i=0;i<m;++i) {
        int l, r;
        cin >> l >> r;
        t[l-1]++;
        t[r]--;
    }
    int ans = 0;
    for(int i=0;i<n;++i) {
        if(t[i] == m) ans++;
        t[i+1] += t[i];
    }
    cout << ans << endl;
    return 0;
}