A lot of students spend their winter holidays productively. Vlad has advanced very well in doing so! For three days already, fueled by salads and tangerines — the leftovers from New Year celebration — he has been calibrating his rating in his favorite MOBA game, playing as a hero named Perun.Perun has an ultimate ability called "Thunderwrath". At the instant of its activation, each enemy on the map (n of them in total) loses  health points as a single-time effect. It also has a restriction: it can only activated when the moment of time is an integer. The initial bounty for killing an enemy is . Additionally, it increases by  each second. Formally, if at some second t the ability is activated and the i-th enemy is killed as a result (i.e. his health drops to zero or lower), Vlad earns  units of gold.Every enemy can receive damage, as well as be healed. There are multiple ways of doing so, but Vlad is not interested in details. For each of n enemies he knows:    — maximum number of health points for the i-th enemy;   — initial health of the enemy (on the 0-th second);   — the amount of health the i-th enemy can regenerate per second. There also m health updates Vlad knows about:    — time when the health was updated;   — the enemy whose health was updated;   — updated health points for enemyj. Obviously, Vlad wants to maximize his profit. If it's necessary, he could even wait for years to activate his ability at the right second. Help him determine the exact second (note that it must be an integer) from 0 (inclusively) to  + ∞ so that a single activation of the ability would yield Vlad the maximum possible amount of gold, and print this amount.

In the first line, two integers are given (separated by spaces) — n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105). In the second line, there are three integers: ,  and  (, ). Each of the following n lines has three integers — , ,  (, ). The next m lines contain three integers each — , ,  (, , ). It is guaranteed that there is no more than one hearth change per second for each enemy: more formally, for each a, b so that 1 ≤ a, b ≤ m, a ≠ b holds that if , then .

Output the single integer — the maximum amount of gold Vlad can obtain if he applies "Thunderwrath" exactly once, or -1 if this amount can be infinitely large.

NoteOn the pictures you can see health points of each enemy versus time in sample cases.Periods when Vlad can kill one enemy are marked with yellow color.Periods when Vlad can kill two enemies are marked with purple color.  In the first sample case, Vlad can activate the ability at the 50-th second: the enemies 2 and 3 will die since they would have 40 and 50 health points correspondingly. Vlad will earn 2·(1000 + 50·10) = 3000 gold.  In the second sample case, the maximum amount of health for the enemy 1 is less than the damage dealt by the ability. Hence, the enemy could be killed anytime. As the bounty increases by 50 over the time, the maximum possible amount of gold is infinite.

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Hero {
    int hp, maxHp, regen;
    int lastUpdated;
}

struct Event {
    enum Type: ubyte {
        hpChanged,
        critPoint,
    }

    int time;
    Type type;
    Hero* h;
    union { int newHp, lastUpdated; }
}

int hcount, mcount;
int baseBounty, kBounty, damage;
Hero[100_000] _heroes;

long calcBounty(int time) {
    return baseBounty + long(time) * kBounty;
}

void main() {
    Array!Event events;
    while (read(hcount, mcount, baseBounty, kBounty, damage)) {
        auto heroes = _heroes[0 .. hcount];
        version (LocalProject)
            heroes[ ] = Hero.init;
        events.clear();
        events.reserve(hcount + mcount);
        foreach (ref h; heroes) {
            read(h.maxHp, h.hp, h.regen);
            assert(h.hp <= h.maxHp);
        }
        foreach (i; 0 .. mcount) {
            int time, hindex, newHp;
            read(time, hindex, newHp);
            events ~= Event(time, Event.Type.hpChanged, &heroes[hindex - 1], newHp);
        }

        auto pq = events.heapify!((a, b) => tuple(a.time, a.type) > tuple(b.time, b.type));
        int curTime = 0, prevTime = 0;

        int getEffectiveHpAt(ref const Hero h, int time) {
            return cast(int)min(h.hp + long(time - h.lastUpdated) * h.regen, h.maxHp);
        }

        bool isVictimAt(ref const Hero h, int time) {
            if (h.maxHp <= damage)
                return true;
            const hp = getEffectiveHpAt(h, time);
            return hp < damage || (hp == damage && !h.regen);
        }

        bool isSemiVictimAt(ref const Hero h, int time) {
            return h.maxHp > damage && getEffectiveHpAt(h, time) == damage && h.regen;
        }

        int victims = cast(int)heroes[ ].count!(h => isVictimAt(h, 0));
        int semi = 0;
        long maxBounty = 0;

        void processHeroRegen(ref Hero h, int newHp) {
            if (isVictimAt(h, h.lastUpdated))
                victims--;
            assert(victims >= 0);

            h.hp = newHp;
            assert(h.hp <= h.maxHp);
            if (damage > h.hp && damage < h.maxHp && h.regen) {
                const timeToRegen = (damage - h.hp + h.regen - 1) / h.regen;
                assert(timeToRegen > 0);
                pq.insert(Event(curTime + timeToRegen, Event.Type.critPoint, &h, curTime));
            }

            h.lastUpdated = curTime;
            if (isVictimAt(h, curTime))
                victims++;
            else if (isSemiVictimAt(h, curTime))
                semi++;
            assert(victims + semi <= hcount);
        }

        foreach (ref h; heroes)
            processHeroRegen(h, h.hp);

        while (!pq.empty) {
            auto e = pq.front;
            pq.removeFront();
            curTime = e.time;
            if (curTime != prevTime) {
                const option1 = (victims + semi) * calcBounty(prevTime);
                const option2 = victims * calcBounty(curTime - 1);
                debug if (max(option1, option2) > maxBounty)
                    writefln("%s | %s: v = %s, s = %s, bounty = %s | %s",
                        prevTime, curTime - 1, victims, semi, option1, option2);
                maxBounty = max(maxBounty, option1, option2);
                semi = 0;
            }

            final switch (e.type) with (Event.Type) {
            case hpChanged:
                processHeroRegen(*e.h, e.newHp);
                break;

            case critPoint:
                if (e.lastUpdated == e.h.lastUpdated)
                    processHeroRegen(*e.h, getEffectiveHpAt(*e.h, curTime));
                break;
            }

            debug writefln("%s: stats = [%(%(%s/%), %)]",
                curTime,
                heroes[ ].map!(h => [getEffectiveHpAt(h, curTime), h.maxHp]),
            );
            prevTime = curTime;
        }
        maxBounty = max(maxBounty, (victims + semi) * calcBounty(prevTime));
        if (kBounty && heroes[ ].any!(h => h.maxHp <= damage || (!h.regen && h.hp <= damage)))
            write("-1\n");
        else
            writeln(maxBounty);
        debug writeln();
    }

    stdout.flush();
    _Exit(0);
}

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    enum spec = ' ' ~ replicate("%s ", vars.length);
    return readf(spec, getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Hero {
    int hp, maxHp, regen;
    int lastUpdated;
}

struct Event {
    enum Type: ubyte {
        hpChanged,
        critPoint,
    }

    int time;
    Type type;
    Hero* h;
    union { int newHp, lastUpdated; }
}

int hcount, mcount;
int baseBounty, kBounty, damage;
Hero[100_000] _heroes;

long calcBounty(int time) {
    return baseBounty + long(time) * kBounty;
}

void main() {
    Array!Event events;
    while (read(hcount, mcount, baseBounty, kBounty, damage)) {
        auto heroes = _heroes[0 .. hcount];
        version (LocalProject)
            heroes[ ] = Hero.init;
        events.clear();
        events.reserve(hcount + mcount);
        foreach (ref h; heroes) {
            read(h.maxHp, h.hp, h.regen);
            assert(h.hp <= h.maxHp);
        }
        foreach (i; 0 .. mcount) {
            int time, hindex, newHp;
            read(time, hindex, newHp);
            events ~= Event(time, Event.Type.hpChanged, &heroes[hindex - 1], newHp);
        }

        auto pq = events.heapify!((a, b) => tuple(a.time, a.type) > tuple(b.time, b.type));
        int curTime = 0, prevTime = 0;

        int getEffectiveHpAt(ref const Hero h, int time) {
            return cast(int)min(h.hp + long(time - h.lastUpdated) * h.regen, h.maxHp);
        }

        bool isVictimAt(ref const Hero h, int time) {
            if (h.maxHp <= damage)
                return true;
            const hp = getEffectiveHpAt(h, time);
            return hp < damage || (hp == damage && !h.regen);
        }

        bool isSemiVictimAt(ref const Hero h, int time) {
            return h.maxHp > damage && getEffectiveHpAt(h, time) == damage && h.regen;
        }

        int victims = cast(int)heroes[ ].count!(h => isVictimAt(h, 0));
        int semi = 0;
        long maxBounty = 0;

        void processHeroRegen(ref Hero h, int newHp) {
            if (isVictimAt(h, h.lastUpdated))
                victims--;
            assert(victims >= 0);

            h.hp = newHp;
            assert(h.hp <= h.maxHp);
            if (damage > h.hp && damage < h.maxHp && h.regen) {
                const timeToRegen = (damage - h.hp + h.regen - 1) / h.regen;
                assert(timeToRegen > 0);
                pq.insert(Event(curTime + timeToRegen, Event.Type.critPoint, &h, curTime));
            }

            h.lastUpdated = curTime;
            if (isVictimAt(h, curTime))
                victims++;
            else if (isSemiVictimAt(h, curTime))
                semi++;
            assert(victims + semi <= hcount);
        }

        foreach (ref h; heroes)
            processHeroRegen(h, h.hp);

        while (!pq.empty) {
            auto e = pq.front;
            pq.removeFront();
            curTime = e.time;
            if (curTime != prevTime) {
                const option1 = (victims + semi) * calcBounty(prevTime);
                const option2 = victims * calcBounty(curTime - 1);
                debug if (max(option1, option2) > maxBounty)
                    writefln("%s | %s: v = %s, s = %s, bounty = %s | %s",
                        prevTime, curTime - 1, victims, semi, option1, option2);
                maxBounty = max(maxBounty, option1, option2);
                semi = 0;
            }

            final switch (e.type) with (Event.Type) {
            case hpChanged:
                processHeroRegen(*e.h, e.newHp);
                break;

            case critPoint:
                if (e.lastUpdated == e.h.lastUpdated)
                    processHeroRegen(*e.h, getEffectiveHpAt(*e.h, curTime));
                break;
            }

            debug writefln("%s: stats = [%(%(%s/%), %)]",
                curTime,
                heroes[ ].map!(h => [getEffectiveHpAt(h, curTime), h.maxHp]),
            );
            prevTime = curTime;
        }
        maxBounty = max(maxBounty, (victims + semi) * calcBounty(prevTime));
        if (kBounty && heroes[ ].any!(h => h.maxHp <= damage || (!h.regen && h.hp <= damage)))
            write("-1\n");
        else
            writeln(maxBounty);
        debug writeln();
    }

    stdout.flush();
    _Exit(0);
}

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Hero {
    int hp, maxHp, regen;
    int lastUpdated;
}

struct Event {
    enum Type: ubyte {
        hpChanged,
        critPoint,
    }

    int time;
    Type type;
    Hero* h;
    union { int newHp, lastUpdated; }
}

int hcount, mcount;
int baseBounty, kBounty, damage;
Hero[100_000] _heroes;

long calcBounty(int time) {
    return baseBounty + long(time) * kBounty;
}

void main() {
    Array!Event events;
    while (read(hcount, mcount, baseBounty, kBounty, damage)) {
        auto heroes = _heroes[0 .. hcount];
        events.clear();
        events.reserve(hcount + mcount);
        foreach (ref h; heroes) {
            read(h.maxHp, h.hp, h.regen);
            assert(h.hp <= h.maxHp);
        }
        foreach (i; 0 .. mcount) {
            int time, hindex, newHp;
            read(time, hindex, newHp);
            events ~= Event(time, Event.Type.hpChanged, &heroes[hindex - 1], newHp);
        }

        auto pq = events.heapify!((a, b) => tuple(a.time, a.type) > tuple(b.time, b.type));
        int curTime = 0, prevTime = 0;

        int getEffectiveHpAt(ref const Hero h, int time) {
            return cast(int)min(h.hp + long(time - h.lastUpdated) * h.regen, h.maxHp);
        }

        bool isVictimAt(ref const Hero h, int time) {
            if (h.maxHp <= damage)
                return true;
            const hp = getEffectiveHpAt(h, time);
            return hp < damage || (hp == damage && !h.regen);
        }

        bool isSemiVictimAt(ref const Hero h, int time) {
            return h.maxHp > damage && getEffectiveHpAt(h, time) == damage && h.regen;
        }

        int victims = cast(int)heroes[ ].count!(h => isVictimAt(h, 0));
        int semi = cast(int)heroes[ ].count!(h => isSemiVictimAt(h, 0));
        long maxBounty = 0;

        void processHeroRegen(ref Hero h, int newHp, bool allowLoop = true) {
            if (isVictimAt(h, h.lastUpdated))
                victims--;
            assert(victims >= 0);

            h.hp = newHp;
            assert(h.hp <= h.maxHp);
            if (damage >= h.hp && damage < h.maxHp && h.regen && (damage > h.hp || allowLoop)) {
                const timeToRegen = (damage - h.hp + h.regen - 1) / h.regen;
                assert(timeToRegen >= 0);
                pq.insert(Event(curTime + timeToRegen, Event.Type.critPoint, &h, curTime));
            }

            h.lastUpdated = curTime;
            if (isVictimAt(h, curTime))
                victims++;
            else if (isSemiVictimAt(h, curTime))
                semi++;
            assert(victims + semi <= hcount);
        }

        foreach (ref h; heroes)
            processHeroRegen(h, h.hp);

        while (!pq.empty) {
            auto e = pq.front;
            pq.removeFront();
            curTime = e.time;
            if (curTime != prevTime) {
                const option1 = (victims + semi) * calcBounty(prevTime);
                const option2 = victims * calcBounty(curTime - 1);
                debug if (max(option1, option2) > maxBounty)
                    writefln("%s | %s: v = %s, s = %s, bounty = %s | %s",
                        prevTime, curTime - 1, victims, semi, option1, option2);
                maxBounty = max(maxBounty, option1, option2);
                semi = 0;
            }

            final switch (e.type) with (Event.Type) {
            case hpChanged:
                processHeroRegen(*e.h, e.newHp);
                break;

            case critPoint:
                if (e.lastUpdated == e.h.lastUpdated)
                    processHeroRegen(*e.h, getEffectiveHpAt(*e.h, curTime), false);
                break;
            }

            debug writefln("%s: stats = [%(%(%s/%), %)]",
                curTime,
                heroes[ ].map!(h => [getEffectiveHpAt(h, curTime), h.maxHp]),
            );
            prevTime = curTime;
        }
        maxBounty = max(maxBounty, (victims + semi) * calcBounty(prevTime));
        if (heroes[ ].any!(h => h.maxHp <= damage || (!h.regen && h.hp <= damage)))
            write("-1\n");
        else
            writeln(maxBounty);
        debug writeln();
    }

    stdout.flush();
    _Exit(0);
}

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Hero {
    int hp, maxHp, regen;
    int lastUpdated;
}

struct Event {
    enum Type: ubyte {
        hpChanged,
        critPoint,
    }

    int time;
    Type type;
    Hero* h;
    union { int newHp, lastUpdated; }
}

int hcount, mcount;
int baseBounty, kBounty, damage;
Hero[100_000] _heroes;

long calcBounty(int time) {
    return baseBounty + long(time) * kBounty;
}

void main() {
    Array!Event events;
    while (read(hcount, mcount, baseBounty, kBounty, damage)) {
        auto heroes = _heroes[0 .. hcount];
        events.clear();
        events.reserve(hcount + mcount);
        foreach (ref h; heroes) {
            read(h.maxHp, h.hp, h.regen);
            assert(h.hp <= h.maxHp);
        }
        foreach (i; 0 .. mcount) {
            int time, hindex, newHp;
            read(time, hindex, newHp);
            events ~= Event(time, Event.Type.hpChanged, &heroes[hindex - 1], newHp);
        }
        if (kBounty && heroes[ ].any!(h => h.maxHp <= damage)) {
            write("-1\n");
            debug writeln();
            continue;
        }

        auto pq = events.heapify!((a, b) => tuple(a.time, a.type) > tuple(b.time, b.type));
        int curTime = 0, prevTime = 0;

        int getEffectiveHpAt(ref const Hero h, int time) {
            return cast(int)min(h.hp + long(time - h.lastUpdated) * h.regen, h.maxHp);
        }

        bool isVictimAt(ref const Hero h, int time) {
            if (h.maxHp <= damage)
                return true;
            const hp = getEffectiveHpAt(h, time);
            return hp < damage || (hp == damage && !h.regen);
        }

        bool isSemiVictimAt(ref const Hero h, int time) {
            return h.maxHp > damage && getEffectiveHpAt(h, time) == damage && h.regen;
        }

        int victims = cast(int)heroes[ ].count!(h => isVictimAt(h, 0));
        int semi = cast(int)heroes[ ].count!(h => isSemiVictimAt(h, 0));
        long maxBounty = 0;

        void processHeroRegen(ref Hero h, int newHp, bool allowLoop = true) {
            if (isVictimAt(h, h.lastUpdated))
                victims--;
            assert(victims >= 0);

            h.hp = newHp;
            assert(h.hp <= h.maxHp);
            if (damage >= h.hp && damage < h.maxHp && h.regen && (damage > h.hp || allowLoop)) {
                const timeToRegen = (damage - h.hp + h.regen - 1) / h.regen;
                assert(timeToRegen >= 0);
                pq.insert(Event(curTime + timeToRegen, Event.Type.critPoint, &h, curTime));
            }

            h.lastUpdated = curTime;
            if (isVictimAt(h, curTime))
                victims++;
            else if (isSemiVictimAt(h, curTime))
                semi++;
            assert(victims + semi <= hcount);
        }

        foreach (ref h; heroes)
            processHeroRegen(h, h.hp);

        while (!pq.empty) {
            auto e = pq.front;
            pq.removeFront();
            curTime = e.time;
            if (curTime != prevTime) {
                const option1 = (victims + semi) * calcBounty(prevTime);
                const option2 = victims * calcBounty(curTime - 1);
                debug if (max(option1, option2) > maxBounty)
                    writefln("%s | %s: v = %s, s = %s, bounty = %s | %s",
                        prevTime, curTime - 1, victims, semi, option1, option2);
                maxBounty = max(maxBounty, option1, option2);
                semi = 0;
            }

            final switch (e.type) with (Event.Type) {
            case hpChanged:
                processHeroRegen(*e.h, e.newHp);
                break;

            case critPoint:
                if (e.lastUpdated == e.h.lastUpdated)
                    processHeroRegen(*e.h, getEffectiveHpAt(*e.h, curTime), false);
                break;
            }

            debug writefln("%s: stats = [%(%(%s/%), %)]",
                curTime,
                heroes[ ].map!(h => [getEffectiveHpAt(h, curTime), h.maxHp]),
            );
            prevTime = curTime;
        }
        maxBounty = max(maxBounty, (victims + semi) * calcBounty(prevTime));
        writeln(maxBounty);
        debug writeln();
    }

    stdout.flush();
    _Exit(0);
}

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Hero {
    int hp, maxHp, regen;
    int lastUpdated;
}

struct Event {
    enum Type: ubyte {
        hpChanged,
        critPoint,
    }

    int time;
    Type type;
    Hero* h;
    union { int newHp, lastUpdated; }
}

int hcount, mcount;
int baseBounty, kBounty, damage;
Hero[100_000] _heroes;

long calcBounty(int time) {
    return baseBounty + long(time) * kBounty;
}

void main() {
    Array!Event events;
    while (read(hcount, mcount, baseBounty, kBounty, damage)) {
        auto heroes = _heroes[0 .. hcount];
        version (LocalProject)
            heroes[ ] = Hero.init;
        events.clear();
        events.reserve(hcount + mcount);
        foreach (ref h; heroes) {
            read(h.maxHp, h.hp, h.regen);
            assert(h.hp <= h.maxHp);
        }
        foreach (i; 0 .. mcount) {
            int time, hindex, newHp;
            read(time, hindex, newHp);
            events ~= Event(time, Event.Type.hpChanged, &heroes[hindex - 1], newHp);
        }

        auto pq = events.heapify!((a, b) => tuple(a.time, a.type) > tuple(b.time, b.type));
        int curTime = 0, prevTime = 0;

        int getEffectiveHpAt(ref const Hero h, int time) {
            return cast(int)min(h.hp + long(time - h.lastUpdated) * h.regen, h.maxHp);
        }

        bool isVictimAt(ref const Hero h, int time) {
            if (h.maxHp <= damage)
                return true;
            const hp = getEffectiveHpAt(h, time);
            return hp < damage || (hp == damage && !h.regen);
        }

        bool isSemiVictimAt(ref const Hero h, int time) {
            return h.maxHp > damage && getEffectiveHpAt(h, time) == damage && h.regen;
        }

        int victims = cast(int)heroes[ ].count!(h => isVictimAt(h, 0));
        int semi = cast(int)heroes[ ].count!(h => isSemiVictimAt(h, 0));
        long maxBounty = 0;

        void processHeroRegen(ref Hero h, int newHp, bool allowLoop = true) {
            if (isVictimAt(h, h.lastUpdated))
                victims--;
            assert(victims >= 0);

            h.hp = newHp;
            assert(h.hp <= h.maxHp);
            if (damage >= h.hp && damage < h.maxHp && h.regen && (damage > h.hp || allowLoop)) {
                const timeToRegen = (damage - h.hp + h.regen - 1) / h.regen;
                assert(timeToRegen >= 0);
                pq.insert(Event(curTime + timeToRegen, Event.Type.critPoint, &h, curTime));
            }

            h.lastUpdated = curTime;
            if (isVictimAt(h, curTime))
                victims++;
            else if (isSemiVictimAt(h, curTime))
                semi++;
            assert(victims + semi <= hcount);
        }

        foreach (ref h; heroes)
            processHeroRegen(h, h.hp);

        while (!pq.empty) {
            auto e = pq.front;
            pq.removeFront();
            curTime = e.time;
            if (curTime != prevTime) {
                const option1 = (victims + semi) * calcBounty(prevTime);
                const option2 = victims * calcBounty(curTime - 1);
                debug if (max(option1, option2) > maxBounty)
                    writefln("%s | %s: v = %s, s = %s, bounty = %s | %s",
                        prevTime, curTime - 1, victims, semi, option1, option2);
                maxBounty = max(maxBounty, option1, option2);
                semi = 0;
            }

            final switch (e.type) with (Event.Type) {
            case hpChanged:
                processHeroRegen(*e.h, e.newHp);
                break;

            case critPoint:
                if (e.lastUpdated == e.h.lastUpdated)
                    processHeroRegen(*e.h, getEffectiveHpAt(*e.h, curTime), false);
                break;
            }

            debug writefln("%s: stats = [%(%(%s/%), %)]",
                curTime,
                heroes[ ].map!(h => [getEffectiveHpAt(h, curTime), h.maxHp]),
            );
            prevTime = curTime;
        }
        maxBounty = max(maxBounty, (victims + semi) * calcBounty(prevTime));
        if (kBounty && heroes[ ].any!(h => h.maxHp <= damage || (!h.regen && h.hp <= damage)))
            write("-1\n");
        else
            writeln(maxBounty);
        debug writeln();
    }

    stdout.flush();
    _Exit(0);
}

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Hero {
    int hp, maxHp, regen;
    int lastUpdated;
}

struct Event {
    enum Type: ubyte {
        hpChanged,
        critPoint,
    }

    int time;
    Type type;
    Hero* h;
    union { int newHp, lastUpdated; }
}

int hcount, mcount;
int baseBounty, kBounty, damage;
Hero[100_000] _heroes;

long calcBounty(int time) {
    return baseBounty + long(time) * kBounty;
}

void main() {
    Array!Event events;
    while (read(hcount, mcount, baseBounty, kBounty, damage)) {
        auto heroes = _heroes[0 .. hcount];
        version (LocalProject)
            heroes[ ] = Hero.init;
        events.clear();
        events.reserve(hcount + mcount);
        foreach (ref h; heroes) {
            read(h.maxHp, h.hp, h.regen);
            assert(h.hp <= h.maxHp);
        }
        foreach (i; 0 .. mcount) {
            int time, hindex, newHp;
            read(time, hindex, newHp);
            events ~= Event(time, Event.Type.hpChanged, &heroes[hindex - 1], newHp);
        }

        auto pq = events.heapify!((a, b) => tuple(a.time, a.type) > tuple(b.time, b.type));
        int curTime = 0, prevTime = 0;

        int getEffectiveHpAt(ref const Hero h, int time) {
            return cast(int)min(h.hp + long(time - h.lastUpdated) * h.regen, h.maxHp);
        }

        bool isVictimAt(ref const Hero h, int time) {
            if (h.maxHp <= damage)
                return true;
            const hp = getEffectiveHpAt(h, time);
            return hp < damage || (hp == damage && !h.regen);
        }

        bool isSemiVictimAt(ref const Hero h, int time) {
            return h.maxHp > damage && getEffectiveHpAt(h, time) == damage && h.regen;
        }

        int victims = cast(int)heroes[ ].count!(h => isVictimAt(h, 0));
        int semi = cast(int)heroes[ ].count!(h => isSemiVictimAt(h, 0));
        long maxBounty = 0;

        void processHeroRegen(ref Hero h, int newHp) {
            if (isVictimAt(h, h.lastUpdated))
                victims--;
            assert(victims >= 0);

            h.hp = newHp;
            assert(h.hp <= h.maxHp);
            if (damage > h.hp && damage < h.maxHp && h.regen) {
                const timeToRegen = (damage - h.hp + h.regen - 1) / h.regen;
                assert(timeToRegen >= 0);
                pq.insert(Event(curTime + timeToRegen, Event.Type.critPoint, &h, curTime));
            }

            h.lastUpdated = curTime;
            if (isVictimAt(h, curTime))
                victims++;
            else if (isSemiVictimAt(h, curTime))
                semi++;
            assert(victims + semi <= hcount);
        }

        foreach (ref h; heroes)
            processHeroRegen(h, h.hp);

        while (!pq.empty) {
            auto e = pq.front;
            pq.removeFront();
            curTime = e.time;
            if (curTime != prevTime) {
                const option1 = (victims + semi) * calcBounty(prevTime);
                const option2 = victims * calcBounty(curTime - 1);
                debug if (max(option1, option2) > maxBounty)
                    writefln("%s | %s: v = %s, s = %s, bounty = %s | %s",
                        prevTime, curTime - 1, victims, semi, option1, option2);
                maxBounty = max(maxBounty, option1, option2);
                semi = 0;
            }

            final switch (e.type) with (Event.Type) {
            case hpChanged:
                processHeroRegen(*e.h, e.newHp);
                break;

            case critPoint:
                if (e.lastUpdated == e.h.lastUpdated)
                    processHeroRegen(*e.h, getEffectiveHpAt(*e.h, curTime));
                break;
            }

            debug writefln("%s: stats = [%(%(%s/%), %)]",
                curTime,
                heroes[ ].map!(h => [getEffectiveHpAt(h, curTime), h.maxHp]),
            );
            prevTime = curTime;
        }
        maxBounty = max(maxBounty, (victims + semi) * calcBounty(prevTime));
        if (kBounty && heroes[ ].any!(h => h.maxHp <= damage || (!h.regen && h.hp <= damage)))
            write("-1\n");
        else
            writeln(maxBounty);
        debug writeln();
    }

    stdout.flush();
    _Exit(0);
}


One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $$$n$$$ non-negative integers.If there are exactly $$$K$$$ distinct values in the array, then we need $$$k = \lceil \log_{2} K \rceil$$$ bits to store each value. It then takes $$$nk$$$ bits to store the whole file.To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers $$$l \le r$$$, and after that all intensity values are changed in the following way: if the intensity value is within the range $$$[l;r]$$$, we don't change it. If it is less than $$$l$$$, we change it to $$$l$$$; if it is greater than $$$r$$$, we change it to $$$r$$$. You can see that we lose some low and some high intensities.Your task is to apply this compression in such a way that the file fits onto a disk of size $$$I$$$ bytes, and the number of changed elements in the array is minimal possible.We remind you that $$$1$$$ byte contains $$$8$$$ bits.$$$k = \lceil log_{2} K \rceil$$$ is the smallest integer such that $$$K \le 2^{k}$$$. In particular, if $$$K = 1$$$, then $$$k = 0$$$.

The first line contains two integers $$$n$$$ and $$$I$$$ ($$$1 \le n \le 4 \cdot 10^{5}$$$, $$$1 \le I \le 10^{8}$$$) — the length of the array and the size of the disk in bytes, respectively. The next line contains $$$n$$$ integers $$$a_{i}$$$ ($$$0 \le a_{i} \le 10^{9}$$$) — the array denoting the sound file.

Print a single integer — the minimal possible number of changed elements.

NoteIn the first example we can choose $$$l=2, r=3$$$. The array becomes 2 2 2 3 3 3, the number of distinct elements is $$$K=2$$$, and the sound file fits onto the disk. Only two values are changed.In the second example the disk is larger, so the initial file fits it and no changes are required.In the third example we have to change both 1s or both 3s.

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{
    int n, el;
    readf("%s %s", &n, &el);
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    debug { int.max.writeln; }

    int space = el * 8 / n;
    int mx = space < 31 ? 2 ^^ space : int.max;

    debug { mx.writeln; }

    auto vals = arr.sort.group.map!(v => v[1]).array;

    debug { vals.writeln; }

    int ans = n, cur = vals[0 .. min(mx, vals.length)].sum;
    foreach (i; 0 .. vals.length) {
        ans = min(ans, n - cur);

        cur -= vals[i];
        if (i + mx < vals.length) { cur += vals[i + mx]; }
    }

    ans.writeln;
}

import std.stdio;
import std.algorithm;
import std.math: pow;

const int MAX = 400005;

int n, I;
int[MAX] a;
int[MAX] count;
int[MAX] sum;

void main() {
    readf(" %s %s", n, I);
    foreach(i; 0..n) readf(" %s", a[i]);

    auto k = min(19, I * 8 / n);
    auto K = pow(2, k);

    sort(a[0..n]);
    auto m = 1;
    count[0] = 0;
    count[1] = 1;
    foreach(i; 1..n) {
        if (a[i] != a[i-1]) m++;
        count[m]++;
    }
    m++;

    foreach(i; 1..m) sum[i] = sum[i-1] + count[i];

    auto result = 0;
    foreach(i; 1..m) {
        auto j = max(0, i-K);
        result = max(result, sum[i] - sum[j]);
    }
    writeln(n - result);
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n, limit;
	while (readf (" %s %s", &n, &limit) > 0)
	{
		limit *= 8;
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		auto c = a.group.array;
		auto letters = c.length;
		auto s = [0];
		s.reserve (letters + 1);
		foreach (e; c)
		{
			s ~= s.back + e[1];
		}
		int res = n;

		int k = 0;
		int r = 1;
		while (r <= letters)
		{
			for (int i = 0, j = r; j <= letters; i++, j++)
			{
				if (n * 1L * k <= limit)
				{
					int cur = s[j] - s[i];
					res = min (res, n - cur);
				}
			}
			k += 1;
			r <<= 1;
		}
		if (n * 1L * k <= limit)
		{
			res = 0;
		}

		writeln (res);
	}
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

int N, I;
int[] A;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      I = readInt();
      A = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
      }
      A.sort;

      int k;
      for (k = N; k >= 1; --k) {
        long logK = bsr(k);
        if (k & k - 1) {
          ++logK;
        }
        debug {
          writeln(k, " ", logK);
        }
        if (N * logK <= 8 * I) {
          break;
        }
      }
      debug {
        writeln("k = ", k);
      }

      auto as = A.dup;
      as = as.sort.uniq.array;
      const asLen = cast(int)(as.length);
      auto cnt = new int[asLen];
      foreach (i; 0 .. N) {
        ++cnt[as.lowerBound(A[i])];
      }
      debug {
        writeln("cnt = ", cnt);
      }
      auto sum = new int[asLen + 1];
      foreach (j; 0 .. asLen) {
        sum[j + 1] = sum[j] + cnt[j];
      }

      int ans;
      foreach (j; 0 .. asLen) {
        chmax(ans, sum[min(j + k, asLen)] - sum[j]);
      }
      ans = N - ans;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{
    int n, el;
    readf("%s %s", &n, &el);
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    debug { int.max.writeln; }

    int space = el * 8 / n;
    int mx = space < 31 ? 2 ^^ space : int.max;

    debug { mx.writeln; }

    auto vals = arr.sort.group.map!(v => v[1]).array;

    debug { vals.writeln; }

    int ans = n, cur = vals[0 .. min(mx, vals.length)].sum;
    foreach (i; 0 .. vals.length) {
        ans = min(ans, n - cur);

        cur -= vals[i];
        if (i + mx < vals.length) { cur += vals[i + mx - 1]; }
    }

    ans.writeln;
}

import std.stdio;
import std.algorithm;
import std.math: pow;

const int MAX = 400005;

int n, I;
int[MAX] a;
int[MAX] count;
int[MAX] sum;

void main() {
    readf(" %s %s", n, I);
    foreach(i; 0..n) readf(" %s", a[i]);

    auto k = I * 8 / n;
    auto K = pow(2, k);

    sort(a[0..n]);
    auto m = 1;
    count[0] = 0;
    count[1] = 1;
    foreach(i; 1..n) {
        if (a[i] != a[i-1]) m++;
        count[m]++;
    }
    m++;

    foreach(i; 1..m) sum[i] = sum[i-1] + count[i];

    auto result = 0;
    foreach(i; 1..m) {
        auto j = max(0, i-K);
        result = max(result, sum[i] - sum[j]);
    }
    writeln(n - result);
}


The Elements of Harmony are six supernatural artifacts representing subjective aspects of harmony. They are arguably the most powerful force in Equestria. The inside of Elements of Harmony can be seen as a complete graph with n vertices labeled from 0 to n - 1, where n is a power of two, equal to 2m.  The energy in Elements of Harmony is in constant movement. According to the ancient book, the energy of vertex u in time i (ei[u]) equals to: Here b[] is the transformation coefficient — an array of m + 1 integers and f(u, v) is the number of ones in the binary representation of number (u xor v).Given the transformation coefficient and the energy distribution at time 0 (e0[]). Help Twilight Sparkle predict the energy distribution at time t (et[]). The answer can be quite large, so output it modulo p.

The first line contains three integers m, t and p (1 ≤ m ≤ 20; 0 ≤ t ≤ 1018; 2 ≤ p ≤ 109). The following line contains n (n = 2m) integers e0[i] (1 ≤ e0[i] ≤ 109; 0 ≤ i < n). The next line contains m + 1 integers b[i] (0 ≤ b[i] ≤ 109; 0 ≤ i ≤ m).

Output n lines, the i-th line must contain a single integer et[i] modulo p.

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.math, std.range;

//	Input
class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { tokens = readln.split; if (stdin.eof) throw new EOFException; } auto token = tokens[0]; tokens.popFront; return token; }
int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

//	chmin/chmax
void chmin(T)(ref T t, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

long MO;
void pl(ref long t, long f) {
	if ((t += f) >= MO) {
		t -= MO;
	}
}

int M;
long T;
long[] E;
long[] B;

long[][] bn;

long[] mul(long[] a, long[] b) {
	long[] ret = new long[M + 1];
	foreach (i; 0 .. M + 1) foreach (j; 0 .. M + 1) {
		long prod = (a[i] * b[j]) % MO;
		foreach (k; 0 .. j + 1) if (k <= i && j - k <= M - i) {
			long tmp = prod;
			(tmp *= bn[(i - k) + (j - k)][i - k]) %= MO;
			(tmp *= bn[k + ((M - i) - (j - k))][k]) %= MO;
			pl(ret[(i - k) + (j - k)], tmp);
		}
	}
	return ret;
}

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		T = readLong;
		MO = readLong;
		E = new long[1 << M];
		foreach (x; 0 .. 1 << M) {
			E[x] = readLong;
		}
		B = new long[M + 1];
		foreach (i; 0 .. M + 1) {
			B[i] = readLong;
		}

		bn = new long[][](M + 1, M + 1);
		foreach (i; 0 .. M + 1) {
			bn[i][0] = bn[i][i] = 1;
			foreach (j; 1 .. i) {
				bn[i][j] = (bn[i - 1][j - 1] + bn[i - 1][j]) % MO;
			}
		}

		long[][] dp = new long[][](M + 1, 1 << M);
		dp[0][] = E[] % MO;
		foreach (i; 0 .. M) {
			foreach_reverse (j; 0 .. i + 1) {
				foreach (x; 0 .. 1 << M) {
					pl(dp[j + 1][x ^ 1 << i], dp[j][x]);
				}
			}
		}
// writeln(dp);

		long[] bx = new long[M + 1];
		long[] by = new long[M + 1];
		bx[] = B[] % MO;
		by[0] = 1;
		for (long e = T; e; e >>= 1, bx = mul(bx, bx)) {
			if (e & 1) {
				by = mul(by, bx);
			}
		}
// writeln("by = ",by);

		foreach (x; 0 .. 1 << M) {
			long ans;
			foreach (i; 0 .. M + 1) {
				(ans += by[i] * dp[i][x]) %= MO;
			}
			writeln(ans);
		}
	}
	} catch (EOFException) {}
}


Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.

For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.

NoteLet's consider the test cases of the example:  $$$n=8$$$, $$$k=3$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$;  during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$.   $$$n=6$$$, $$$k=6$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$.   $$$n=7$$$, $$$k=1$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$;  during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$;  during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$;  during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.

import std.stdio;
import std.conv;
import std.string;
import std.algorithm;
import std.math;

void main() {
    int cases = to!int(strip(readln()));

    // per testcase
    for (int t = 0; t < cases; t++) {
        ulong n, k;
        readf!"%d %d\n"(n, k);

        ulong l = cast(ulong) ceil(log2(k));

        ulong c_i = pow(2, l+1) - (pow(2, l) - k);

        if (n <= c_i) {
            writeln(ceil(log2(n)));
            continue;
        }

        ulong c_a = n - c_i;
        ulong ceil = c_a / k + (c_a % k == 0 ? 0 : 1);
        writeln(l + ceil + 1);
    }
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		long n, k;
		readf !(" %s %s") (n, k);
		long cur = 1;
		long res = 0;
		while (cur < n && cur < k)
		{
			cur <<= 1;
			res += 1;
		}
		writeln (res + (n - cur + k - 1) / k);
	}
}


Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value ai.Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative integer power of k. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment.Help her to do so in finding the total number of such segments.

The first line of input contains two integers, n and k, the number of chemicals and the number, such that the total affection value is a non-negative power of this number k. (1 ≤ n ≤ 105, 1 ≤ |k| ≤ 10). Next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — affection values of chemicals.

Output a single integer — the number of valid segments.

NoteDo keep in mind that k0 = 1.In the first sample, Molly can get following different affection values:  2: segments [1, 1], [2, 2], [3, 3], [4, 4]; 4: segments [1, 2], [2, 3], [3, 4]; 6: segments [1, 3], [2, 4]; 8: segments [1, 4]. Out of these, 2, 4 and 8 are powers of k = 2. Therefore, the answer is 8.In the second sample, Molly can choose segments [1, 2], [3, 3], [3, 4].

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, k;
    readf("%s %s", &n, &k);
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    long[] pows;
    if (k == 1) pows ~= 1;
    else if (k == -1) pows ~= [-1, 1];
    else {
        pows ~= [1, k];
        while (abs(pows.back) < 10L ^^ 9 * 10 ^^ 5) pows ~= pows[$-1] * k;
    }

    int[long] cnt;
    cnt[0] = 1;

    long ans = 0;
    long sm = 0;
    foreach (e; arr) {
        sm += e;

        foreach (p; pows) { ans += cnt.get(sm - p, 0); }

        cnt[sm] += 1;
    }

    ans.writeln;
}

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, k;
    readf("%s %s", &n, &k);
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    long[] pows;
    if (k == 1) pows ~= 1;
    else if (k == -1) pows ~= [-1, 1];
    else {
        pows ~= [1, k];
        while (abs(pows.back) < 10L ^^ 9 * 10 ^^ 5) { pows ~= pows[$-1] * k; }
    }

    int[long] cnt;
    cnt[0] = 1;

    long ans = 0;
    long sm = 0;
    foreach (e; arr) {
        sm += e;

        foreach (p; pows) { ans += cnt.get(sm - p, 0); }

        cnt[sm] += 1;
    }

    ans.writeln;
}

import core.bitop;
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n;
	long k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		long total = a.map !(abs).sum (0L);
		long q = 1;
		long [] p;
		while (!p.canFind (q) && abs (q) <= total)
		{
			p ~= q;
			q *= k;
		}
		debug {writeln (p);}

		long res = 0;
		int [long] s;
		s[0] += 1;
		long cur = 0;
		foreach (c; a)
		{
			cur += c;
			foreach (r; p)
			{
				debug {writeln ("? ", r - cur);}
				if ((cur - r) in s)
				{
					res += s[cur - r];
				}
			}
			s[cur] += 1;
			debug {writeln (s);}
		}
		writeln (res);
	}
}

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, k;
    readf("%s %s", &n, &k);
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    long[] pows;
    pows ~= k;
    while (k != 1 && abs(pows.back) < 10L ^^ 9 * 10 ^^ 5) pows ~= pows[$-1] * k;

    int[long] cnt;
    cnt[0] = 1;

    long ans = 0;
    long sm = 0;
    foreach (e; arr) {
        sm += e;

        foreach (p; pows) { ans += cnt.get(sm - p, 0); }

        cnt[sm] += 1;
    }

    ans.writeln;
}

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, k;
    readf("%s %s", &n, &k);
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    long[] pows;
    if (k == 1) pows ~= 1;
    else if (k == -1) pows ~= [-1, 1];
    else {
        pows ~= k;
        while (abs(pows.back) < 10L ^^ 9 * 10 ^^ 5) pows ~= pows[$-1] * k;
    }

    int[long] cnt;
    cnt[0] = 1;

    long ans = 0;
    long sm = 0;
    foreach (e; arr) {
        sm += e;

        foreach (p; pows) { ans += cnt.get(sm - p, 0); }

        cnt[sm] += 1;
    }

    ans.writeln;
}


You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct.You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?

The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given. Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct.

If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO.

NoteIn the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points.

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!*******************************************/

bool trisign(tup p1, tup p2, tup p3){
    ll area2 = p1[0] * p2[1] + p2[0] * p3[1] + p3[0] * p1[1] - p1[0] * p3[1] - p3[0] * p2[1] - p2[0] * p1[1];
    /* debug writeln(p1, p2, p3, " ", area2); */
    return (area2 != 0);
}

bool check_part(tup[] partition){
    if(partition.length <= 2) return 1;
    tup fixedp = partition[0];
    tup np = partition[1];
    foreach(p; partition){
        if(trisign(fixedp, np, p)){
            return 0;
        }
    }
    return 1;
}

void play(){
    int n;
    n = rd!int;
    tup[] arr;
    ll x, y;
    foreach(i; 0..n){
        x = rd; y = rd;
        arr ~= tup(x, y);
    }

    if(n <= 4){
        writeln("YES");
        return;
    }

    tup fixedp = arr[0], np;
    // Check if any of next two points match
    foreach(j; 1..3){
        np = arr[j];
        // Partition Points
        tup[] part;
        foreach(i; 0..n){
            // Non-Collinear
            if(trisign(fixedp, np, arr[i])){
                part ~= arr[i];
            }
        }
        debug writeln(part);
        // Check other partition
        if(check_part(part)){
            writeln("YES");
            return;
        }
    }

    // Alternate Partition
    fixedp = arr[1];
    np = arr[2];
    tup[] part;
    foreach(i; 0..n){
        if(trisign(fixedp, np, arr[i])){
            part ~= arr[i];
        }
    }
    debug writeln(part);
    if(check_part(part)){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

int main(){
    long t = 1;
    /* t = rd;        // Toggle! */
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: b: 2 c: 3, 10 d: 4, 8 e: 6 f: 7 z: 1, 5, 9 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.

The single line contains a positive integer n (1 ≤ n ≤ 105) — the length of the sought string.

Print on the single line the lexicographically minimal lucky string whose length equals n.

NoteThe lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.

import std.stdio, std.string, std.conv;
import std.algorithm, std.array, std.bigint, std.math, std.range;
import core.thread;

//  Input
string[] tokens;
int tokenId = 0;
string readToken() { for (; tokenId == tokens.length; ) tokens = readln.split, tokenId = 0; return tokens[tokenId++]; }

int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

//  chmin/chmax
void chmin(T)(ref T t, T f) { if (t > f) t = f; }
void chmax(T)(ref T t, T f) { if (t < f) t = f; }

int N;
string source = "abcd";

void main () {
    N = readInt();

    foreach (int i; 0 .. N) {
        writef("%s", source[i % 4]);
    }
    writeln("");
}


After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.Help Petya to determine maximum possible total cost.

The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market. Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.

Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,std.parallelism,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.bitmanip,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,core.bitop,
	std.meta,core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;const int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	size_t lowb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' ') if(isInputRange!X)
{foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a) if(isInputRange!X && isInputRange!(typeof(a.front)))
{
	foreach(ref const i;a)
	{
		foreach(ref const j;i)write(j,' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n,m;
loop:while(read(n,m))
	{
		alias Tuple!(long,int,int) suv;
		auto dp=new suv[m+1];
		auto a=new pii[n+1];
		foreach(i;0..n)read(a[i].fi,a[i].se);
		sort!"a>b"(a);
		//debug writeln(a);
		int pos2=0,pos1=0;
		while(pos2<n && a[pos2].fi>2)pos2++;
		while(pos1<n && a[pos1].fi>1)pos1++;
		debug writeln(pos2,' ',pos1);
		foreach(i;0..m)
		{
			if(i+2<=m && pos2+dp[i][1]<pos1)
			{
				suv x=dp[i];
				x[0]=dp[i][0]+a[pos2+dp[i][1]].se;
				x[1]=dp[i][1]+1;
				dp[i+2]=max(dp[i+2],x);
			}
			if(i+1<=m && pos1+dp[i][2]<n)
			{
				suv x=dp[i];
				x[0]=dp[i][0]+a[pos1+dp[i][2]].se;
				x[2]=dp[i][2]+1;
				dp[i+1]=max(dp[i+1],x);
			}
		}
		foreach(i;1..m+1)dp[i]=max(dp[i],dp[i-1]);
		long ans,s;
		foreach(i;dp)ans=max(ans,i[0]);
		foreach(i;0..pos2)
		{
			if(3*(i+1)>m)break;
			s+=a[i].se;
			ans=max(ans,s+dp[m-3*(i+1)][0]);
		}
		writeln(ans);
	}
}

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,std.parallelism,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.bitmanip,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,core.bitop,
	std.meta,core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;const int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	size_t lowb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' ') if(isInputRange!X)
{foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a) if(isInputRange!X && isInputRange!(typeof(a.front)))
{
	foreach(ref const i;a)
	{
		foreach(ref const j;i)write(j,' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n,m;
loop:while(read(n,m))
	{
		alias Tuple!(long,int,int) suv;
		auto dp=new suv[m+1];
		auto a=new pii[n+1];
		foreach(i;0..n)read(a[i].fi,a[i].se);
		sort!"a>b"(a);
		int pos2=0,pos1=0;
		while(pos2<n && a[pos2].fi>2)pos2++;
		while(pos1<n && a[pos1].fi>1)pos1++;
		foreach(i;0..m)
		{
			if(i+2<=m && pos2+dp[i][1]<pos1)
			{
				suv x=dp[i];
				x[0]=dp[i][0]+a[pos2+dp[i][1]].se;
				x[1]=dp[i][1]+1;
				dp[i+2]=max(dp[i+2],x);
			}
			if(i+1<=m && pos1+dp[i][2]<n)
			{
				suv x=dp[i];
				x[0]=dp[i][0]+a[pos1+dp[i][2]].se;
				x[2]=dp[i][2]+1;
				dp[i+1]=max(dp[i+1],x);
			}
		}
		long ans,s;
		foreach(i;dp)ans=max(ans,i[0]);
		foreach(i;0..pos2)
		{
			if(3*(i+1)>m)break;
			s+=a[i].se;
			ans=max(ans,s+dp[m-3*(i+1)][0]);
		}
		writeln(ans);
	}
}

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,std.parallelism,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.bitmanip,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,core.bitop,
	std.meta,core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;const int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	size_t lowb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' ') if(isInputRange!X)
{foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a) if(isInputRange!X && isInputRange!(typeof(a.front)))
{
	foreach(ref const i;a)
	{
		foreach(ref const j;i)write(j,' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n,m;
loop:while(read(n,m))
	{
		alias Tuple!(long,int,int) suv;
		auto dp=new suv[m+1];
		auto a=new pii[n+1];
		foreach(i;0..n)read(a[i].fi,a[i].se);
		sort!"a>b"(a);
		int pos2=0,pos1=0;
		while(pos2<n && a[pos2].fi>2)pos2++;
		while(pos1<n && a[pos1].fi>1)pos1++;
		foreach(i;0..m)
		{
			if(i+2<=m && pos2+dp[i][2]<pos1)
			{
				suv x=dp[i];
				x[0]=dp[i][0]+a[pos2+dp[i][2]].se;
				x[2]=dp[i][2]+1;
				dp[i+2]=max(dp[i+2],x);
			}
			if(i+1<=m && pos1+dp[i][1]<n)
			{
				dp[i+1]=max(dp[i+1],tuple(dp[i][0]+a[pos1+dp[i][1]].se,dp[i][1]+1,dp[i][2]));
			}
		}
		long ans,s;
		foreach(i;dp)ans=max(ans,i[0]);
		foreach(i;0..pos2)
		{
			if(3*(i+1)>m)break;
			s+=a[i].se;
			ans=max(ans,s+dp[m-3*(i+1)][0]);
		}
		writeln(ans);
	}
}


Dreamoon likes coloring cells very much.There is a row of $$$n$$$ cells. Initially, all cells are empty (don't contain any color). Cells are numbered from $$$1$$$ to $$$n$$$.You are given an integer $$$m$$$ and $$$m$$$ integers $$$l_1, l_2, \ldots, l_m$$$ ($$$1 \le l_i \le n$$$)Dreamoon will perform $$$m$$$ operations.In $$$i$$$-th operation, Dreamoon will choose a number $$$p_i$$$ from range $$$[1, n-l_i+1]$$$ (inclusive) and will paint all cells from $$$p_i$$$ to $$$p_i+l_i-1$$$ (inclusive) in $$$i$$$-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.Dreamoon hopes that after these $$$m$$$ operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose $$$p_i$$$ in each operation to satisfy all constraints.

The first line contains two integers $$$n,m$$$ ($$$1 \leq m \leq n \leq 100\,000$$$). The second line contains $$$m$$$ integers $$$l_1, l_2, \ldots, l_m$$$ ($$$1 \leq l_i \leq n$$$).

If it's impossible to perform $$$m$$$ operations to satisfy all constraints, print "'-1" (without quotes). Otherwise, print $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \leq p_i \leq n - l_i + 1$$$), after these $$$m$$$ operations, all colors should appear at least once and all cells should be colored. If there are several possible solutions, you can print any.

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto l = RDA;

	auto len = l.sum;
	auto d = len - n;
	if (d < 0)
		writeln(-1);
	else
	{
		bool ok = true;
		auto ans = new int[](m);
		int pos = 1;
		long r;
		foreach (i; 0..m)
		{
			if (l[i] > n-i)
			{
				ok = false;
				break;
			}
			ans[i] = pos - cast(int)r;
			r = min(l[i]-1, d);
			d -= r;
			pos = ans[i] + cast(int)l[i];
			if (pos > n+1)
			{
				ok = false;
				break;
			}
		}
		debug writeln(ans);
		if (ok)
			ans.map!(to!string).join(" ").writeln;
		else
			writeln(-1);
	}

	stdout.flush;
	debug readln;
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n, m;
multitest_loop:
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;
		auto len = readln.splitter.map !(to !(int)).array;
		auto total = sum (len, 0L);
		if (total < n)
		{
			writeln (-1);
			continue multitest_loop;
		}
		foreach (i; 0..m)
		{
			if (len[i] > n - i)
			{
				writeln (-1);
				continue multitest_loop;
			}
		}

		long [] ans;
		ans.reserve (m);
		foreach (i; 0..m)
		{
			long pos = max (i, n - total);
			ans ~= pos + 1;
			total -= len[i];
		}
		writefln !("%(%s %)") (ans);
	}
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    int n = scan!int, m = scan!int;
    int[] ls = scan!int(m);

    foreach(i; 0 .. m){
        if(i + ls[i] > n){
            "-1".writeln;
            return;
        }
    }

    long sum = ls.to!(long[]).sum;
    if(sum < n.to!long){
        "-1".writeln;
        return;
    }

    int[] ans;
    foreach(i; 0 .. m) ans ~= i + 1;

    ans[m - 1] = n - ls[m - 1] + 1;
    foreach_reverse(i; 0 .. m - 1){
        if(ans[i] + ls[i] < ans[i + 1]) ans[i] = ans[i + 1] - ls[i];
    }

    ans.unsplit.print;
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

void main() {
  try {
    for (; ; ) {
      const N = readLong();
      const M = readInt();
      auto L = new long[M];
      foreach (i; 0 .. M) {
        L[i] = readLong();
      }

      auto LSum = new long[M + 1];
      foreach (i; 0 .. M) {
        LSum[i + 1] = LSum[i] + L[i];
      }

      long[] ans;
      if (LSum[M] >= N) {
        ans = new long[M];
        long bef = -1;
        foreach (i; 0 .. M) {
          /*
            bef < p
            p + L[i] <= N
            p + L[i] + ... + L[M - 1] >= N
          */
          ans[i] = max(bef + 1, N - (LSum[M] - LSum[i]));
          if (!(ans[i] + L[i] <= N)) {
            ans = [];
            break;
          }
          bef = ans[i];
        }
      }

      if (!ans.empty) {
        foreach (i; 0 .. M) {
          if (i > 0) write(" ");
          write(ans[i] + 1);
        }
        writeln();
      } else {
        writeln(-1);
      }

      debug {
        long[] brt;
        foreach (h; 0 .. N^^M) {
          auto ps = iota(M).map!(i => (h / N^^i % N)).array;
          bool ok = true;
          auto col = new int[cast(int)(N)];
          col[] = -1;
          foreach (i; 0 .. M) {
            if (ps[i] + L[i] <= N) {
              col[cast(int)(ps[i]) .. cast(int)(ps[i] + L[i])] = i;
            } else {
              ok = false;
              break;
            }
          }
          ok = ok && (col.count(-1) == 0);
          foreach (i; 0 .. M) {
            ok = ok && (col.count(i) != 0);
          }
          if (ok) {
            brt = ps;
            break;
          }
        }
        writeln("brt = ", brt);
        assert((!ans.empty) == (!brt.empty));
      }
    }
  } catch (EOFException e) {
  }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto l = RDA!int;

	auto len = l.sum;
	auto d = len - n;
	if (d < 0)
		writeln(-1);
	else
	{
		auto ans = new int[](m);
		int pos = 1;
		int r;
		foreach (i; 0..m)
		{
			ans[i] = pos - r;
			r = min(l[i]-1, d);
			d -= r;
			pos = ans[i] + l[i];
		}
		ans.map!(to!string).join(" ").writeln;
	}

	stdout.flush;
	debug readln;
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto l = RDA!int;

	auto len = l.sum;
	auto d = len - n;
	if (d < 0)
		writeln(-1);
	else
	{
		bool ok = true;
		auto ans = new int[](m);
		int pos = 1;
		int r;
		foreach (i; 0..m)
		{
			ans[i] = pos - r;
			r = min(l[i]-1, d);
			d -= r;
			pos = ans[i] + l[i];
			if (pos > n+1)
				ok = false;
		}
		debug writeln(ans);
		if (ok)
			ans.map!(to!string).join(" ").writeln;
		else
			writeln(-1);
	}

	stdout.flush;
	debug readln;
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto l = RDA!int;

	auto len = l.sum;
	auto d = len - n;
	if (d < 0)
		writeln(-1);
	else
	{
		bool ok = true;
		auto ans = new int[](m);
		int pos = 1;
		int r;
		auto index = l.MAKE_IDX!"a > b"();
		foreach (i; index)
		{
			ans[i] = pos - r;
			r = min(l[i]-1, d);
			d -= r;
			pos = ans[i] + l[i];
			if (pos > n+1)
				ok = false;
		}
		debug writeln(ans);
		if (ok)
			ans.map!(to!string).join(" ").writeln;
		else
			writeln(-1);
	}

	stdout.flush;
	debug readln;
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto l = RDA!int;

	auto len = l.sum;
	auto d = len - n;
	if (d < 0)
		writeln(-1);
	else
	{
		bool ok = true;
		auto ans = new int[](m);
		int pos = 1;
		int r;
		foreach (i; 0..m)
		{
			ans[i] = pos - r;
			r = min(l[i]-1, d);
			d -= r;
			pos = ans[i] + l[i];
			if (pos > n)
				ok = false;
		}
		if (ok)
			ans.map!(to!string).join(" ").writeln;
		else
			writeln(-1);
	}

	stdout.flush;
	debug readln;
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto l = RDA!int;

	auto len = l.sum;
	auto d = len - n;
	if (d < 0)
		writeln(-1);
	else
	{
		bool ok = true;
		auto ans = new int[](m);
		int pos = 1;
		int r;
		foreach (i; 0..m)
		{
			if (l[i] > n-i)
			{
				ok = false;
				break;
			}
			ans[i] = pos - r;
			r = min(l[i]-1, d);
			d -= r;
			pos = ans[i] + l[i];
			if (pos > n+1)
			{
				ok = false;
				break;
			}
		}
		debug writeln(ans);
		if (ok)
			ans.map!(to!string).join(" ").writeln;
		else
			writeln(-1);
	}

	stdout.flush;
	debug readln;
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      auto L = new int[M];
      foreach (i; 0 .. M) {
        L[i] = readInt();
      }

      auto LSum = new int[M + 1];
      foreach (i; 0 .. M) {
        LSum[i + 1] = LSum[i] + L[i];
      }

      int[] ans;
      if (LSum[M] >= N) {
        ans = new int[M];
        int bef = -1;
        foreach (i; 0 .. M) {
          /*
            bef < p
            p + L[i] <= N
            p + L[i] + ... + L[M - 1] >= N
          */
          ans[i] = max(bef + 1, N - (LSum[M] - LSum[i]));
          if (!(ans[i] + L[i] <= N)) {
            ans = [];
            break;
          }
          bef = ans[i];
        }
      }

      if (!ans.empty) {
        foreach (i; 0 .. M) {
          if (i > 0) write(" ");
          write(ans[i] + 1);
        }
        writeln();
      } else {
        writeln(-1);
      }
    }
  } catch (EOFException e) {
  }
}