Ziota found a video game called "Monster Invaders".Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns.For the sake of simplicity, we only consider two different types of monsters and three different types of guns.Namely, the two types of monsters are:   a normal monster with $$$1$$$ hp.  a boss with $$$2$$$ hp. And the three types of guns are:   Pistol, deals $$$1$$$ hp in damage to one monster, $$$r_1$$$ reloading time  Laser gun, deals $$$1$$$ hp in damage to all the monsters in the current level (including the boss), $$$r_2$$$ reloading time  AWP, instantly kills any monster, $$$r_3$$$ reloading time The guns are initially not loaded, and the Ziota can only reload 1 gun at a time.The levels of the game can be considered as an array $$$a_1, a_2, \ldots, a_n$$$, in which the $$$i$$$-th stage has $$$a_i$$$ normal monsters and 1 boss. Due to the nature of the game, Ziota cannot use the Pistol (the first type of gun) or AWP (the third type of gun) to shoot the boss before killing all of the $$$a_i$$$ normal monsters.If Ziota damages the boss but does not kill it immediately, he is forced to move out of the current level to an arbitrary adjacent level (adjacent levels of level $$$i$$$ $$$(1 < i < n)$$$ are levels $$$i - 1$$$ and $$$i + 1$$$, the only adjacent level of level $$$1$$$ is level $$$2$$$, the only adjacent level of level $$$n$$$ is level $$$n - 1$$$). Ziota can also choose to move to an adjacent level at any time. Each move between adjacent levels are managed by portals with $$$d$$$ teleportation time.In order not to disrupt the space-time continuum within the game, it is strictly forbidden to reload or shoot monsters during teleportation. Ziota starts the game at level 1. The objective of the game is rather simple, to kill all the bosses in all the levels. He is curious about the minimum time to finish the game (assuming it takes no time to shoot the monsters with a loaded gun and Ziota has infinite ammo on all the three guns). Please help him find this value.

The first line of the input contains five integers separated by single spaces: $$$n$$$ $$$(2 \le n \le 10^6)$$$ — the number of stages, $$$r_1, r_2, r_3$$$ $$$(1 \le r_1 \le r_2 \le r_3 \le 10^9)$$$ — the reload time of the three guns respectively, $$$d$$$ $$$(1 \le d \le 10^9)$$$ — the time of moving between adjacent levels. The second line of the input contains $$$n$$$ integers separated by single spaces $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^6, 1 \le i \le n)$$$.

Print one integer, the minimum time to finish the game.

NoteIn the first test case, the optimal strategy is:  Use the pistol to kill three normal monsters and AWP to kill the boss (Total time $$$1\cdot3+4=7$$$)  Move to stage two (Total time $$$7+3=10$$$)  Use the pistol twice and AWP to kill the boss (Total time $$$10+1\cdot2+4=16$$$)  Move to stage three (Total time $$$16+3=19$$$)  Use the laser gun and forced to move to either stage four or two, here we move to stage four (Total time $$$19+3+3=25$$$)  Use the pistol once, use AWP to kill the boss (Total time $$$25+1\cdot1+4=30$$$)  Move back to stage three (Total time $$$30+3=33$$$)  Kill the boss at stage three with the pistol (Total time $$$33+1=34$$$) Note that here, we do not finish at level $$$n$$$, but when all the bosses are killed.

import std.algorithm, std.conv, std.range, std.stdio;
void main () {
	int n;
	long r1, r2, r3, d;
	while (readf !(" %s %s %s %s %s") (n, r1, r2, r3, d) > 0) {
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		auto b = a.map !(x => r1 * x + r3).array;
		auto c = a.map !(x => min (r1 * (x + 1), r2) + r1).array;
		auto e = n.iota.map !(i => min (b[i], c[i])).array;
		auto f = [0L];
		foreach (i; 0..n) {
			auto cur = f[i] + b[i] + d;
			if (i > 0) cur = min (cur, f[i - 1] + e[i - 1] + e[i] + d * 4);
			if (i > 1) cur = min (cur, f[i - 2] + e[i - 2] + e[i - 1] + e[i] + d * 7);
			f ~= cur;
		}
		writeln (min (f[n] - d, f[n - 2] + e[n - 2] + b[n - 1] + d * 2));
	}
}

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

immutable long infinity = long.max / 4;

void main ()
{
	int n;
	long r1, r2, r3, d;
	while (readf !(" %s %s %s %s %s") (n, r1, r2, r3, d) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		auto b = a.map !(x => r1 * x + r3).array;
		debug {writeln (b);}
		auto c = a.map !(x => min (r1 * (x + 1), r2) + r1).array;
		debug {writeln (c);}
		auto e = new long [n];
		foreach (i; 0..n)
		{
			e[i] = min (b[i], c[i]);
		}
		debug {writeln (e);}

		auto f = [0L];
		foreach (i; 0..n)
		{
			auto cur = f[i] + b[i] + d;
			if (i > 0)
			{
				cur = min (cur, f[i - 1] +
				    e[i - 1] + e[i] + d * 4);
			}
			if (i > 1)
			{
				cur = min (cur, f[i - 2] +
				    e[i - 2] + e[i - 1] + e[i] + d * 7);
			}
			f ~= cur;
		}
		debug {writeln (f);}

		long res = min (f[n] - d,
		    f[n - 2] + e[n - 2] + b[n - 1] + d * 2);

		writeln (res);
	}
}


You are given an array consisting of n non-negative integers a1, a2, ..., an.You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).  The third line contains a permutation of integers from 1 to n — the order used to destroy elements.

Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.

NoteConsider the first sample:   Third element is destroyed. Array is now 1 3  *  5. Segment with maximum sum 5 consists of one integer 5.  Fourth element is destroyed. Array is now 1 3  *   * . Segment with maximum sum 4 consists of two integers 1 3.  First element is destroyed. Array is now  *  3  *   * . Segment with maximum sum 3 consists of one integer 3.  Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
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;
import std.variant;

__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];
}

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

struct Node {
    private {
        mixin(bitfields!(
            uint, `index`,   31,
            bool, `delayed`, 1,
        ));
    }
    int size = 1;
    Splay left, right, parent;

    invariant {
        foreach (child; AliasSeq!(left, right))
            if (child !is null)
                assert(child.parent is &this);
        assert(size == left.size + right.size + 1);
    }

    void assign(int id) {
        index = id;
        delayed = true;
    }

    static void split(Splay t, ref Splay l, ref Splay r, int x)
    in {
        assert(x <= t.size);
    }
    out {
        assert(l.size == x);
    }
    body {
        if (x == t.size) {
            l = t;
            r = null;
        } else {
            r = t.splayByKey(x);
            l = r.left;
            l.unlink();
        }
    }

    static Splay merge(/+return+/ Splay l, /+return+/ Splay r)
    in {
        if (l !is null) {
            assert(l.parent is null);
            assert(l !is r);
        }
        if (r !is null)
            assert(r.parent is null);
    }
    out (result) {
        assert(result.parent is null);
    }
    body {
        if (l is null)
            return r;
        if (r is null)
            return l;
        auto t = r.splayLeft();
        l.link(L, t);
        return t;
    }

    Splay splayLeft() return
    out (result) {
        assert(result.parent is null);
        assert(result.left is null);
    }
    body {
        push();
        if (left !is null)
            return left.splayLeft();
        splay();
        return Splay(&this);
    }

    Splay splayByKey(int x) return
    in {
        assert(x < size);
    }
    out (result) {
        assert(result.left.size == x);
        assert(result.parent is null);
    }
    body {
        return _splayByKey(x);
    }

    private Splay _splayByKey(int x) return
    in {
        assert(x < size);
    }
    body {
        push();
        if (x == left.size) {
            splay();
            return Splay(&this);
        } else if (x < left.size)
            return left._splayByKey(x);
        else
            return right._splayByKey(x - left.size - 1);
    }

    void splay()
    out {
        assert(parent is null);
    }
    body {
        while (true) {
            auto parent = parent;
            if (parent is null)
                return;
            if (parent.parent is null) {
                rotate();
                return;
            }
            if (side == parent.side)
                parent.rotate();
            else
                rotate();
            rotate();
        }
    }

    void rotate()
    in {
        assert(parent !is null);
    }
    body {
        auto parent = parent;
        auto gparent = parent.parent;
        auto side = side;
        auto parentSide = gparent ? parent.side : 0;
        unlink();
        parent.unlink();
        if (side == L) {
            if (auto right = right) {
                right.unlink();
                right.link(L, parent);
            }
            parent.link(R, Splay(&this));
        } else {
            if (auto left = left) {
                left.unlink();
                left.link(R, parent);
            }
            parent.link(L, Splay(&this));
        }
        link(parentSide, gparent);
    }

private:
    void push()
    out {
        assert(!delayed);
    }
    body {
        if (!delayed)
            return;
        foreach (child; AliasSeq!(left, right))
            if (child !is null)
                child.assign(index);
        delayed = false;
    }

    void recalc() {
        size = left.size + right.size + 1;
    }

    enum { L, R }

    @property bool side() const
    in {
        assert(parent !is null);
    }
    body {
        return &this is parent.left ? L : R;
    }

    void link(int c, Splay newParent)
    in {
        assert(parent is null);
        if (newParent !is null)
            assert((c == L ? newParent.left : newParent.right) is null);
    }
    out {
        assert(parent is newParent);
    }
    body {
        if (newParent is null)
            return;
        parent = newParent;
        if (c == L)
            parent.left = &this;
        else
            parent.right = &this;
        parent.recalc();
    }

    void unlink()
    out {
        assert(parent is null);
    }
    body {
        if (parent is null)
            return;
        if (side == L)
            parent.left = null;
        else
            parent.right = null;
        parent.recalc();
        parent = null;
    }
}

struct Splay {
    Node* _node;

    alias _node this;

    @property int size() const { return _node ? _node.size : 0; }

    static Splay build(int n) {
        Splay t;
        foreach (ref node; _nodes[0 .. n])
            t = Node.merge(t, Splay(&node));
        return t;
    }

    int getIndex(int i) {
        this = splayByKey(i);
        return index;
    }

    void update(int i, int j, int value) {
        Splay prefix, suffix;
        Node.split(this, this, suffix, j);
        Node.split(this, prefix, this, i);
        if (_node !is null)
            assign(value);
        this = Node.merge(Node.merge(prefix, this), suffix);
    }
}

alias Interval = Tuple!(int, `left`, int, `right`);

int[10^^5] _arr;
long[10^^5 + 1] psum;
Interval[10^^5 + 1] intervals;
Node[10^^5] _nodes;

long getSum(int i, int j) {
    return psum[j] - psum[i];
}

void main() {
    int n;
    while (scanf("%d", &n) == 1) {
        auto arr = _arr[0 .. n];
        version (LocalProject)
            _nodes[ ] = Node.init;
        //psum[0] = 0;
        foreach (i, ref x; arr) {
            scanf("%d", &x);
            psum[i + 1] = psum[i] + x;
        }
        int intervalCount = 1;
        intervals[0] = Interval(0, n);
        auto intervalSums = redBlackTree!true(psum[n]);
        auto t = Splay.build(n);
        foreach (i; 0 .. n) {
            int x;
            scanf("%d", &x);
            x--;

            const id = t.getIndex(x);
            intervalSums.removeKey(getSum(intervals[id].left, intervals[id].right));
            intervals[intervalCount] = Interval(x + 1, intervals[id].right);
            intervals[id].right = x;
            intervalSums.insert(getSum(intervals[id].left, x));
            intervalSums.insert(getSum(x + 1, intervals[intervalCount].right));
            t.update(x + 1, intervals[intervalCount].right, intervalCount);
            intervalCount++;

            printf("%lld\n", intervalSums.back);
        }
        debug putchar('\n');
    }
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(int)).array;
		a = 0 ~ a ~ 0;
		auto p = readln.split.map !(to !(int)).array;

		auto r = new int [n + 2];
		r[] = -1;
		auto w = new long [n + 2];

		long [] ans;
		long cur = 0;

		int root (int v)
		{
			if (r[v] != -1 && r[v] != v)
			{
				r[v] = root (r[v]);
			}
			return r[v];
		}

		void unite (int q)
		{
			long temp = a[q];
			r[q] = q;
			int u = root (q - 1);
			if (u != -1)
			{
				r[u] = q;
				temp += w[u];
			}
			int v = root (q + 1);
			if (v != -1)
			{
				r[v] = q;
				temp += w[v];
			}
			w[q] = temp;
			cur = max (cur, temp);
		}

		foreach_reverse (q; p)
		{
			ans ~= cur;
			unite (q);
		}
		writefln ("%(%s\n%)", ans.retro);
	}
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
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;
import std.variant;

__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];
}

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

struct Node {
    private {
        mixin(bitfields!(
            uint, `index`,   31,
            bool, `delayed`, 1,
        ));
    }
    int size = 1;
    Splay left, right, parent;

    invariant {
        foreach (child; AliasSeq!(left, right))
            if (child !is null)
                assert(child.parent is &this);
        assert(size == left.size + right.size + 1);
    }

    void assign(int id) {
        index = id;
        delayed = true;
    }

    static void split(Splay t, ref Splay l, ref Splay r, int x)
    in {
        assert(x <= t.size);
    }
    out {
        assert(l.size == x);
    }
    body {
        if (x == t.size) {
            l = t;
            r = null;
        } else {
            r = t.splayByKey(x);
            l = r.left;
            l.unlink();
        }
    }

    static Splay merge(/+return+/ Splay l, /+return+/ Splay r)
    in {
        if (l !is null) {
            assert(l.parent is null);
            assert(l !is r);
        }
        if (r !is null)
            assert(r.parent is null);
    }
    out (result) {
        assert(result.parent is null);
    }
    body {
        if (l is null)
            return r;
        if (r is null)
            return l;
        auto t = r.splayLeft();
        l.link(L, t);
        return t;
    }

    Splay splayLeft() return
    out (result) {
        assert(result.parent is null);
        assert(result.left is null);
    }
    body {
        push();
        if (left !is null)
            return left.splayLeft();
        splay();
        return Splay(&this);
    }

    Splay splayByKey(int x) return
    in {
        assert(x < size);
    }
    out (result) {
        assert(result.left.size == x);
        assert(result.parent is null);
    }
    body {
        return _splayByKey(x);
    }

    private Splay _splayByKey(int x) return
    in {
        assert(x < size);
    }
    body {
        push();
        if (x == left.size) {
            splay();
            return Splay(&this);
        } else if (x < left.size)
            return left._splayByKey(x);
        else
            return right._splayByKey(x - left.size - 1);
    }

    void splay()
    out {
        assert(parent is null);
    }
    body {
        while (true) {
            auto parent = parent;
            if (parent is null)
                return;
            if (parent.parent is null) {
                rotate();
                return;
            }
            if (side == parent.side)
                parent.rotate();
            else
                rotate();
            rotate();
        }
    }

    void rotate()
    in {
        assert(parent !is null);
    }
    body {
        auto parent = parent;
        auto gparent = parent.parent;
        auto side = side;
        auto parentSide = gparent ? parent.side : 0;
        unlink();
        parent.unlink();
        if (side == L) {
            if (auto right = right) {
                right.unlink();
                right.link(L, parent);
            }
            parent.link(R, Splay(&this));
        } else {
            if (auto left = left) {
                left.unlink();
                left.link(R, parent);
            }
            parent.link(L, Splay(&this));
        }
        link(parentSide, gparent);
    }

private:
    void push()
    out {
        assert(!delayed);
    }
    body {
        if (!delayed)
            return;
        foreach (child; AliasSeq!(left, right))
            if (child !is null)
                child.assign(index);
        delayed = false;
    }

    void recalc() {
        size = left.size + right.size + 1;
    }

    enum { L, R }

    @property bool side() const
    in {
        assert(parent !is null);
    }
    body {
        return &this is parent.left ? L : R;
    }

    void link(int c, Splay newParent)
    in {
        assert(parent is null);
        if (newParent !is null)
            assert((c == L ? newParent.left : newParent.right) is null);
    }
    out {
        assert(parent is newParent);
    }
    body {
        if (newParent is null)
            return;
        parent = newParent;
        if (c == L)
            parent.left = &this;
        else
            parent.right = &this;
        parent.recalc();
    }

    void unlink()
    out {
        assert(parent is null);
    }
    body {
        if (parent is null)
            return;
        if (side == L)
            parent.left = null;
        else
            parent.right = null;
        parent.recalc();
        parent = null;
    }
}

struct Splay {
    Node* _node;

    alias _node this;

    @property int size() const { return _node ? _node.size : 0; }

    static Splay build(int n) {
        Splay t;
        foreach (ref node; _nodes[0 .. n])
            t = Node.merge(t, Splay(&node));
        return t;
    }

    int getIndex(int i) {
        this = splayByKey(i);
        return index;
    }

    void update(int i, int j, int value) {
        Splay prefix, suffix;
        Node.split(this, this, suffix, j);
        Node.split(this, prefix, this, i);
        if (_node !is null)
            assign(value);
        this = Node.merge(Node.merge(prefix, this), suffix);
    }
}

alias Interval = Tuple!(int, `left`, int, `right`);

int[10^^5] _arr;
long[10^^5 + 1] psum;
Interval[10^^5 + 1] intervals;
Node[10^^5] _nodes;

long getSum(int i, int j) {
    return psum[j] - psum[i];
}

void main() {
    int n;
    while (scanf("%d", &n) == 1) {
        auto arr = _arr[0 .. n];
        version (LocalProject)
            _nodes[ ] = Node.init;
        //psum[0] = 0;
        foreach (i, ref x; arr) {
            scanf("%d", &x);
            psum[i + 1] = psum[i] + x;
        }
        int intervalCount = 1;
        intervals[0] = Interval(0, n);
        auto intervalSums = redBlackTree!true(psum[n]);
        auto t = Splay.build(n);
        foreach (i; 0 .. n) {
            int x;
            scanf("%d", &x);
            x--;
            int id = t.getIndex(x);
            intervalSums.removeKey(getSum(intervals[id].left, intervals[id].right));
            intervals[intervalCount] = Interval(x + 1, intervals[id].right);
            intervals[id].right = x;
            intervalSums.insert(getSum(intervals[id].left, x));
            intervalSums.insert(getSum(x + 1, intervals[intervalCount].right));
            t.update(x + 1, intervals[intervalCount].right, intervalCount);
            intervalCount++;
            printf("%d\n", intervalSums.back);
        }
        debug putchar('\n');
    }
}


Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel.  It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.

If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.

NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.

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

void main() {
    auto N = readln.chomp.to!int;
    auto M = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto B = readln.split.map!(to!long).array;

    bool ok(real fuel) {
        foreach (i; 0..N-1) {
            real x = (M + fuel) / A[i];
            fuel -= x;
            if (fuel < 0) return false;
            x = (M + fuel) / B[i+1];
            fuel -= x;
            if (fuel < 0) return false;
        }
        real x = (M + fuel) / A[N-1];
        fuel -= x;
        if (fuel < 0) return false;
        x = (M + fuel) / B[0];
        fuel -= x;
        if (fuel < 0) return false;
        return true;
    }

    real hi = 10L^^10;
    real lo = 0;

    foreach (_; 0..100) {
        real mid = (hi + lo) / 2;
        (ok(mid) ? hi : lo) = mid;
    }

    if (hi > 10^^9+100)
        writeln(-1);
    else
        writefln("%.9f", hi);
}

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

void main() {
    int n; double m;
    readf("%d\n%f\n", &n, &m);
    double[] a = readln.strip.split.map!(to!double).array;
    double[] b = readln.strip.split.map!(to!double).array;
    bool check(double fuel) {
        foreach (p; zip(a, b)) {
            double now_a = p[0], now_b = p[1];
            fuel -= (m + fuel) / now_a;
            if (fuel < 0) return false;
            fuel -= (m + fuel) / now_b;
            if (fuel < 0) return false;
        }
        return true;
    }
    if (!check(1e10)) {
        writeln(-1);
        return;
    }
    double min_x = 0, max_x = 1e9;
    foreach (phase; 0..200) {
        double mid = (min_x + max_x) / 2;
        if (!check(mid)) min_x = mid;
        else max_x = mid;
    }
    writefln("%.20f", max_x);
}

import std.algorithm, std.conv, std.range, std.stdio;
void main () {
	readln;
	int m = readln.split[0].to!int;
	auto c = (readln ~ readln).split.map !("1 - 1 / a.to!real").fold!"a * b";
	writef ("%.9f", c ? m / c - m : -1);
}

import std.stdio;

int main ()
{
	int n, m, i;
	double c = 1.0, x;
	scanf ("%d%d", &n, &m);
	for (i = 0; i < n * 2; i++)
	{
		scanf ("%lf", &x);
		c *= 1 - 1 / x;
	}
	printf ("%.10lf\n", c > 0 ? m / c - m : -1);
	return 0;
}

import std.stdio;

int main ()
{
	int n, m, i;
	double c = 1.0, x;
	scanf ("%d%d", &n, &m);
	for (i = 0; i < n * 2; i++)
	{
		scanf ("%lf", &x);
		c *= 1 - 1 / x;
	}
	printf ("%.10f\n", c > 0 ? m / c - m : -1);
	return 0;
}

import std.stdio;

int main ()
{
	int n, m, i;
	double c = 1.0, x;
	scanf ("%d%d", &n, &m);
	for (i = 0; i < n * 2; i++)
	{
		scanf ("%lf", &x);
		c *= 1 - 1 / x;
	}
	printf ("%.10lf", c > 0 ? m / c - m : -1);
	return 0;
}

import std.algorithm, std.conv, std.stdio;

void main ()
{
	int n, m;
	readf (" %s %s ", n, m);
	auto c = (readln ~ readln)
	    .splitter
	    .map !(to!double)
	    .map !(x => 1 - 1 / x)
	    .fold !"a * b";
	writefln ("%.10f", c > 0 ? m / c - m : -1);
}

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

void main ()
{
	readln;
	int m = readln.strip.to!int;
	auto c = (readln ~ readln).split.map !("1 - 1 / a.to!real").fold !"a * b" (1.0);
	writefln ("%.10f", c ? m / c - m : -1);
}

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;

		if (chain (a, b).any !(q{a == 1}))
		{
			writeln (-1);
			continue;
		}

		long res = 0;
		real lo = 0;
		real hi = 1E10;
		foreach (step; 0..200)
		{
			real me = (lo + hi) * 0.5;
			real cur = m + me;
			foreach (i; 0..n)
			{
				cur *= 1.0L - 1.0L / a[i];
				cur *= 1.0L - 1.0L / b[i];
			}
			if (cur >= m)
			{
				hi = me;
			}
			else
			{
				lo = me;
			}
		}
		writefln ("%.10f", lo);
	}
}

import std.algorithm, std.conv, std.stdio;

void main ()
{
	int n, m;
	readf !" %s %s " (n, m);
	auto c = (readln ~ readln)
	    .splitter
	    .map !(to!double)
	    .map !(x => 1 - 1 / x)
	    .fold !"a * b";
	writefln !"%.10f" (c > 0 ? m / c - m : -1);
}

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

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

    auto r = () => readln.chomp.split.map!(to!int).array;
    auto a = r();
    auto b = r();

    int[] arr;
    foreach (e1, e2; lockstep(a, b)) {
        arr ~= e1;
        arr ~= e2;
    }

    double ans = 0, curm = m;
    foreach_reverse (e; arr) {
        if (e == 1) {
            writeln(-1);
            return;
        }

        debug { writeln(e, ' ', curm); }

        double curf = curm / (e - 1);
        ans += curf;
        curm += curf;
    }

    ans.writefln!("%.10f");
}

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

void main ()
{
	readln;
	int m = readln.strip.to!int;
	auto c = (readln ~ readln).split.map !("1 - 1 / a.to!real").fold !"a * b" (1.0);
	writeln (c ? m / c - m : -1);
}


According to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.

The first line of the input contains numbers n and m (1 ≤ n, m ≤ 100), n — the amount of rows, m — the amount of columns on the flag of Berland. Then there follows the description of the flag: each of the following n lines contain m characters. Each character is a digit between 0 and 9, and stands for the colour of the corresponding square.

Output YES, if the flag meets the new ISO standard, and NO otherwise.

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

void main()
{
    auto nm = readln.split.map!(to!int);
    auto n = nm[0], m = nm[1];
    auto flag = m.iota.map!(_ => readln.chomp).array;
    auto hasSameColorInRow = flag.map!(a=>a.all!(b=>b==a[0])).all!"a==true";
    auto hasAdjacentColorInColumn = true;
    foreach(i; 0..n)
        hasAdjacentColorInColumn = hasAdjacentColorInColumn &&  flag.transversal(i).array.chunkBy!"a==b".all!(a=>a.array.length==1);
    writeln(!(hasSameColorInRow && hasAdjacentColorInColumn)?"NO":"YES");
}

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

void main()
{
    auto nm = readln.split.map!(to!int);
    auto n = nm[0], m = nm[1];
    auto flag = m.iota.map!(_ => readln.chomp).array;
    auto hasSameColorInRow = flag.map!(a=>a.all!(b=>b==a[0])).all!"a==true";
    auto hasAdjacentColorInColumn = n.iota.array.map!(i=>flag.transversal(i).chunkBy!"a==b".all!(a=>a.array.length==1)).fold!"a&&b"(true);
    writeln(!(hasSameColorInRow && hasAdjacentColorInColumn)?"NO":"YES");
}


You are given a board with $$$n$$$ rows and $$$n$$$ columns, numbered from $$$1$$$ to $$$n$$$. The intersection of the $$$a$$$-th row and $$$b$$$-th column is denoted by $$$(a, b)$$$.A half-queen attacks cells in the same row, same column, and on one diagonal. More formally, a half-queen on $$$(a, b)$$$ attacks the cell $$$(c, d)$$$ if $$$a=c$$$ or $$$b=d$$$ or $$$a-b=c-d$$$.    The blue cells are under attack.  What is the minimum number of half-queens that can be placed on that board so as to ensure that each square is attacked by at least one half-queen?Construct an optimal solution.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of the board.

In the first line print a single integer $$$k$$$ — the minimum number of half-queens. In each of the next $$$k$$$ lines print two integers $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the position of the $$$i$$$-th half-queen. If there are multiple solutions, print any.

NoteExample $$$1$$$: one half-queen is enough. Note: a half-queen on $$$(1, 1)$$$ attacks $$$(1, 1)$$$.Example $$$2$$$: one half-queen is enough too. $$$(1, 2)$$$ or $$$(2, 1)$$$ would be wrong solutions, because a half-queen on $$$(1, 2)$$$ does not attack the cell $$$(2, 1)$$$ and vice versa. $$$(2, 2)$$$ is also a valid solution.Example $$$3$$$: it is impossible to cover the board with one half queen. There are multiple solutions for $$$2$$$ half-queens; you can print any of them.

import std;
void main () {
	int n = readln.strip.to!int, r = n - (n % 3 != 1), c = 1;
	auto a = [[r, c]];
	foreach (i; 0..n) {
		r -= 1 + (i & 1);
		c += 1 + !(i & 1);
		if (r < 1 || c > n) break;
		a ~= [r, c];
	}
	writefln!"%s\n%(%(%s %)\n%)" (a.length, a);
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		int [2] [] answer;
		int row = n - (n % 3 != 1);
		int col = 1;
		answer ~= [row, col];
		foreach (step; 0..n)
		{
			row -= 1 + (step & 1);
			col += 1 + !(step & 1);
			if (row < 1 || col > n)
			{
				break;
			}
			answer ~= [row, col];
		}
		writeln (answer.length);
		foreach (ref line; answer)
		{
			writefln !("%(%s %)") (line);
		}
	}
}

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)); }

bool experiment(int N, int M) {
  bool found;
  void check(int[] zs) {
    auto a = new char[][](N, N);
    foreach (x; 0 .. N) foreach (y; 0 .. N) {
      a[x][y] = '?';
    }
    foreach (z; zs) {
      const x = z / N, y = z % N;
      foreach (xx; 0 .. N) foreach (yy; 0 .. N) {
        if (x == xx || y == yy || x - y == xx - yy) {
          a[xx][yy] = '.';
        }
      }
    }
    foreach (z; zs) {
      const x = z / N, y = z % N;
      a[x][y] = '#';
    }
    bool ok = true;
    foreach (x; 0 .. N) foreach (y; 0 .. N) {
      ok = ok && (a[x][y] != '?');
    }
    if (ok) {
      found = true;
      foreach (x; 0 .. N) {
        writeln(a[x]);
      }
      writeln;
      stdout.flush;
    }
  }
  void dfs(int[] zs) {
    if (zs.length == M) {
      check(zs);
    } else {
      foreach (z; (zs.empty ? 0 : (zs[$ - 1] + 1)) .. N^^2) {
        dfs(zs ~ z);
      }
    }
  }
  dfs([]);
  return found;
}

alias Pt = Tuple!(int, "x", int, "y");

Pt[] solve(int N) {
  Pt[] ans;
  const a = (N - 1) / 3;
  foreach (i; 0 .. a + 1) {
    ans ~= Pt(i, a - i);
  }
  foreach (i; 0 .. a) {
    ans ~= Pt(N - 1 - i, N - 1 - (a - 1 - i));
  }
  if (N % 3 == 0) {
    ans ~= Pt(N - 1 - a, N - 1 - a);
  }
  return ans;
}

void judge(int N, const(Pt[]) P) {
  foreach (p; P) {
    assert(0 <= p.x); assert(p.x < N);
    assert(0 <= p.y); assert(p.y < N);
  }
  foreach (x; 0 .. N) foreach (y; 0 .. N) {
    bool ok;
    foreach (p; P) {
      ok = ok || (x == p.x || y == p.y || x - y == p.x - p.y);
    }
    assert(ok);
  }
}

void main() {
  /*
  debug {
    foreach (n; 1 .. 9 + 1) {
      for (int m = 1; ; ++m) {
        const res = experiment(n, m);
        if (res) {
          stderr.writeln(n, ": ", m);
          stderr.flush;
          break;
        }
      }
    }
    return;
  }
  //*/

  debug {
    foreach (n; 1 .. 20 + 1) {
      const ans = solve(n);
      // writeln(n, ": ", ans.length, " ", ans);
      writeln(n, ": ", ans.length);
      judge(n, ans);
    }
  }

  try {
    for (; ; ) {
      const N = readInt;

      auto ans = solve(N);
      writeln(ans.length);
      foreach (p; ans) {
        writeln(p.x + 1, " ", p.y + 1);
      }
    }
  } catch (EOFException e) {
  }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element.

NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$.

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
void main()
{
  int n; get(n);
  auto a = new int[n]; get(a);
  int[2][] ps;
  int i = 0;
  int res = 0;
  for(; i < n;)
    {
      int si = i, fi = i;
      while(fi + 1 < n && a[fi + 1] > a[fi])
	{
	  fi++;
	}
      ps ~= [si, fi];
      res = max(res, fi - si + 1);
      i = fi + 1;
    }
  for(int j = 1; j < ps.length; j++)
    {
      auto curr = ps[j];
      auto prev = ps[j - 1];
      int comb = 0;
      if (prev[0] < prev[1])
	{
	  if(a[prev[1] - 1] < a[curr[0]])
	    {
	      comb = max(comb, curr[1] - curr[0] + 1 + prev[1] - prev[0]);
	    }
	}
      if (curr[0] < curr[1])
	{
	  if(a[prev[1]] < a[curr[0] + 1])
	    {
	      comb = max(comb, curr[1] - curr[0] + prev[1] - prev[0] + 1);
	    }
	}
      res = max(res, comb);
    }
  ans(res);
}

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

immutable int INF = 1 << 29;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;

    auto dp = new int[][][](N, 2, 2);
    foreach (i; 0..N) foreach (j; 0..2) foreach (k; 0..2) dp[i][j][k] = j + k == 0 ? 1 : 0;
    dp[0][0][0] = 1;
    dp[0][1][1] = 0;

    foreach (i; 1..N) {
        if (A[i] > A[i-1]) {
            dp[i][0][0] = max(dp[i][0][0], dp[i-1][0][0] + 1);
            dp[i][1][0] = max(dp[i][1][0], dp[i-1][1][0] + 1);
        }
        if (i > 1 && A[i] > A[i-2]) {
            dp[i][1][0] = max(dp[i][1][0], dp[i-1][1][1] + 1);
        }
        dp[i][1][1] = max(dp[i][1][1], dp[i-1][0][0]);
    }

    int ans = 0;
    foreach (i; 0..N) foreach (j; 0..2) foreach (k; 0..2) ans = max(ans, dp[i][j][k]);
    ans.writeln;
}

import std.stdio, std.string;
import std.array, std.conv;
import std.algorithm;

int solve(int[] a)
{
    auto n = to!int(a.length);
    auto fdp = new int[n];
    auto bdp = new int[n];
    auto res = 0;
    foreach_reverse (i; 0 .. n)
    {
        fdp[i] = 1;
        if (i < n - 1 && a[i] < a[i + 1]) fdp[i] = fdp[i + 1] + 1;
        res = max(res, fdp[i]);
    }
    foreach (i; 0 .. n)
    {
        bdp[i] = 1;
        if (i > 0 && a[i - 1] < a[i]) bdp[i] = bdp[i - 1] + 1;
    }
    foreach (i; 1 .. n - 1)
    {
        if (a[i - 1] < a[i + 1]) res = max(res, bdp[i - 1] + fdp[i + 1]);
    }
    return res;
}

int main(string[] args)
{
    readln;
    auto a = map!(x => to!int(x))(readln.strip.split(" ")).array;
    auto ret = solve(a);
    writeln(ret);
    return 0;
}

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(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	int n = rint;
	long[] as = rlong(n);

	int[] xs = new int[](n);
	int[] ys = new int[](n); // xs[i]: best using i without skip; ys[i]: best using i and skipped one before
	foreach(i; 0 .. n){
		xs[i] = 1, ys[i] = 0;
		if(i > 0 && as[i - 1] < as[i]) xs[i].chmax(xs[i - 1] + 1);
		if(i > 0 && as[i - 1] < as[i]) ys[i].chmax(ys[i - 1] + 1);
		if(i > 1 && as[i - 2] < as[i]) ys[i].chmax(xs[i - 2] + 1);
	}
	long ans;
	foreach(x; xs) ans.chmax(x);
	foreach(y; ys) ans.chmax(y);
	ans.writeln;
}

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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto a = RDA!int;
	int[][] arr;
	int begin;
	foreach (i; 1..n)
	{
		if (a[i] <= a[i-1])
		{
			arr ~= [begin, i];
			begin = i;
		}
	}
	arr ~= [begin, n];

	if (arr.length == 1)
		writeln(n);
	else
	{
		int ans = arr[0][1] - arr[0][0];
		foreach (i; 1..arr.length)
		{
			auto len1 = arr[i-1][1] - arr[i-1][0];
			auto len2 = arr[i][1] - arr[i][0];
			ans.chmax(len2);
			if (len1 != 1 && len2 != 1)
			{
				{
					auto r = arr[i-1][1]-2;
					auto l = arr[i][0];
					if (a[r] < a[l])
						ans.chmax(len2 + len1 - 1);
				}
				{
					auto r = arr[i-1][1]-1;
					auto l = arr[i][0]+1;
					if (a[r] < a[l])
						ans.chmax(len2 + len1 - 1);
				}
			}
		}
		writeln(ans);
	}

	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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto a = RDA!int;
	int l1, l2, ans = 1;
	int last;
	foreach (i; 1..n)
	{
		if (a[i] <= last)
		{
			auto len = i - l1 - 1;
			ans.chmax(len);
			l1 = l2;
			l2 = i;
			if (i < 2)
				last = a[i];
			else if (a[i] > a[i-2])
				last = a[i];
			else
				last = a[i-1];
		}
		else
			last = a[i];
	}
	ans.chmax(n - l1 - 1);
	ans.chmax(n - l2);

	writeln(ans);
	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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto a = RDA!int;
	/*while (true)
	{
	auto n = uniform(5, 10);
	auto a = new int[](n);
	foreach (i; 0..n)
	{
		a[i] = uniform(1, 10);
	}
	writeln(n);
	writeln(a);*/
	long ans = 1;
	auto dp = new int[][][](n+1, 2, 2);
	foreach (i; 0..n)
	{
		if (a[i] <= dp[i][1][0])
		{
			ans.chmax(dp[i][1][1]);
			dp[i+1][0] = [a[i], 1];
		}
		else
			dp[i+1][1] = [a[i], dp[i][1][1]+1];

		if (a[i] <= dp[i][0][0])
		{
			if (dp[i][0][1] > dp[i+1][1][1])
				dp[i+1][1] = [a[i], dp[i][0][1]];
		}
		else
			dp[i+1][0] = [a[i], dp[i][0][1]+1];
	}
	ans.chmax(dp[n][0][1]);
	ans.chmax(dp[n][1][1]);

	writeln(ans);
	stdout.flush;
	//readln;
	//}
	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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto a = RDA!int;
	int l1, l2, ans = 1;
	foreach (i; 1..n)
	{
		if (a[i] <= a[i-1])
		{
			auto len = i - l1 - 1;
			ans.chmax(len);
			l1 = l2;
			l2 = i;
		}
	}
	ans.chmax(n - l1 - 1);
	ans.chmax(n - l2);

	writeln(ans);
	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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto a = RDA!int;
	int l1, l2, ans;
	foreach (i; 1..n)
	{
		if (a[i] <= a[i-1])
		{
			auto len = i - l1 - 1;
			ans.chmax(len);
			l1 = l2;
			l2 = i;
		}
	}
	ans.chmax(n - l1 - 1);
	ans.chmax(n - l2);

	writeln(ans);
	stdout.flush;
	debug readln;
}


You are given three integers $$$n$$$, $$$k$$$, $$$m$$$ and $$$m$$$ conditions $$$(l_1, r_1, x_1), (l_2, r_2, x_2), \dots, (l_m, r_m, x_m)$$$.Calculate the number of distinct arrays $$$a$$$, consisting of $$$n$$$ integers such that:   $$$0 \le a_i < 2^k$$$ for each $$$1 \le i \le n$$$;  bitwise AND of numbers $$$a[l_i] \& a[l_i + 1] \& \dots \& a[r_i] = x_i$$$ for each $$$1 \le i \le m$$$. Two arrays $$$a$$$ and $$$b$$$ are considered different if there exists such a position $$$i$$$ that $$$a_i \neq b_i$$$. The number can be pretty large so print it modulo $$$998244353$$$.

The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 5 \cdot 10^5$$$, $$$1 \le k \le 30$$$, $$$0 \le m \le 5 \cdot 10^5$$$) — the length of the array $$$a$$$, the value such that all numbers in $$$a$$$ should be smaller than $$$2^k$$$ and the number of conditions, respectively. Each of the next $$$m$$$ lines contains the description of a condition $$$l_i$$$, $$$r_i$$$ and $$$x_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le x_i < 2^k$$$) — the borders of the condition segment and the required bitwise AND value on it.

Print a single integer — the number of distinct arrays $$$a$$$ that satisfy all the above conditions modulo $$$998244353$$$.

NoteYou can recall what is a bitwise AND operation here.In the first example, the answer is the following arrays: $$$[3, 3, 7, 6]$$$, $$$[3, 7, 7, 6]$$$ and $$$[7, 3, 7, 6]$$$.

// Code By H~$~C

module main;

import std.stdio, std.array, std.string, std.math, std.uni, std.format, std.bigint;
import std.algorithm, std.conv, std.container, std.range, std.functional;
import std.random, std.typecons;

immutable Maxn = 500005;

int n, k, m;
modint ans;
int[Maxn] l, r, x, prf, mx;
modint[Maxn] dp, pre;

void solve(in int testcase) {
  n.read, k.read, m.read;
  foreach(i; 0 .. m) {
    l[i].read, r[i].read, x[i].read;
  }
  ans = 1;
  foreach(b; 0 .. k) {
    debug{writefln!"b = %s"(b);}
    prf[] = 0;
    mx[] = 0;
    foreach(i; 0 .. m) {
      int cur = (x[i] >> b) & 1;
      if (cur == 1) {
        prf[l[i]]++;
        prf[r[i] + 1]--;
      }
      else {
        mx[r[i]] = max(mx[r[i]], l[i]);
      }
    }
    foreach(i; 1 .. n + 1) {
      mx[i] = max(mx[i], mx[i - 1]);
      prf[i] += prf[i - 1];
    }
    dp[] = modint(0L);
    dp[0] = 1;
    pre[0] = 1;
    debug{writefln!"i = %s, dp = %s, pre = %s"(0, dp[0].to!int, pre[0].to!int);}
    foreach(i; 1 .. n + 2) {
      debug{writefln!"i = %s"(i);}
      if (prf[i] > 0) {
        dp[i] = 0;
        pre[i] = pre[i - 1];
        continue;
      }
      debug{writefln!"mx[%s] = %s"(i - 1, mx[i - 1]);}
      dp[i] = pre[i - 1];
      if (mx[i - 1] != 0) {
        dp[i] -= pre[mx[i - 1] - 1];
      }
      pre[i] = pre[i - 1] + dp[i];
      debug{writefln!"dp = %s, pre = %s"(dp[i].to!int, pre[i].to!int);}
    }
    debug{writefln!"ans = %s"(dp[n + 1].to!int);}
    ans *= dp[n + 1];
  }
  ans.to!int.writeln;
}

// ************************************************************

T reader(T)() { return readToken().to!T; }
void read(T)(ref T t) { t = reader!T; }
T[] readarray(T)() { return readln.splitter.map!(to!T).array; }
void chmax(T)(ref T a, T b) { a = max(a, b); }
void chmin(T)(ref T a, T b) { a = min(a, b); }
alias less = (a, b) => a < b;
alias greater = (a, b) => a > b;
T min_element(T)(in T[] a) { return a.element!less; }
T max_element(T)(in T[] a) { return a.element!greater; }
alias unique = uniq;

// constant or some variables
immutable int inf = 0x3f3f3f3f;
immutable long lnf = 0x3f3f3f3f3f3f3f3f;
immutable typeof(null) NULL = null;
string[] _tokens;

// functions
T element(alias pred, T)(in T[] a) {
  int pos = 0;
  for (int i = 1; i < cast(int)(a.length); ++i)
    if (binaryFun!pred(a[i], a[pos])) pos = i;
  return a[pos];
}
string readToken() {
  for (; _tokens.empty; ) {
    if (stdin.eof) return "";
    _tokens = readln.split;
  }
  auto token = _tokens.front;
  _tokens.popFront;
  return token;
}
int binary_bearch(alias pred, T)(in T[] as) {
  int l = -1, h = cast(int)(as.length), mid;
  for (; l + 1 < h; ) {
    mid = (l + h) >> 1;
    (unaryFun!pred(as[mid]) ? h : l) = mid;
  }
  return h;
}
int lower_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => a == val || pred(val, a));
}
int upper_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => pred(val, a));
}
int countbit(T)(T x) {
  int res = 0;
  while (x) {
    res++;
    x &= x - 1;
  }
  return res;
}

void main(string[] args) {
  int tests = 1;
//  tests.read();
  foreach(test; 1 .. tests + 1) solve(test);
}

struct modular_int(uint M_) {
  alias M = M_;
  uint x;
  modular_int inv() const {
    uint a = M, b = x;
    long u = 0, v = 1;
    while (b) {
      uint t = a / b;
      a -= t * b; swap(a, b);
      u -= t * v; swap(u, v);
    }
    if (u < 0) u += M;
    return modular_int(u);
  }
  this(modular_int a) { x = a.x; }
  this(long a) { a %= M; if (a < 0) a += M; x = cast(int)a; }
  ref modular_int opAssign(long a) { return (this = modular_int(a)); }
  ref modular_int opOpAssign(string op)(modular_int a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x & (1U << 31)) x += M; }
    else static if (op == "*") { x = cast(uint)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref modular_int opOpAssign(string op)(long a) {
    static if (op == "^^") {
      modular_int t2 = this, te = modular_int(1);
      if (a < 0) a = -a, t2 = t2.inv();
      for (long e = a; e; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = te.x;
      return this;
    }
    else return mixin("this " ~ op ~ "= modular_int(a)");
  }
  modular_int opUnary(string op)() const if (op == "-") {
    return modular_int(M - x);
  }
  modular_int opBinary(string op, T)(T a) const {
    return mixin("modular_int(this) " ~ op ~ "= a");
  }
  modular_int opBinaryRight(string op)(long a) const {
    return mixin("modular_int(a) " ~ op ~ "= this");
  }
  T to(T)() const {
    return x.to!T;
  }
}
alias modint = modular_int!998244353;

// Code By H~$~C

module main;

import std.stdio, std.array, std.string, std.math, std.uni, std.format, std.bigint;
import std.algorithm, std.conv, std.container, std.range, std.functional;
import std.random, std.typecons;

immutable Maxn = 500005;

int n, k, m;
modint ans;
int[Maxn] l, r, x, prf, mx;
modint[Maxn] dp, pre;

void solve(in int testcase) {
  n.read, k.read, m.read;
  foreach(i; 0 .. m) {
    l[i].read, r[i].read, x[i].read;
  }
  ans = 1;
  foreach(b; 0 .. k) {
    prf[] = 0;
    mx[] = 0;
    foreach(i; 0 .. m) {
      int cur = (x[i] >> b) & 1;
      if (cur == 1) {
        prf[l[i]]++;
        prf[r[i] + 1]--;
      }
      else {
        mx[r[i]] = max(mx[r[i]], l[i]);
      }
    }
    foreach(i; 1 .. n + 1) {
      mx[i] = max(mx[i], mx[i - 1]);
      prf[i] += prf[i - 1];
    }
    dp[] = modint(0L);
    dp[0] = 1;
    pre[0] = 1;
    foreach(i; 1 .. n + 2) {
      if (prf[i] > 0) {
        dp[i] = 0;
        pre[i] = pre[i - 1];
        continue;
      }
      dp[i] = pre[i - 1];
      if (mx[i - 1] != 0) {
        dp[i] -= pre[mx[i - 1] - 1];
      }
      pre[i] = pre[i - 1] + dp[i];
    }
    ans *= dp[n + 1];
  }
  ans.to!int.writeln;
}

// ************************************************************

T reader(T)() { return readToken().to!T; }
void read(T)(ref T t) { t = reader!T; }
T[] readarray(T)() { return readln.splitter.map!(to!T).array; }
void chmax(T)(ref T a, T b) { a = max(a, b); }
void chmin(T)(ref T a, T b) { a = min(a, b); }
alias less = (a, b) => a < b;
alias greater = (a, b) => a > b;
T min_element(T)(in T[] a) { return a.element!less; }
T max_element(T)(in T[] a) { return a.element!greater; }
alias unique = uniq;

// constant or some variables
immutable int inf = 0x3f3f3f3f;
immutable long lnf = 0x3f3f3f3f3f3f3f3f;
immutable typeof(null) NULL = null;
string[] _tokens;

// functions
T element(alias pred, T)(in T[] a) {
  int pos = 0;
  for (int i = 1; i < cast(int)(a.length); ++i)
    if (binaryFun!pred(a[i], a[pos])) pos = i;
  return a[pos];
}
string readToken() {
  for (; _tokens.empty; ) {
    if (stdin.eof) return "";
    _tokens = readln.split;
  }
  auto token = _tokens.front;
  _tokens.popFront;
  return token;
}
int binary_bearch(alias pred, T)(in T[] as) {
  int l = -1, h = cast(int)(as.length), mid;
  for (; l + 1 < h; ) {
    mid = (l + h) >> 1;
    (unaryFun!pred(as[mid]) ? h : l) = mid;
  }
  return h;
}
int lower_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => a == val || pred(val, a));
}
int upper_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => pred(val, a));
}
int countbit(T)(T x) {
  int res = 0;
  while (x) {
    res++;
    x &= x - 1;
  }
  return res;
}

void main(string[] args) {
  int tests = 1;
//  tests.read();
  foreach(test; 1 .. tests + 1) solve(test);
}

struct modular_int(uint M_) {
  alias M = M_;
  uint x;
  modular_int inv() const {
    uint a = M, b = x;
    long u = 0, v = 1;
    while (b) {
      uint t = a / b;
      a -= t * b; swap(a, b);
      u -= t * v; swap(u, v);
    }
    if (u < 0) u += M;
    return modular_int(u);
  }
  this(modular_int a) { x = a.x; }
  this(long a) { a %= M; if (a < 0) a += M; x = cast(int)a; }
  ref modular_int opAssign(long a) { return (this = modular_int(a)); }
  ref modular_int opOpAssign(string op)(modular_int a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x & (1U << 31)) x += M; }
    else static if (op == "*") { x = cast(uint)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref modular_int opOpAssign(string op)(long a) {
    static if (op == "^^") {
      modular_int t2 = this, te = modular_int(1);
      if (a < 0) a = -a, t2 = t2.inv();
      for (long e = a; e; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = te.x;
      return this;
    }
    else return mixin("this " ~ op ~ "= modular_int(a)");
  }
  modular_int opUnary(string op)() const if (op == "-") {
    return modular_int(M - x);
  }
  modular_int opBinary(string op, T)(T a) const {
    return mixin("modular_int(this) " ~ op ~ "= a");
  }
  modular_int opBinaryRight(string op)(long a) const {
    return mixin("modular_int(a) " ~ op ~ "= this");
  }
  T to(T)() const {
    return x.to!T;
  }
}
alias modint = modular_int!998244353;


An important meeting is to be held and there are exactly $$$n$$$ people invited. At any moment, any two people can step back and talk in private. The same two people can talk several (as many as they want) times per meeting.Each person has limited sociability. The sociability of the $$$i$$$-th person is a non-negative integer $$$a_i$$$. This means that after exactly $$$a_i$$$ talks this person leaves the meeting (and does not talk to anyone else anymore). If $$$a_i = 0$$$, the $$$i$$$-th person leaves the meeting immediately after it starts.A meeting is considered most productive if the maximum possible number of talks took place during it.You are given an array of sociability $$$a$$$, determine which people should talk to each other so that the total number of talks is as large as possible.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of each test case description contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) —the number of people in the meeting. The second line consists of $$$n$$$ space-separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2 \cdot 10^5$$$) — the sociability parameters of all people.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of all $$$a_i$$$ (over all test cases and all $$$i$$$) does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ answers to all test cases. On the first line of each answer print the number $$$k$$$ — the maximum number of talks possible in a meeting. On each of the next $$$k$$$ lines print two integers $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$ and $$$i \neq j$$$) — the numbers of people who will have another talk. If there are several possible answers, you may print any of them.

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	auto pq = redBlackTree!("a > b", int[2])();
	foreach(i, ai; a)
	{
		int[2] toInsert = [ai, cast(int)i];
		pq.insert(toInsert);
	}
	auto talks = new int[2][](0);
	while (pq.length >= 2)
	{
		auto x = pq.front; pq.removeFront;
		auto y = pq.front; pq.removeFront;
		auto xv = x[0]; auto xi = x[1];
		auto yv = y[0]; auto yi = y[1];
		assert(xv == a[xi]);
		assert(yv == a[yi]);
		if (xv <= 0 || yv <= 0) break;
		talks ~= [xi, yi];
		a[xi]--;
		a[yi]--;
		int[2] insX = [a[xi], xi];
		int[2] insY = [a[yi], yi];
		pq.insert(insX);
		pq.insert(insY);
	}
	talks.length.writeln;
	foreach(talk; talks) writeln(talk[0]+1, " ", talk[1]+1);
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}


Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.It is an undirected weighted graph on $$$n$$$ vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either $$$0$$$ or $$$1$$$; exactly $$$m$$$ edges have weight $$$1$$$, and all others have weight $$$0$$$.Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq \min(\frac{n(n-1)}{2},10^5)$$$), the number of vertices and the number of edges of weight $$$1$$$ in the graph.  The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$), the endpoints of the $$$i$$$-th edge of weight $$$1$$$. It is guaranteed that no edge appears twice in the input.

Output a single integer, the weight of the minimum spanning tree of the graph.

NoteThe graph from the first sample is shown below. Dashed edges have weight $$$0$$$, other edges have weight $$$1$$$. One of the minimum spanning trees is highlighted in orange and has total weight $$$2$$$.  In the second sample, all edges have weight $$$0$$$ so any spanning tree has total weight $$$0$$$.

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto adj = new bool [int] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			adj[u][v] = true;
			adj[v][u] = true;
		}

		long res = -1;
		auto p = n.iota.array;
		int [] q;

		while (!p.empty)
		{
			if (q.empty)
			{
				int u = p[$ - 1];
				q ~= u;
				p.length -= 1;
				res += 1;
			}
			else
			{
				int v = q[0];
				q = q[1..$];
				q.assumeSafeAppend ();

				for (int i = 0; i < p.length; i++)
				{
					int u = p[i];
					if (u !in adj[v])
					{
						q ~= u;
						swap (p[i], p[$ - 1]);
						p.length -= 1;
						i -= 1;
					}
				}
			}
		}

		writeln (res);
	}
}

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.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)); }

enum INF = 10^^9;

int segN;
Tuple!(int, int)[] seg;

void update(int a, int val) {
  seg[a += segN][0] += val;
  for (; a >>= 1; ) {
    seg[a] = min(seg[a << 1], seg[a << 1 | 1]);
  }
}

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

      auto G = new int[][N];
      foreach (i; 0 .. M) {
        G[A[i]] ~= B[i];
        G[B[i]] ~= A[i];
      }

      for (segN = 1; segN < N; segN <<= 1) {}
      seg.length = segN << 1;
      seg[] = tuple(INF, -1);
      foreach (u; 0 .. N) {
        seg[segN + u] = tuple(0, u);
      }
      foreach_reverse (a; 1 .. segN) {
        seg[a] = min(seg[a << 1], seg[a << 1 | 1]);
      }

      int ans;
      foreach (h; 0 .. N) {
        const u = seg[1][1];
        debug {
          writeln("u = ", u);
        }
        if (seg[1][0] == h) {
          debug {
            writeln("  new comp");
          }
          ++ans;
        }
        update(u, INF);
        foreach (v; G[u]) {
          update(v, 1);
        }
      }
      --ans;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $$$s_1 s_2 \ldots s_n$$$. It is necessary to make this string non-decreasing in the least number of operations. In other words, each character should be not less than the previous. In one operation, you can do the following: Select an arbitrary index $$$1 \leq i \leq n$$$ in the string; For all $$$j \geq i$$$, change the value in the $$$j$$$-th position to the opposite, that is, if $$$s_j = 1$$$, then make $$$s_j = 0$$$, and vice versa.What is the minimum number of operations needed to make the string non-decreasing?

Each test consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of test cases follows. The first line of each test cases a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the string. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the minimum number of operations that are needed to make the string non-decreasing.

NoteIn the first test case, the string is already non-decreasing.In the second test case, you can select $$$i = 1$$$ and then $$$s = \mathtt{01}$$$.In the third test case, you can select $$$i = 1$$$ and get $$$s = \mathtt{010}$$$, and then select $$$i = 2$$$. As a result, we get $$$s = \mathtt{001}$$$, that is, a non-decreasing string.In the sixth test case, you can select $$$i = 5$$$ at the first iteration and get $$$s = \mathtt{100001}$$$. Then choose $$$i = 2$$$, then $$$s = \mathtt{111110}$$$. Then we select $$$i = 1$$$, getting the non-decreasing string $$$s = \mathtt{000001}$$$.

import std.stdio;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;
import std.functional;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

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 solve() {
    int n = read!int;
    dchar[] s = readln.strip.to!(dchar[]);
    s = s.uniq.array;
    auto s1 = s.dup;
    foreach(ref e; s1)
        if (e == '0')
            e = '1';
        else
            e = '0';

    if (n == 1) {
        writeln(0);
        return;
    }
    int res;
    bool flip = false;
    bool up = true;
    n = cast(int) s.length;
    foreach(i; 0 .. n) {
        if (i != n - 1) {
            if (up) {
                if (s[i] > s[i+1]) {
                    res++;
                    flip = true;
                    up = !up;
                }
            }
            else {
                if (s1[i] > s1[i+1]) {
                    res++;
                    up = !up;
                }
            }
        }
    }
    if (flip)
        if (up) {
            if (s[n-1] == '0') {
                res++;
            }
        }
        else {
            if (s1[n-1] == '0') {
                res++;
            }
        }
    writeln(res);
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}