There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight ai.For example, if weights are [1, 2, 2, 2, 1, 2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are:  the first monster can't eat the second monster because a1 = 1 is not greater than a2 = 2;  the second monster can't eat the third monster because a2 = 2 is not greater than a3 = 2;  the second monster can't eat the fifth monster because they are not neighbors;  the second monster can eat the first monster, the queue will be transformed to [3, 2, 2, 1, 2]. After some time, someone said a good joke and all monsters recovered. At that moment there were k (k ≤ n) monsters in the queue, the j-th of which had weight bj. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last.You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other.

The first line contains single integer n (1 ≤ n ≤ 500) — the number of monsters in the initial queue. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial weights of the monsters. The third line contains single integer k (1 ≤ k ≤ n) — the number of monsters in the queue after the joke.  The fourth line contains k integers b1, b2, ..., bk (1 ≤ bj ≤ 5·108) — the weights of the monsters after the joke.  Monsters are listed in the order from the beginning of the queue to the end.

In case if no actions could lead to the final queue, print "NO" (without quotes) in the only line.  Otherwise print "YES" (without quotes) in the first line. In the next n - k lines print actions in the chronological order. In each line print x — the index number of the monster in the current queue which eats and, separated by space, the symbol 'L' if the monster which stays the x-th in the queue eats the monster in front of him, or 'R' if the monster which stays the x-th in the queue eats the monster behind him. After each eating the queue is enumerated again.  When one monster eats another the queue decreases. If there are several answers, print any of them.

NoteIn the first example, initially there were n = 6 monsters, their weights are [1, 2, 2, 2, 1, 2] (in order of queue from the first monster to the last monster). The final queue should be [5, 5]. The following sequence of eatings leads to the final queue:  the second monster eats the monster to the left (i.e. the first monster), queue becomes [3, 2, 2, 1, 2];  the first monster (note, it was the second on the previous step) eats the monster to the right (i.e. the second monster), queue becomes [5, 2, 1, 2];  the fourth monster eats the mosnter to the left (i.e. the third monster), queue becomes [5, 2, 3];  the finally, the third monster eats the monster to the left (i.e. the second monster), queue becomes [5, 5]. Note that for each step the output contains numbers of the monsters in their current order in the queue.

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 = 10 ^^ 9 + 23;

void main()
{
    int[2] ns;
    int[][2] arr;

    foreach (i; 0 .. 2) {
        readf("%s", &ns[i]);
        readln;
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    Tuple!(int, char)[] ans;
    int i = ns[0] - 1, gidx = ns[1]-1;
    for ( ; i >= 0 && gidx >= 0; ) {
        int cursm = 0;
        int j = i;
        while (j >= 0 && cursm < arr[1][gidx]) {
            cursm += arr[0][j];
            j -= 1;
        }

        debug { writeln(j+1, ' ', i, ' ', cursm, ' ', arr[1][gidx]); }

        if (cursm > arr[1][gidx]) {
            writeln("NO");
            return;
        }

        bool segAns(int le, int r) {
            if (r - le + 1 == 1) { return true; }

            int mx = arr[0][le .. r+1].maxElement;
            Nullable!int start;
            for (int k = le; k <= r; ++k) {
                if (arr[0][k] != mx) { continue; }
                if ((k > le && arr[0][k-1] < mx) || (k < r && arr[0][k+1] < mx)) {
                    start = k;
                    break;
                }
            }

            if (start.isNull) { return false; }

            int curidx = start + 1;
            int cursz = arr[0][start];
            int lb = start-1, rb = start+1;
            while (lb >= le || rb <= r) {
                if (lb >= le && arr[0][lb] < cursz) {
                    cursz += arr[0][lb];
                    ans ~= tuple(curidx, 'L');
                    curidx -= 1;
                    lb -= 1;
                } else {
                    cursz += arr[0][rb];
                    ans ~= tuple(curidx, 'R');
                    rb += 1;
                }
            }

            return true;
        }

        if (! segAns(j+1, i)) {
            writeln("NO");
            return;
        }

        i = j;
        gidx -= 1;
    }

    if (i >= 0 || gidx >= 0) {
        writeln("NO");
        return;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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 = 10 ^^ 9 + 23;

void main()
{
    int[2] ns;
    int[][2] arr;

    foreach (i; 0 .. 2) {
        readf("%s", &ns[i]);
        readln;
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    Tuple!(int, char)[] ans;
    int i = ns[0] - 1, gidx = ns[1]-1;
    for ( ; i >= 0 && gidx >= 0; ) {
        int cursm = 0;
        int j = i;
        while (j >= 0 && cursm < arr[1][gidx]) {
            cursm += arr[0][j];
            j -= 1;
        }

        debug { writeln(j+1, ' ', i, ' ', cursm, ' ', arr[1][gidx]); }

        if (cursm > arr[1][gidx]) {
            writeln("NO");
            return;
        }

        int mx = arr[0][j+1 .. i+1].maxElement;
        int mn = arr[0][j+1 .. i+1].minElement;
        if (i - j > 1 && mx == mn) {
            writeln("NO");
            return;
        }

        int start = j+1;
        for (int k = j+1; k <= i; ++k) {
            if (arr[0][k] != mx) { continue; }
            if ((k > j+1 && arr[0][k-1] < mx) || (k < i && arr[0][k+1] < mx)) {
                start = k;
                break;
            }
        }

        int curidx = start + 1;
        int cursz = arr[0][start];
        int lb = start-1, rb = start+1;
        while (lb > j || rb <= i) {
            if (lb > j && arr[0][lb] < cursz) {
                cursz += arr[0][lb];
                ans ~= tuple(curidx, 'L');
                curidx -= 1;
                lb -= 1;
            } else {
                cursz += arr[0][rb];
                ans ~= tuple(curidx, 'R');
                rb += 1;
            }
        }

        i = j;
        gidx -= 1;
    }

    if (i >= 0 || gidx >= 0) {
        writeln("NO");
        return;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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 = 10 ^^ 9 + 23;

void main()
{
    int[2] ns;
    int[][2] arr;

    foreach (i; 0 .. 2) {
        readf("%s", &ns[i]);
        readln;
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    Tuple!(int, char)[] ans;
    int gidx = ns[1]-1;
    for (int i = ns[0]-1; i >= 0 && gidx >= 0; ) {
        int cursm = 0;
        int j = i;
        while (j >= 0 && cursm < arr[1][gidx]) {
            cursm += arr[0][j];
            j -= 1;
        }

        debug { writeln(j+1, ' ', i, ' ', cursm, ' ', arr[1][gidx]); }

        if (cursm > arr[1][gidx]) {
            writeln("NO");
            return;
        }

        int mx = arr[0][j+1 .. i+1].maxElement;
        int mn = arr[0][j+1 .. i+1].minElement;
        if (i - j > 1 && mx == mn) {
            writeln("NO");
            return;
        }

        int start = j+1;
        for (int k = j+1; k <= i; ++k) {
            if (arr[0][k] != mx) { continue; }
            if ((k > j+1 && arr[0][k-1] < mx) || (k < i && arr[0][k+1] < mx)) {
                start = k;
                break;
            }
        }

        int curidx = start + 1;
        int cursz = arr[0][start];
        int lb = start-1, rb = start+1;
        while (lb > j || rb <= i) {
            if (lb > j && arr[0][lb] < cursz) {
                cursz += arr[0][lb];
                ans ~= tuple(curidx, 'L');
                curidx -= 1;
                lb -= 1;
            } else {
                cursz += arr[0][rb];
                ans ~= tuple(curidx, 'R');
                rb += 1;
            }
        }

        i = j;
        gidx -= 1;
    }

    if (gidx >= 0) {
        writeln("NO");
        return;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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 = 10 ^^ 9 + 23;

void main()
{
    int[2] ns;
    int[][2] arr;

    foreach (i; 0 .. 2) {
        readf("%s", &ns[i]);
        readln;
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    Tuple!(int, char)[] ans;
    int gidx = ns[1]-1;
    for (int i = ns[0]-1; i >= 0 && gidx >= 0; ) {
        int cursm = 0;
        int j = i;
        while (j >= 0 && cursm < arr[1][gidx]) {
            cursm += arr[0][j];
            j -= 1;
        }

        debug { writeln(j+1, ' ', i, ' ', cursm, ' ', arr[1][gidx]); }

        if (cursm > arr[1][gidx]) {
            writeln("NO");
            return;
        }

        int mx = arr[0][j+1 .. i+1].maxElement;
        int mn = arr[0][j+1 .. i+1].minElement;
        if (mx == mn) {
            writeln("NO");
            return;
        }

        int start = 0;
        for (int k = j+1; k <= i; ++k) {
            if (arr[0][k] != mx) { continue; }
            if ((k > j+1 && arr[0][k-1] < mx) || (k < i && arr[0][k+1] < mx)) {
                start = k;
                break;
            }
        }

        int curidx = start + 1;
        int cursz = arr[0][start];
        int lb = start-1, rb = start+1;
        while (lb > j || rb <= i) {
            if (lb > j && arr[0][lb] < cursz) {
                ans ~= tuple(curidx, 'L');
                curidx -= 1;
                lb -= 1;
            } else {
                ans ~= tuple(curidx, 'R');
                rb += 1;
            }
        }

        i = j;
        gidx -= 1;
    }

    if (gidx >= 0) {
        writeln("NO");
        return;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}


Peter decided to lay a parquet in the room of size n × m, the parquet consists of tiles of size 1 × 2. When the workers laid the parquet, it became clear that the tiles pattern looks not like Peter likes, and workers will have to re-lay it.The workers decided that removing entire parquet and then laying it again is very difficult task, so they decided to make such an operation every hour: remove two tiles, which form a 2 × 2 square, rotate them 90 degrees and put them back on the same place.  They have no idea how to obtain the desired configuration using these operations, and whether it is possible at all.Help Peter to make a plan for the workers or tell that it is impossible. The plan should contain at most 100 000 commands.

The first line contains integer n and m, size of the room (1 ≤ n, m ≤ 50). At least one of them is even number. The following n lines contain m characters each, the description of the current configuration of the parquet tiles. Each character represents the position of the half-tile. Characters 'L', 'R', 'U' and 'D' correspond to the left, right, upper and lower halves, respectively. The following n lines contain m characters each, describing the desired configuration in the same format.

In the first line output integer k, the number of operations. In the next k lines output description of operations. The operation is specified by coordinates (row and column) of the left upper half-tile on which the operation is performed. If there is no solution, output -1 in the first line.

NoteIn the first sample test first operation is to rotate two rightmost tiles, after this all tiles lie vertically. Second operation is to rotate two leftmost tiles, after this we will get desired configuration.

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;

int rows;
int cols;

struct Board {
    bool [] [] contents;
    alias contents this;

    this (int rows, int cols) {
        contents = new bool [] [] (rows, cols);
    }
}

Board readConfig () {
    auto res = Board (rows, cols);
    foreach (row; 0..rows)
 {
        auto line = readln.strip;
        foreach (col; 0..cols)
     {
            res[row][col] = "LR".canFind (line[col]);
        }
    }
    return res;
}

Board trans (const ref Board b) {
    int rows = cast (int) b.length;
    int cols = cast (int) b.front.length;
    auto res = Board (cols, rows);
    foreach (row; 0..rows)
        foreach (col; 0..cols)
            res[col][row] = !b[row][col];
    return res;
}

auto solve (Board b) {
    bool doTrans = cols & 1;
    if (doTrans) {
        b = trans (b);
        swap (rows, cols);
    }

    int [2] [] res;
    foreach (row; 0..rows) {
        foreach (col; 0..cols) {
            if (!b[row][col]) {
                int [2] [] cur;
                int cRow = row;
                int cCol = col;
                while (true) {
                    debug {writefln
                        ("%s %s\n%(%(%6s%)\n%)",
                        cRow, cCol, b);}
                    cur ~= [cRow, cCol];
                    cCol += 1;
                    if (!b[cRow][cCol]) {
                        break;
                    }
                    debug {writefln
                        ("%s %s\n%(%(%6s%)\n%)",
                        cRow, cCol, b);}
                    cur ~= [cRow, cCol];
                    cRow += 1;
                    if (b[cRow][cCol]) {
                        break;
                    }
                }
                foreach_reverse (p; cur) {
                    res ~= p;
                    b[p[0] + 0][p[1] + 0] ^= true;
                    b[p[0] + 0][p[1] + 1] ^= true;
                    b[p[0] + 1][p[1] + 0] ^= true;
                    b[p[0] + 1][p[1] + 1] ^= true;
                }
            }
        }
    }

    if (doTrans) {
        foreach (ref p; res)
            swap (p[0], p[1]);
        swap (rows, cols);
    }
    foreach (ref p; res)
        p[] += 1;
    return res;
}

void main () {
    while (readf (" %s %s", &rows, &cols) > 0) {
        readln;
        auto a = readConfig ();
        auto b = readConfig ();
        auto x = a.solve ();
        auto y = b.solve ();
        auto ans = chain (x, y.retro).array;
        writeln (ans.length);
        writefln ("%(%(%s %)\n%)", ans);
    }
}

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;

int rows;
int cols;

struct Board
{
	bool [] [] contents;
	alias contents this;

	this (int rows, int cols)
	{
		contents = new bool [] [] (rows, cols);
	}
}

Board readConfig ()
{
	auto res = Board (rows, cols);
	foreach (row; 0..rows)
	{
		auto line = readln.strip;
		foreach (col; 0..cols)
		{
			res[row][col] = "LR".canFind (line[col]);
		}
	}
	return res;
}

Board trans (const ref Board b)
{
	int rows = cast (int) b.length;
	int cols = cast (int) b.front.length;
	auto res = Board (cols, rows);
	foreach (row; 0..rows)
	{
		foreach (col; 0..cols)
		{
			res[col][row] = !b[row][col];
		}
	}
	return res;
}

auto solve (Board b)
{
	bool doTrans = cols & 1;
	if (doTrans)
	{
		b = trans (b);
		swap (rows, cols);
	}

	int [2] [] res;
	foreach (row; 0..rows)
	{
		foreach (col; 0..cols)
		{
			if (!b[row][col])
			{
				int [2] [] cur;
				int cRow = row;
				int cCol = col;
				while (true)
				{
					debug {writefln
					    ("%s %s\n%(%(%6s%)\n%)",
					    cRow, cCol, b);}
					cur ~= [cRow, cCol];
					cCol += 1;
					if (!b[cRow][cCol])
					{
						break;
					}
					debug {writefln
					    ("%s %s\n%(%(%6s%)\n%)",
					    cRow, cCol, b);}
					cur ~= [cRow, cCol];
					cRow += 1;
					if (b[cRow][cCol])
					{
						break;
					}
				}
				foreach_reverse (p; cur)
				{
					res ~= p;
					b[p[0] + 0][p[1] + 0] ^= true;
					b[p[0] + 0][p[1] + 1] ^= true;
					b[p[0] + 1][p[1] + 0] ^= true;
					b[p[0] + 1][p[1] + 1] ^= true;
				}
			}
		}
	}

	if (doTrans)
	{
		foreach (ref p; res)
		{
			swap (p[0], p[1]);
		}
		swap (rows, cols);
	}
	foreach (ref p; res)
	{
		p[] += 1;
	}
	return res;
}

void main ()
{
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		readln;
		auto a = readConfig ();
		auto b = readConfig ();
		auto x = a.solve ();
		auto y = b.solve ();
		auto ans = chain (x, y.retro).array;
		writeln (ans.length);
		writefln ("%(%(%s %)\n%)", ans);
	}
}


Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting of m partitions. Partition with index i has ai rows from A. Similarly, second cluster containing table B has n partitions, i-th one having bi rows from B. In one network operation she can copy one row from any partition to any other partition. At the end, for each row from A and each row from B there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.

First line contains two integer numbers, m and n (1 ≤ m, n ≤ 105). Second line contains description of the first cluster with m space separated integers, ai (1 ≤ ai ≤ 109). Similarly, third line describes second cluster with n space separated integers, bi (1 ≤ bi ≤ 109).

Print one integer — minimal number of copy operations.

NoteIn the first example it makes sense to move all the rows to the second partition of the second cluster which is achieved in 2 + 6 + 3 = 11 operationsIn the second example Piegirl can copy each row from B to the both partitions of the first cluster which needs 2·3 = 6 copy operations.

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;
import core.bitop;

void main ()
{
	int m, n;
	while (readf (" %s %s", &m, &n) > 0)
	{
		auto a = new int [m];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}
		auto b = new int [n];
		foreach (ref x; b)
		{
			readf (" %s", &x);
		}
		sort !("a < b", SwapStrategy.stable) (a);
		sort !("a < b", SwapStrategy.stable) (b);
		auto as = new long [m + 1];
		foreach (i; 0..m)
		{
			as[i + 1] = as[i] + a[i];
		}
		auto bs = new long [n + 1];
		foreach (i; 0..n)
		{
			bs[i + 1] = bs[i] + b[i];
		}

		long res = long.max / 4;
		foreach (i; 0..m)
		{
			if (long.max / 4 / (m - i) <= bs[n])
			{
				continue;
			}
			long cur = (m - i) * bs[n];
			cur += as[i];
			res = min (res, cur);
		}
		foreach (i; 0..n)
		{
			if (long.max / 4 / (n - i) <= as[m])
			{
				continue;
			}
			long cur = (n - i) * as[m];
			cur += bs[i];
			res = min (res, cur);
		}
		writeln (res);
	}
}

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

//	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, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	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)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in 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)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

immutable INF = 1_000_000_000_000_000_000;

int M, N;
long[] A, B;

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = new long[M];
		B = new long[N];
		foreach (i; 0 .. M) {
			A[i] = readLong;
		}
		foreach (j; 0 .. N) {
			B[j] = readLong;
		}

		A.sort();
		B.sort();
		long[] ASum = new long[M + 1];
		long[] BSum = new long[N + 1];
		foreach (i; 0 .. M) {
			ASum[i + 1] = ASum[i] + A[i];
		}
		foreach (j; 0 .. N) {
			BSum[j + 1] = BSum[j] + B[j];
		}

		long ans = INF;
		foreach (x; 1 .. M + 1) {
			if (BSum[N] > INF / x) {
				continue;
			}
			chmin(ans, ASum[M - x] + x * BSum[N]);
		}
		foreach (x; 1 .. N + 1) {
			if (ASum[M] > INF / x) {
				continue;
			}
			chmin(ans, BSum[N - x] + x * ASum[M]);
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}

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

//	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, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	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)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in 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)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

immutable INF = 1_000_000_000_000_000_000;

int M, N;
long[] A, B;

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = new long[M];
		B = new long[N];
		foreach (i; 0 .. M) {
			A[i] = readLong;
		}
		foreach (j; 0 .. N) {
			B[j] = readLong;
		}

		A.sort();
		B.sort();
		long[] ASum = new long[M + 1];
		long[] BSum = new long[N + 1];
		foreach (i; 0 .. M) {
			ASum[i + 1] = ASum[i] + A[i];
		}
		foreach (j; 0 .. N) {
			BSum[j + 1] = BSum[j] + B[j];
		}

		long ans = INF;
		foreach (x; 1 .. M + 1) {
			chmin(ans, ASum[M - x] + x * BSum[N]);
		}
		foreach (x; 1 .. N + 1) {
			chmin(ans, BSum[N - x] + x * ASum[M]);
		}

		{
			long now;
			foreach (x; 1 .. M + 1) {
				now += A[M - x] + BSum[N] - max(A[M - x], B[N - 1]);
				chmin(ans, now + ASum[M - x]);
			}
		}
		{
			long now;
			foreach (x; 1 .. N + 1) {
				now += B[N - x] + ASum[M] - max(B[N - x], A[M - 1]);
				chmin(ans, now + BSum[N - x]);
			}
		}

		writeln(ans);

	}
	} catch (EOFException) {}
}

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

//	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, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	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)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in 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)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

immutable INF = 1_000_000_000_000_000_000;

int M, N;
long[] A, B;

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = new long[M];
		B = new long[N];
		foreach (i; 0 .. M) {
			A[i] = readLong;
		}
		foreach (j; 0 .. N) {
			B[j] = readLong;
		}

		A.sort();
		B.sort();
		long[] ASum = new long[M + 1];
		long[] BSum = new long[N + 1];
		foreach (i; 0 .. M) {
			ASum[i + 1] = ASum[i] + A[i];
		}
		foreach (j; 0 .. N) {
			BSum[j + 1] = BSum[j] + B[j];
		}

		long ans = INF;
		foreach (x; 1 .. M + 1) {
			chmin(ans, x * ASum[M - x] + x * BSum[N]);
		}
		foreach (x; 1 .. N + 1) {
			chmin(ans, x * BSum[N - x] + x * ASum[M]);
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}


This is an interactive problem.Initially, there is an array $$$a = [1, 2, \ldots, n]$$$, where $$$n$$$ is an odd positive integer. The jury has selected $$$\frac{n-1}{2}$$$ disjoint pairs of elements, and then the elements in those pairs are swapped. For example, if $$$a=[1,2,3,4,5]$$$, and the pairs $$$1 \leftrightarrow 4$$$ and $$$3 \leftrightarrow 5$$$ are swapped, then the resulting array is $$$[4, 2, 5, 1, 3]$$$. As a result of these swaps, exactly one element will not change position. You need to find this element.To do this, you can ask several queries. In each query, you can pick two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$). In return, you will be given the elements of the subarray $$$[a_l, a_{l + 1}, \dots, a_r]$$$ sorted in increasing order. Find the element which did not change position. You can make at most $$$\mathbf{15}$$$ queries.The array $$$a$$$ is fixed before the interaction and does not change after your queries.Recall that an array $$$b$$$ is a subarray of the array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 500$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n < 10^4$$$; $$$n$$$ is odd) — the length of the array $$$a$$$. After reading the first line of each test case, you should begin the interaction. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

NoteIn the first test, the interaction proceeds as follows. SolutionJuryExplanation$$$\texttt{2}$$$There are 2 test cases.$$$\texttt{5}$$$In the first test case, the hidden array is $$$[4,2,5,1,3]$$$, with length $$$5$$$.$$$\texttt{? 1 4}$$$$$$\texttt{1 2 4 5}$$$The solution requests the subarray $$$[4,2,5,1]$$$ in increasing order, and the jury responds with $$$[1,2,4,5]$$$.$$$\texttt{? 3 5}$$$$$$\texttt{1 3 5}$$$The solution requests the subarray $$$[5,1,3]$$$ in increasing order, and the jury responds with $$$[1,3,5]$$$.$$$\texttt{! 2}$$$The solution has somehow determined that $$$a_2=2$$$, and outputs it. Since the output is correct, the jury continues to the next test case.$$$\texttt{3}$$$In the second test case, the hidden array is $$$[1,3,2]$$$, with length $$$3$$$.$$$\texttt{? 1 1}$$$$$$\texttt{1}$$$The solution requests the number $$$[1]$$$ only, and the jury responds with $$$[1]$$$.$$$\texttt{! 1}$$$The solution has determined that $$$a_1=1$$$, and outputs it. Since the output is correct and there are no more test cases, the jury and the solution exit. Note that the line breaks in the example input and output are for the sake of clarity, and do not occur in the real interaction.

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

alias ll = ulong;
void solve()
{
    int[][Tuple!(immutable ll, immutable ll)] mp;
    auto get = (immutable ll l, immutable ll r) {
        auto tup = tuple(l, r);
        if (auto val = tup in mp)
            return *val;
        writefln!("? %s %s")(l, r);
        stdout.flush;
        return mp[tup] = readln.splitter.map!(to!int).array;
    };

    ll n;
    readf!(" %s")(n);
    readln;
    ll l = 1, r = n;
    while (l <= r)
    {
        ll mid = (l + r) / 2;
        auto swaps = get(l, mid).count!(x => l <= x && x <= mid);
        if (swaps % 2 == 0)
            l = mid + 1;
        else
            r = mid - 1;
    }
    writefln!("! %s")(l);
    stdout.flush;
}

void main()
{
    size_t TC = 1;
    TC = readln.strip.to!int;
    foreach (_; 0 .. TC)
        solve();
}

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

alias ll = ulong;
void solve()
{
    auto get = (ll l, ll r) {
        writefln!("? %s %s")(l, r);
        stdout.flush;
        return readln.splitter.map!(to!int);
    };

    ll n;
    readf!(" %s")(n);
    readln;
    ll l = 1, r = n;
    while (l <= r)
    {
        ll mid = (l + r) / 2;
        auto swaps = get(l, mid).count!(x => l <= x && x <= mid);
        if (swaps % 2 == 0)
            l = mid + 1;
        else
            r = mid - 1;
    }
    writefln!("! %s")(l);
    stdout.flush;
}

void main()
{
    size_t TC = 1;
    TC = readln.strip.to!int;
    foreach (_; 0 .. TC)
        solve();
}

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

int main(string[] args)
{
    auto t = to!int(readln.strip);
    foreach (_; 0 .. t)
    {
        auto n = to!int(readln.strip);
        auto left = 1, right = n;
        while (left < right)
        {
            auto mid = (left + right) >> 1;
            writeln("? ", left, " ", mid);
            stdout.flush;
            auto r = map!(to!int)(readln.strip.split(" ")).array;
            int c, i, j = left;
            while (i < r.length && j <= mid)
            {
                if (r[i] < j) ++ i;
                else if (r[i] > j) j = r[i];
                else ++ i, ++ j, ++ c;
            }
            if (c & 1) right = mid;
            else left = mid + 1;
        }
        writeln("! ", left);
        stdout.flush;
    }
    return 0;
}

import std.stdio;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

int[] ask(int l, int r) {
    writefln("? %s %s", l, r);
    stdout.flush;
    return readln.chomp.split(" ").map!(to!int).array;
}

void solve() {
    int N = readln.chomp.to!int;

    int f(int l, int r) {
        if (l == r) return l;
        int[] xs = ask(l, (l+r)/2);
        int R = 0;
        foreach (i, x; xs) {
            if (l <= x && x <= (l+r)/2) {
                R++;
            }
        }
        //stderr.writefln("(%s, %s) -> %s", l, r, R);
        if (R % 2 == 1) {
            r = (l + r) / 2;
        } else {
            l = (l + r) / 2 + 1;
        }
        return f(l, r);
    }

    int ans = f(1, N);
    writefln("! %s", ans);
    stdout.flush;
}

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

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)
	{
		auto n = readln.strip.to !(int);
		int lo = 1;
		int hi = n + 1;
		while (hi - lo > 1)
		{
			int me = (lo + hi) / 2;
			writefln !("? %s %s") (lo, me - 1);
			stdout.flush ();
			auto a = readln.splitter.map !(to !(int)).array;
			auto num = a.count !(x => lo <= x && x <= me - 1);
			if (num % 2 == 0)
			{
				lo = me;
			}
			else
			{
				hi = me;
			}
		}
		writefln !("! %s") (lo);
		stdout.flush ();
	}
}

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

alias ll = ulong;
void solve()
{
    auto get_ = (ll l, ll r) {
        writefln!("? %s %s")(l, r);
        stdout.flush;
        return readln.splitter.map!(to!int);
    };
    alias get = memoize!get_;
    ll n;
    readf!(" %s")(n);
    readln;
    ll l = 1, r = n;
    while (l <= r)
    {
        ll mid = (l + r) / 2;
        auto swaps = get(l, mid).count!(x => l <= x && x <= mid);
        if (swaps % 2 == 0)
            l = mid + 1;
        else
            r = mid - 1;
    }
    writefln!("! %s")(l);
    stdout.flush;
}

void main()
{
    size_t TC = 1;
    TC = readln.strip.to!int;
    foreach (_; 0 .. TC)
        solve();
}


Polycarp has $$$n$$$ coins, the value of the $$$i$$$-th coin is $$$a_i$$$. It is guaranteed that all the values are integer powers of $$$2$$$ (i.e. $$$a_i = 2^d$$$ for some non-negative integer number $$$d$$$).Polycarp wants to know answers on $$$q$$$ queries. The $$$j$$$-th query is described as integer number $$$b_j$$$. The answer to the query is the minimum number of coins that is necessary to obtain the value $$$b_j$$$ using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value $$$b_j$$$, the answer to the $$$j$$$-th query is -1.The queries are independent (the answer on the query doesn't affect Polycarp's coins).

The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of coins and the number of queries. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ — values of coins ($$$1 \le a_i \le 2 \cdot 10^9$$$). It is guaranteed that all $$$a_i$$$ are integer powers of $$$2$$$ (i.e. $$$a_i = 2^d$$$ for some non-negative integer number $$$d$$$). The next $$$q$$$ lines contain one integer each. The $$$j$$$-th line contains one integer $$$b_j$$$ — the value of the $$$j$$$-th query ($$$1 \le b_j \le 10^9$$$).

Print $$$q$$$ integers $$$ans_j$$$. The $$$j$$$-th integer must be equal to the answer on the $$$j$$$-th query. If Polycarp can't obtain the value $$$b_j$$$ the answer to the $$$j$$$-th query is -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.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

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

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

    int[40] vals;
    coins.each!(e => ++vals[bsr(e)]);

    debug { vals.writeln; }

    int getAnsForBit(int b, int need, ref int[] vals) {
        int ans = 0;
        if (b == -1) return -1;

        auto saved = min(need, vals[b]);
        need -= saved;
        vals[b] -= saved;
        ans += saved;

        if (need > 0) {
            auto borrow = getAnsForBit(b-1, 2 * need, vals);
            if (borrow == -1) return -1;

            ans += borrow;
        }

        return ans;
    }

    while (q--) {
        uint x;
        readf("%s", &x);
        readln;

        auto ans = 0;
        auto nowvals = vals.dup;
        foreach_reverse (b; 0 .. 32) {
            if (x & (1U << b)) {
                auto cur = getAnsForBit(b, 1, nowvals);
                if (cur == -1) {
                    ans = -1;
                    break;
                }

                ans += cur;
            }
        }

        ans.writeln;
    }

}

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.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

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

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

    int[40] vals;
    coins.each!(e => ++vals[bsr(e)]);

    debug { vals.writeln; }

    while (q--) {
        uint x;
        readf("%s", &x);
        readln;

        auto ans = 0;
        auto nowvals = vals.dup;
        foreach_reverse (b; 0 .. 32) {
            if (x & (1U << b)) {

                int getAns(int b, int need) {
                    int ans = 0;
                    if (b == -1) return -1;

                    auto saved = min(need, nowvals[b]);
                    need -= saved;
                    nowvals[b] -= saved;
                    ans += saved;

                    if (need > 0) {
                        auto borrow = getAns(b-1, 2 * need);
                        if (borrow == -1) return -1;

                        ans += borrow;
                    }

                    return ans;
                }

                auto cur = getAns(b, 1);
                if (cur == -1) {
                    ans = -1;
                    break;
                }

                ans += cur;
            }
        }

        ans.writeln;
    }

}


Alice and Borys are playing tennis.A tennis match consists of games. In each game, one of the players is serving and the other one is receiving.Players serve in turns: after a game where Alice is serving follows a game where Borys is serving, and vice versa.Each game ends with a victory of one of the players. If a game is won by the serving player, it's said that this player holds serve. If a game is won by the receiving player, it's said that this player breaks serve.It is known that Alice won $$$a$$$ games and Borys won $$$b$$$ games during the match. It is unknown who served first and who won which games.Find all values of $$$k$$$ such that exactly $$$k$$$ breaks could happen during the match between Alice and Borys in total.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. Each of the next $$$t$$$ lines describes one test case and contains two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^5$$$; $$$a + b > 0$$$) — the number of games won by Alice and Borys, respectively. It is guaranteed that the sum of $$$a + b$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print two lines. In the first line, print a single integer $$$m$$$ ($$$1 \le m \le a + b + 1$$$) — the number of values of $$$k$$$ such that exactly $$$k$$$ breaks could happen during the match. In the second line, print $$$m$$$ distinct integers $$$k_1, k_2, \ldots, k_m$$$ ($$$0 \le k_1 < k_2 < \ldots < k_m \le a + b$$$) — the sought values of $$$k$$$ in increasing order.

NoteIn the first test case, any number of breaks between $$$0$$$ and $$$3$$$ could happen during the match:   Alice holds serve, Borys holds serve, Alice holds serve: $$$0$$$ breaks;  Borys holds serve, Alice holds serve, Alice breaks serve: $$$1$$$ break;  Borys breaks serve, Alice breaks serve, Alice holds serve: $$$2$$$ breaks;  Alice breaks serve, Borys breaks serve, Alice breaks serve: $$$3$$$ breaks. In the second test case, the players could either both hold serves ($$$0$$$ breaks) or both break serves ($$$2$$$ breaks).In the third test case, either $$$2$$$ or $$$3$$$ breaks could happen:   Borys holds serve, Borys breaks serve, Borys holds serve, Borys breaks serve, Borys holds serve: $$$2$$$ breaks;  Borys breaks serve, Borys holds serve, Borys breaks serve, Borys holds serve, Borys breaks serve: $$$3$$$ breaks.

immutable multi = true;

void solve(int tc)
{
	auto a = readInt!int;
	auto b = readInt!int;
	auto pk = new bool[](a + b + 1);
	void tryPair(int c0, int c1)
	{
		foreach(bi0; 0 .. c0+1)
		{
			auto bi1 = b - bi0;
			if (bi1 < 0 || bi1 > c1) continue;
			int breaks = bi0 + (c1 - bi1);
			pk[breaks] = true;
		}
	}
	auto m1 = (a+b)/2;
	auto m2 = (a+b) - m1;
	tryPair(m1, m2);
	tryPair(m2, m1);
	auto ks = new int[](0);
	foreach(k, hk; pk)
		if (hk) ks ~= cast(int)k;
	ks.length.writeln;
	foreach(k; ks) write(k, " ");
	writeln;
}

// main {{{
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;
// }}}

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)
	{
		int a, b;
		readf !(" %s %s") (a, b);
		auto n = a + b;
		auto h = n / 2;
		auto g = n - h;
		auto s = new bool [a + b + 1];
		foreach (k; 0..2)
		{
			for (int i = 0; i <= min (a, g); i++)
			{
				auto ag = i;
				auto ah = a - ag;
				auto bg = g - ag;
				auto bh = b - bg;
				if (0 <= ag && ag <= a && ag <= g &&
				    0 <= ah && ah <= a && ah <= h &&
				    0 <= bg && bg <= b && bg <= g &&
				    0 <= bh && bh <= b && bh <= h)
				{
					s[ah + bg] = true;
				}
			}
			swap (g, h);
		}
		writeln (s.sum);
		writefln !("%(%s %)") (iota (a + b + 1).filter !(x => s[x]));
	}
}

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 numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const A = readInt();
        const B = readInt();

        int[] ans;
        foreach (s; 0 .. 2) {
          const a = (A + B + s) / 2;
          const b = (A + B + (1 - s)) / 2;
          foreach (x; 0 .. a + 1) {
            if (x <= A) {
              const y = B - (a - x);
              if (y >= 0) {
                ans ~= A + B - x - y;
              }
            }
          }
        }

        ans = ans.sort.uniq.array;
        writeln(ans.length);
        foreach (i; 0 .. cast(int)(ans.length)) {
          if (i > 0) write(" ");
          write(ans[i]);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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

void solve(int a, int b, ref bool[int] possible_k)
{
  int n = a + b;
  foreach (ah ; 0 .. (n + 1) / 2 + 1) {
    int ab = a - ah;
    if (ab < 0)
      break;
    int bh = n / 2 - ab;
    if (bh < 0)
      continue;
    int bb = b - bh;
    if (bb < 0)
      continue;
    int k = ab + bb;
    if (k < 0)
      continue;
    possible_k[k] = true;
  }
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int a, b;
    readf!" %d %d "(a, b);
    bool[int] possible_k;
    solve(a, b, possible_k);
    solve(b, a, possible_k);
    writeln(possible_k.length);
    writeln(possible_k.byKey.array.sort.map!text.joiner(" "));
  }
}

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)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//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 modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto a = RD!int;
		auto b = RD!int;
		if (a < b)
			swap(a, b);

		auto n = a + b;
		bool[int] set;
		{
			auto m = (n+1) / 2;
			auto x = a - m;
			set[x] = true;
			foreach (i; 0..max(b-x, min(a, b)))
			{
				x += 2;
				set[x] = true;
			}
		}
		{
			auto m = n / 2;
			auto x = a - m;
			set[x] = true;
			foreach (i; 0..max(b-x, min(a, b)))
			{
				x += 2;
				set[x] = true;
			}
		}
		foreach (key; set.keys.sort)
			ans[ti] ~= key;
	}

	foreach (e; ans)
	{
		writeln(e.length);
		e.map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}


An array $$$a_1, a_2, \ldots, a_n$$$ is good if and only if for every subsegment $$$1 \leq l \leq r \leq n$$$, the following holds: $$$a_l + a_{l + 1} + \ldots + a_r = \frac{1}{2}(a_l + a_r) \cdot (r - l + 1)$$$. You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$. In one operation, you can replace any one element of this array with any real number. Find the minimum number of operations you need to make this array good.

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. Each of the next $$$t$$$ lines contains the description of a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 70$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$): the initial array.

For each test case, print one integer: the minimum number of elements that you need to replace to make the given array good.

NoteIn the first test case, the array is good already.In the second test case, one of the possible good arrays is $$$[1, 1, \underline{1}, \underline{1}]$$$ (replaced elements are underlined).In the third test case, the array is good already.In the fourth test case, one of the possible good arrays is $$$[\underline{-2.5}, -2, \underline{-1.5}, -1, \underline{-0.5}, 0]$$$.

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        readln;

        immutable vec =
            readln.chomp
            .split(' ')
            .to!(int[]);

        immutable longestProgressionLength = (){
            ubyte ret = 1;
            foreach (start; 0 .. vec.length)
                foreach (step; 1 .. vec.length - start) {
                    immutable strive = vec[start + step] - vec[start];
                    immutable nowLength = iota(start, vec.length, 1)
                        .count!((ind) => (vec[ind] - vec[start]) * step == strive * (ind - start));
                    ret = cast(ubyte)max(ret, nowLength);
                }
            return ret;
        }();

        (
            vec.length
            - longestProgressionLength
        ).writeln;
    }
}
// ""

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        readln;

        immutable vec =
            readln.chomp
            .split(' ')
            .to!(int[]);

        immutable longestProgressionLength = (){
            ubyte ret = 1;
            foreach (start; 0 .. vec.length)
                foreach (step; 1 .. vec.length - start) {
                    immutable strive = vec[start + step] - vec[start];
                    immutable nowLength = iota(0, vec.length, 1)
                        .count!((ind) => (vec[ind] - vec[start]) * step == strive * (ind - start));
                    ret = cast(ubyte)max(ret, nowLength);
                }
            return ret;
        }();

        (
            vec.length
            - longestProgressionLength
        ).writeln;
    }
}
// ""

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

void solve() {
    int N; readf("%d\n", &N);
    auto A = readln.chomp.split(" ").map!(to!double).array;

    auto f(int j, int k) {
        int c = 0;
        auto d = (A[k] - A[j]) / (k - j);
        auto b0 = A[j] - d * j;
        for (int i = 0; i < N; i++) {
            auto b = b0 + i * d;
            if (! isClose(A[i], b, 1e-9)) c++;
        }
        return c;
    }

    int ans = int.max;
    if (N <= 2) {
        ans = 0;
    }
    for (int j = 0; j < N; j++) {
        for (int k = j + 1; k < N; k++) {
            ans = min(ans, f(j, k));
        }
    }
    writeln(ans);
}

void main() {
    int T; readf("%d\n", &T);
    foreach (t; 0 .. T) solve();
}

void main() { runSolver(); }

void problem() {
  auto QN = scan!long;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!real(N);

      int ans = N - 1;
      foreach(i; 0..N - 1) foreach(j; i+1..N) {
        real d = A[j] - A[i] == 0 ? 0 : (A[j] - A[i]) / (j - i);
        real t = A[i] - d*i;
        int tans = N;
        foreach(x; 0..N) {
          if (t.approxEqual(A[x], 1e-04, 1e-04)) tans--;
          t += d;
        }
        ans = min(ans, tans);
      }

      return ans;
    }

    foreach(_; 0..QN) subSolve().writeln;
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
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)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

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)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		int res = n - (n == 1);
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				auto num = a[j] - a[i];
				auto den = j - i;
				int cur = 0;
				foreach (k; 0..n)
				{
					auto value = num * (k - i);
					cur += (a[k] - a[i]) * den != value;
				}
				res = min (res, cur);
			}
		}
		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.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 numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        auto A = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt;
        }

        int ans = 1;
        foreach (i; 0 .. N) foreach (j; i + 1 .. N) {
          int cnt;
          foreach (k; 0 .. N) {
            if ((j - i) * (A[k] - A[i]) == (k - i) * (A[j] - A[i])) {
              ++cnt;
            }
          }
          chmax(ans, cnt);
        }

        writeln(N - ans);
      }
    }
  } catch (EOFException e) {
  }
}

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        readln;

        immutable vec =
            readln.chomp
            .split(' ')
            .to!(int[]);

        immutable longestProgressionLength = (){
            ubyte ret = 1;
            foreach (start; 0 .. vec.length)
                foreach (step; 1 .. vec.length - start) {
                    immutable strive = vec[start + step] - vec[start];
                    immutable nowLength = iota(start, vec.length, step)
                        .count!((ind) => (vec[ind] - vec[start]) * step == strive * (ind - start));
                    ret = cast(ubyte)max(ret, nowLength);
                }
            return ret;
        }();

        (
            vec.length
            - longestProgressionLength
        ).writeln;
    }
}
// ""

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        readln;

        immutable vec =
            readln.chomp
            .split(' ')
            .to!(byte[]);

        immutable longestProgressionLength = (){
            ubyte ret = 1;
            foreach (start; 0 .. vec.length)
                foreach (step; 1 .. vec.length - start) {
                    immutable strive = vec[start + step] - vec[start];
                    immutable nowLength = iota(start, vec.length, step)
                        .count!((ind) => (vec[ind] - vec[start]) * step == strive * (ind - start));
                    ret = cast(ubyte)max(ret, nowLength);
                }
            return ret;
        }();

        (
            vec.length
            - longestProgressionLength
        ).writeln;
    }
}
// ""


Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string. Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.

The first line contains integer n (1 ≤ n ≤ 106). The second line contains string s — Yaroslav's word. The third line contains string t — Andrey's word. It is guaranteed that both words consist of 2·n characters "0" and "1".

Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.

import std.stdio;
import std.exception;
import std.algorithm;
import std.math;
import std.typecons;

void main(){
    int n;
    string a, b;
    readf("%d\n%s\n%s\n", &n, &a, &b);
    int x1=0, q=0, y1=0;
    foreach(i; 0..2*n){
        if (a[i]=='1' && b[i]=='1') q++;
        else if (a[i]=='1') x1++;
        else if (b[i]=='1') y1++;
    }
    int ans1=q/2+q%2, ans2=q/2;
    if (ans1!=ans2){
        if (x1>y1){
            ans2+=y1;
            ans1+=y1;
            x1-=y1;
            ans1+=x1/2;
        }
        else{
            ans1+=x1;
            ans2+=x1;
            y1-=x1;
            ans2+=y1/2+y1%2;
        }
    }
    else{
        if (x1>y1){
            ans2+=y1;
            ans1+=y1;
            x1-=y1;
            ans1+=x1/2+x1%2;
        }
        else{
            ans1+=x1;
            ans2+=x1;
            y1-=x1;
            ans2+=y1/2;
        }
    }
    if (ans1>ans2) writefln("First");
    else if (ans1<ans2) writefln("Second");
    else writefln("Draw");
}

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto s = readln ().strip ();
		auto t = readln ().strip ();
		auto a = new int [4];
		foreach (i; 0..2 * n)
		{
			a[(s[i] == '1') + ((t[i] == '1') << 1)]++;
		}
		debug {writeln (a);}

		auto b = new int [2];
		foreach (i; 0..2 * n)
		{
			int p = i & 1;
			int bj = -1, bv = -3;
			foreach (j; 0..4)
			{
				if (a[j] == 0)
				{
					continue;
				}

				int v = ((j >> p) & 1) + ((j >> !p) & 1);
				if (bv < v)
				{
					bv = v;
					bj = j;
				}
			}
			assert (bj != -1);
			a[bj]--;
			b[p] += (bj >> p) & 1;
		}

		debug {writeln (b);}
		writeln (b[0] < b[1] ? "Second" :
		         (b[0] == b[1] ? "Draw" : "First"));
	}
}


At a break Vanya came to the class and saw an array of $$$n$$$ $$$k$$$-bit integers $$$a_1, a_2, \ldots, a_n$$$ on the board. An integer $$$x$$$ is called a $$$k$$$-bit integer if $$$0 \leq x \leq 2^k - 1$$$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the number $$$a_i$$$ with the number $$$\overline{a_i}$$$. We define $$$\overline{x}$$$ for a $$$k$$$-bit integer $$$x$$$ as the $$$k$$$-bit integer such that all its $$$k$$$ bits differ from the corresponding bits of $$$x$$$. Vanya does not like the number $$$0$$$. Therefore, he likes such segments $$$[l, r]$$$ ($$$1 \leq l \leq r \leq n$$$) such that $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$1 \leq k \leq 30$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 2^k - 1$$$), separated by spaces — the array of $$$k$$$-bit integers.

Print one integer — the maximum possible number of segments with XOR not equal to $$$0$$$ that can be obtained by making several (possibly $$$0$$$) operations described in the statement.

NoteIn the first example if Vasya does not perform any operations, he gets an array that has $$$5$$$ segments that Vanya likes. If he performs the operation with $$$i = 2$$$, he gets an array $$$[1, 0, 0]$$$, because $$$\overline{3} = 0$$$ when $$$k = 2$$$. This array has $$$3$$$ segments that Vanya likes. Also, to get an array with $$$5$$$ segments that Vanya likes, he can perform two operations with $$$i = 3$$$ and with $$$i = 2$$$. He then gets an array $$$[1, 0, 3]$$$. It can be proven that he can't obtain $$$6$$$ or more segments that he likes.In the second example, to get $$$19$$$ segments that Vanya likes, he can perform $$$4$$$ operations with $$$i = 3$$$, $$$i = 4$$$, $$$i = 5$$$, $$$i = 6$$$ and get an array $$$[1, 4, 3, 0, 4, 3]$$$.

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;

immutable int INF = 1 << 29;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto X = (1L << K) - 1;
    auto A = readln.split.map!(to!long).array;

    long ans = 0;
    long tmp = 0;
    long[long] cnt;
    cnt[0] = 1;

    long f(long x) {
        if (x !in cnt) return 0;
        else return cnt[x];
    }

    foreach (i; 0..N) {
        long a = tmp ^ A[i];
        long b = a ^ X;
        if (f(a) <= f(b)) {
            ans += f(a);
            cnt[a] += 1;
            tmp = a;
        } else {
            ans += f(b);
            cnt[b] += 1;
            tmp = b;
        }
    }

    ans = N.to!long * (N.to!long + 1) / 2 - ans;
    ans.writeln;
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto m = (1 << k) - 1;
		foreach (i; 1..n)
		{
			a[i] ^= a[i - 1];
		}

		int [int] v;
		v[0] = 1;
		long res = 0;
		foreach (ref c0; a)
		{
			auto c1 = c0 ^ m;
			auto one = v.get (c0, 0);
			auto two = v.get (c1, 0);
			if (one < two)
			{
				res += one;
				v[c0] += 1;
			}
			else
			{
				res += two;
				v[c1] += 1;
			}
		}
		debug {writeln (v);}
		writeln (n * (n + 1L) / 2 - res);
	}
}

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

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

		int [int] v;
		long res = 0;
		foreach (ref c0; a)
		{
			auto c1 = c0 ^ m;
			auto one = v.get (c0, 0) + (c0 == 0);
			auto two = v.get (c1, 0) + (c1 == 0);
			if (one < two)
			{
				res += one;
				v[c0] += 1;
			}
			else
			{
				res += two;
				v[c1] += 1;
			}
		}
		writeln (n * (n + 1L) / 2 - res);
	}
}


Let's denote the function $$$f(s)$$$ that takes a string $$$s$$$ consisting of lowercase Latin letters and dots, and returns a string consisting of lowercase Latin letters as follows:  let $$$r$$$ be an empty string;  process the characters of $$$s$$$ from left to right. For each character $$$c$$$, do the following: if $$$c$$$ is a lowercase Latin letter, append $$$c$$$ at the end of the string $$$r$$$; otherwise, delete the last character from $$$r$$$ (if $$$r$$$ is empty before deleting the last character — the function crashes);  return $$$r$$$ as the result of the function. You are given two strings $$$s$$$ and $$$t$$$. You have to delete the minimum possible number of characters from $$$s$$$ so that $$$f(s) = t$$$ (and the function does not crash). Note that you aren't allowed to insert new characters into $$$s$$$ or reorder the existing ones.

The input consists of two lines: the first one contains $$$s$$$ — a string consisting of lowercase Latin letters and dots, the second one contains $$$t$$$ — a string consisting of lowercase Latin letters ($$$1 \le |t| \le |s| \le 10000$$$). Additional constraint on the input: it is possible to remove some number of characters from $$$s$$$ so that $$$f(s) = t$$$.

Print one integer — the minimum possible number of characters you have to delete from $$$s$$$ so $$$f(s)$$$ does not crash and returns $$$t$$$ as the result of the function.

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

immutable int infinity = int.max / 2;
immutable int NA = -1;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto t = readln.strip;
		auto k = s.length.to !(int);
		auto n = t.length.to !(int);

		auto p = new int [k];
		p[] = NA;
		int [] stack;
		foreach (j; 0..k)
		{
			if (s[j] == '.')
			{
				if (!stack.empty)
				{
					p[j] = stack.back;
					stack.popBack ();
					stack.assumeSafeAppend ();
				}
			}
			else
			{
				stack ~= j;
			}
		}

		auto f = new int [] [] (2, k + 1);
		int b = 0;
		f[b][0] = 0;
		foreach (j; 1..k + 1)
		{
			f[b][j] = f[b][j - 1] + 1;
			if (p[j - 1] != NA)
			{
				f[b][j] = min (f[b][j], f[b][p[j - 1]]);
			}
		}
		foreach (i; 0..n)
		{
			b ^= 1;
			f[b][] = infinity;
			foreach (j; i + 1..k + 1)
			{
				f[b][j] = f[b][j - 1] + 1;
				if (t[i] == s[j - 1])
				{
					f[b][j] = min (f[b][j], f[!b][j - 1]);
				}
				if (p[j - 1] != NA)
				{
					f[b][j] = min (f[b][j], f[b][p[j - 1]]);
				}
			}
		}
		writeln (f[b][k]);
	}
}

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

immutable int infinity = int.max / 2;
immutable int NA = -1;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto t = readln.strip;
		auto k = s.length.to !(int);
		auto n = t.length.to !(int);

		auto p = new int [k];
		p[] = NA;
		int [] stack;
		foreach (j; 0..k)
		{
			if (s[j] == '.')
			{
				if (!stack.empty)
				{
					p[j] = stack.back;
					stack.popBack ();
					stack.assumeSafeAppend ();
				}
			}
			else
			{
				stack ~= j;
			}
		}

		auto f = new int [] [] (2, k + 1);
		int b = 0;
		f[b] = iota (k + 1).array;
		foreach (i; 0..n)
		{
			b ^= 1;
			f[b][] = infinity;
			foreach (j; i + 1..k + 1)
			{
				f[b][j] = f[b][j - 1] + 1;
				if (t[i] == s[j - 1])
				{
					f[b][j] = min (f[b][j], f[!b][j - 1]);
				}
				if (p[j - 1] != NA)
				{
					f[b][j] = min (f[b][j], f[b][p[j - 1]]);
				}
			}
		}
		writeln (f[b][k]);
	}
}

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

immutable int infinity = int.max / 2;
immutable int NA = -1;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto t = readln.strip;
		auto k = s.length.to !(int);
		auto n = t.length.to !(int);

		auto p = new int [k];
		int [] stack;
		foreach (j; 0..k)
		{
			if (s[j] == '.')
			{
				if (!stack.empty)
				{
					p[j] = stack.back;
					stack.popBack ();
					stack.assumeSafeAppend ();
				}
			}
			else
			{
				stack ~= j;
			}
		}

		auto f = new int [] [] (2, k + 1);
		int b = 0;
		f[b] = iota (k + 1).array;
		foreach (i; 0..n)
		{
			b ^= 1;
			f[b][] = infinity;
			foreach (j; i + 1..k + 1)
			{
				f[b][j] = f[b][j - 1] + 1;
				if (t[i] == s[j - 1])
				{
					f[b][j] = min (f[b][j], f[!b][j - 1]);
				}
				if (p[j - 1] != NA)
				{
					f[b][j] = min (f[b][j], f[b][p[j - 1]]);
				}
			}
		}
		writeln (f[b][k]);
	}
}


You are given a permutation $$$p=[p_1, p_2, \ldots, p_n]$$$ of integers from $$$1$$$ to $$$n$$$. Let's call the number $$$m$$$ ($$$1 \le m \le n$$$) beautiful, if there exists two indices $$$l, r$$$ ($$$1 \le l \le r \le n$$$), such that the numbers $$$[p_l, p_{l+1}, \ldots, p_r]$$$ is a permutation of numbers $$$1, 2, \ldots, m$$$.For example, let $$$p = [4, 5, 1, 3, 2, 6]$$$. In this case, the numbers $$$1, 3, 5, 6$$$ are beautiful and $$$2, 4$$$ are not. It is because:  if $$$l = 3$$$ and $$$r = 3$$$ we will have a permutation $$$[1]$$$ for $$$m = 1$$$;  if $$$l = 3$$$ and $$$r = 5$$$ we will have a permutation $$$[1, 3, 2]$$$ for $$$m = 3$$$;  if $$$l = 1$$$ and $$$r = 5$$$ we will have a permutation $$$[4, 5, 1, 3, 2]$$$ for $$$m = 5$$$;  if $$$l = 1$$$ and $$$r = 6$$$ we will have a permutation $$$[4, 5, 1, 3, 2, 6]$$$ for $$$m = 6$$$;  it is impossible to take some $$$l$$$ and $$$r$$$, such that $$$[p_l, p_{l+1}, \ldots, p_r]$$$ is a permutation of numbers $$$1, 2, \ldots, m$$$ for $$$m = 2$$$ and for $$$m = 4$$$. You are given a permutation $$$p=[p_1, p_2, \ldots, p_n]$$$. For all $$$m$$$ ($$$1 \le m \le n$$$) determine if it is a beautiful number or not.

The first line contains the only integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the given permutation $$$p$$$. The next line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are different) — the given permutation $$$p$$$. It is guaranteed, that the sum of $$$n$$$ from all test cases in the input doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines — the answers to test cases in the order they are given in the input.  The answer to a test case is the string of length $$$n$$$, there the $$$i$$$-th character is equal to $$$1$$$ if $$$i$$$ is a beautiful number and is equal to $$$0$$$ if $$$i$$$ is not a beautiful number.

NoteThe first test case is described in the problem statement.In the second test case all numbers from $$$1$$$ to $$$5$$$ are beautiful:  if $$$l = 3$$$ and $$$r = 3$$$ we will have a permutation $$$[1]$$$ for $$$m = 1$$$;  if $$$l = 3$$$ and $$$r = 4$$$ we will have a permutation $$$[1, 2]$$$ for $$$m = 2$$$;  if $$$l = 2$$$ and $$$r = 4$$$ we will have a permutation $$$[3, 1, 2]$$$ for $$$m = 3$$$;  if $$$l = 2$$$ and $$$r = 5$$$ we will have a permutation $$$[3, 1, 2, 4]$$$ for $$$m = 4$$$;  if $$$l = 1$$$ and $$$r = 5$$$ we will have a permutation $$$[5, 3, 1, 2, 4]$$$ for $$$m = 5$$$.

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 t = RD!int;
	auto ans = new int[][](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto p = RDA(-1);
		auto pos = new int[](n);
		foreach (j; 0..n)
		{
			pos[p[j]] = j;
		}

		ans[i].length = n;
		int l = int.max, r;
		foreach (j; 0..n)
		{
			l.chmin(pos[j]);
			r.chmax(pos[j]);
			//debug writeln("l:", l, " r:", r);
			if (r-l == j)
			{
				ans[i][j] = 1;
			}
		}
	}

	foreach (e; ans)
	{
		e.map!(to!string).join("").writeln;
	}
	stdout.flush;
	debug readln;
}


Polycarp's workday lasts exactly $$$n$$$ minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has $$$k$$$ bars at the beginning of the workday.In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that $$$k$$$ is strictly greater than $$$1$$$.Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.Consider that Polycarp eats a bar in the minute $$$x$$$ and the next bar in the minute $$$y$$$ ($$$x < y$$$). Then the break time is equal to $$$y - x - 1$$$ minutes. It is not necessary for Polycarp to eat all bars he has.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 200\,000$$$, $$$2 \le k \le n$$$) — the length of the workday in minutes and the number of chocolate bars, which Polycarp has in the beginning of the workday. The second line contains the string with length $$$n$$$ consisting of zeros and ones. If the $$$i$$$-th symbol in the string equals to zero, Polycarp has no important things to do in the minute $$$i$$$ and he can eat a chocolate bar. In the other case, Polycarp is busy in the minute $$$i$$$ and can not eat a chocolate bar. It is guaranteed, that the first and the last characters of the string are equal to zero, and Polycarp always eats chocolate bars in these minutes.

Print the minimum possible break in minutes between eating chocolate bars.

NoteIn the first example Polycarp can not eat the chocolate bar in the second minute, so the time of the break equals to one minute.In the second example Polycarp will eat bars in the minutes $$$1$$$ and $$$8$$$ anyway, also he needs to eat the chocolate bar in the minute $$$5$$$, so that the time of the maximum break will be equal to $$$3$$$ minutes.

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

void main ()
{
	int n;
	int k;
	readf (" %s %s", &n, &k);
	readln;
	auto a = readln.strip.map !(c => c == '0').array;

	int p = -1;
	auto b = new int [n];
	foreach (i; 0..n)
	{
		if (a[i])
		{
			p = i;
		}
		b[i] = p;
	}

	bool check (int step)
	{
		int pos = 0;
		foreach (i; 1..k)
		{
			int next = pos + step + 1;
			next = min (next, n - 1);
			next = b[next];
			pos = next;
		}
		return pos == n - 1;
	}

	int lo = 0;
	int hi = n;
	while (lo < hi)
	{
		int me = (lo + hi) >> 1;
		if (check (me))
		{
			hi = me;
		}
		else
		{
			lo = me + 1;
		}
	}
	writeln (lo);
}

module main;
import std.c.stdio;

char [] arr;
int n, k;

bool Go(int m) {
    if (m == 0)
        return false;
    int have = k - 2;
    int prv = 0;
    int nxt = 0;
    for (int i = 1; i < n - 1; ++i) {
        if (arr[i] == '0')
        nxt = i;
        if (i == prv + m) {
            if (nxt > prv) {
                prv = nxt;
                have--;
                if (have < 0)
                    return false;
            }
            else
                return false;
        }
    }
    return true;
}

int main(string[] argv)
{
	scanf("%d %d\n", &n, &k);
	arr = new char[n + 10];
	for(int i = 0; i < n; i++)
		scanf("%c", &arr[i]);
	int L = 0, R = n + 1;
	while (R - L > 1) {
	    int M = (L + R) / 2;
	    if (Go(M))
	        R = M;
	    else
	        L = M;
	}
	printf("%i", R - 1);
	return 0;
}


This problem is same as the previous one, but has larger constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the $$$n$$$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $$$i$$$-th day has a ribbon with color $$$u_i$$$. Shiro wants to know the largest number $$$x$$$, such that if we consider the streak of the first $$$x$$$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $$$x - 1$$$ will have the same number of occurrences.For example, consider the following sequence of $$$u_i$$$: $$$[2, 2, 1, 1, 5, 4, 4, 5]$$$. Then $$$x = 7$$$ makes a streak, since if we remove the leftmost $$$u_i = 5$$$, each ribbon color will appear exactly twice in the prefix of $$$x - 1$$$ days. Note that $$$x = 8$$$ doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the total number of days. The second line contains $$$n$$$ integers $$$u_1, u_2, \ldots, u_n$$$ ($$$1 \leq u_i \leq 10^5$$$) — the colors of the ribbons the cats wear.

Print a single integer $$$x$$$ — the largest possible streak of days.

NoteIn the first example, we can choose the longest streak of $$$13$$$ days, since upon removing the last day out of the streak, all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$ will have the same number of occurrences of $$$3$$$. Note that the streak can also be $$$10$$$ days (by removing the $$$10$$$-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first $$$6$$$ days, we can remove the third day from this streak then all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ will occur exactly once.

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, core.stdc.string;

void main(){
    auto N = readln.chomp.to!(int);
    auto A = readln.split.map!(x => x.to!(int)-1).array;
    const int M = 10^^5;

    auto cnt = new int[](M);
    auto cnt2 = new int[](M+10);
    cnt2[0] = M;
    int ans = 0;
    int day = 0;
    auto rbt = new RedBlackTree!int();

    foreach (a; A) {
        day += 1;
        cnt2[cnt[a]] -= 1;
        cnt[a] += 1;
        cnt2[cnt[a]] += 1;
        if (cnt2[cnt[a]-1] == 0 && cnt[a] != 1) rbt.removeKey(cnt[a]-1);
        if (cnt2[cnt[a]] == 1) rbt.insert(cnt[a]);
        if (rbt.length == 1 && rbt.front == day) {
            ans = day;
        } else if (rbt.length == 1 && rbt.front == 1) {
            ans = day;
        } else if (rbt.length == 2) {
            if (cnt2[rbt.front] == 1 && rbt.front == 1) {
                ans = day;
            } else if (cnt2[rbt.back] == 1 && rbt.back == 1) {
                ans = day;
            } else if (rbt.back - rbt.front == 1 && cnt2[rbt.back] == 1) {
                ans = day;
            }
        }
    }

    ans.writeln;
}

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int n = read.to!int;
	int[] us;

	foreach(i; 0 .. n) us ~= read.to!int - 1;

	int bestx = 1;
	int minc, maxc;
	int[] ucnt = new int[](100_009);
	int[] ccnt = new int[](100_009);
	int allccnt;
	foreach(i; 0 .. n){
		int u = us[i];
		int c = ucnt[u];
		if(c > 0) ccnt[c] -= 1;
		if(c == minc && ccnt[c] == 0) minc += 1;
		ucnt[u] += 1;
		c = ucnt[u];
		ccnt[c] += 1;
		if(c == 1) minc = 1, allccnt += 1;
		if(c > maxc) maxc = c;

		if(minc == 1 && ccnt[minc] == 1 && ccnt[minc] + ccnt[maxc] == allccnt) bestx = i + 1;
		if(minc == maxc - 1 && ccnt[maxc] == 1) bestx = i + 1;
		if(minc == maxc && ccnt[minc] == 1) bestx = i + 1;
		if(minc == maxc && minc == 1 && ccnt[minc] > 1) bestx = i + 1;

	}

	bestx.writeln;

}

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, core.stdc.string;

void main(){
    auto N = readln.chomp.to!(int);
    auto A = readln.split.map!(x => x.to!(int)-1).array;
    const int M = 10^^5;

    auto cnt = new int[](M);
    auto cnt2 = new int[](M+10);
    cnt2[0] = M;
    int ans = 0;
    int day = 0;
    auto rbt = new RedBlackTree!int();

    foreach (a; A) {
        day += 1;
        cnt2[cnt[a]] -= 1;
        cnt[a] += 1;
        cnt2[cnt[a]] += 1;
        if (cnt2[cnt[a]-1] == 0 && cnt[a] != 1) rbt.removeKey(cnt[a]-1);
        if (cnt2[cnt[a]] == 1) rbt.insert(cnt[a]);
        if (rbt.length == 1 && rbt.front == 1) {
            ans = day;
        } else if (rbt.length == 2) {
            if (cnt2[rbt.front] == 1 && rbt.front == 1) {
                ans = day;
            } else if (cnt2[rbt.back] == 1 && rbt.back == 1) {
                ans = day;
            } else if (rbt.back - rbt.front == 1 && cnt2[rbt.back] == 1) {
                ans = day;
            }
        }
    }

    ans.writeln;
}

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int n = read.to!int;
	int[] us;

	foreach(i; 0 .. n) us ~= read.to!int - 1;

	int bestx = 1;
	int minc, maxc;
	int[] ucnt = new int[](100_009);
	int[] ccnt = new int[](100_009);
	foreach(i; 0 .. n){
		int u = us[i];
		int c = ucnt[u];
		if(c > 0) ccnt[c] -= 1;
		if(c == minc && ccnt[c] == 0) minc += 1;
		ucnt[u] += 1;
		c = ucnt[u];
		ccnt[c] += 1;
		if(c > maxc) maxc = c;

		if(minc == 1 && ccnt[minc] == 1) bestx = i + 1;
		if(minc == maxc - 1 && ccnt[maxc] == 1) bestx = i + 1;
		if(minc == maxc && ccnt[minc] == 1) bestx = i + 1;
		if(minc == maxc && minc == 1 && ccnt[minc] > 1) bestx = i + 1;

	}

	bestx.writeln;

}

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int n = read.to!int;
	int[] us;

	foreach(i; 0 .. n) us ~= read.to!int - 1;

	int bestx = 1;
	int minc, maxc;
	int[] ucnt = new int[](100_009);
	int[] ccnt = new int[](100_009);
	foreach(i; 0 .. n){
		int u = us[i];
		int c = ucnt[u];
		if(c > 0) ccnt[c] -= 1;
		if(c == minc && ccnt[c] == 0) minc += 1;
		ucnt[u] += 1;
		c = ucnt[u];
		ccnt[c] += 1;
		if(c == 1) minc = 1;
		if(c > maxc) maxc = c;

		if(minc == 1 && ccnt[minc] == 1) bestx = i + 1;
		if(minc == maxc - 1 && ccnt[maxc] == 1) bestx = i + 1;
		if(minc == maxc && ccnt[minc] == 1) bestx = i + 1;
		if(minc == maxc && minc == 1 && ccnt[minc] > 1) bestx = i + 1;

	}

	bestx.writeln;

}


You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest".A palindrome is a string that reads the same forward or backward.The length of string B should be at most 104. It is guaranteed that there always exists such string.You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104.

First line contains a string A (1 ≤ |A| ≤ 103) consisting of lowercase Latin letters, where |A| is a length of A.

Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. If there are many possible B, print any of them.

NoteIn the first example, "aba" is a subsequence of "aba" which is a palindrome.In the second example, "ab" is a subsequence of "aabaa" which is a palindrome.

import std.range;
import std.stdio;
import std.string;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		writeln (s, s.retro);
	}
}

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 A = readToken();
      writeln(A ~ A.dup.reverse);
    }
  } catch (EOFException e) {
  }
}

import std.stdio;
import std.algorithm.mutation;

void main() {
	string a; // = readln();
	readf!"%s\n"(a);

	write(a);

	for (int i=a.length-1; i>=0; i--)
		write(a[i]);
}

import std.stdio;
import std.algorithm.mutation;

void main() {
	string a; // = readln();
	readf!"%s"(a);

	write(a);

	for (int i=a.length-1; i>=0; i--)
		write(a[i]);
}

import std.stdio;
import std.algorithm.mutation;

void main() {
	string a = readln();

	write(a);

	for (int i=a.length-1; i>=0; i--)
		write(a[i]);
}