You have an array of integers $$$a$$$ of size $$$n$$$. Initially, all elements of the array are equal to $$$1$$$. You can perform the following operation: choose two integers $$$i$$$ ($$$1 \le i \le n$$$) and $$$x$$$ ($$$x > 0$$$), and then increase the value of $$$a_i$$$ by $$$\left\lfloor\frac{a_i}{x}\right\rfloor$$$ (i.e. make $$$a_i = a_i + \left\lfloor\frac{a_i}{x}\right\rfloor$$$).After performing all operations, you will receive $$$c_i$$$ coins for all such $$$i$$$ that $$$a_i = b_i$$$.Your task is to determine the maximum number of coins that you can receive by performing no more than $$$k$$$ operations.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3; 0 \le k \le 10^6$$$) — the size of the array and the maximum number of operations, respectively. The second line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^3$$$). The third line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 10^6$$$). The sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.

For each test case, print one integer — the maximum number of coins that you can get by performing no more than $$$k$$$ operations.

// cheese-cracker [2022-01-31]

long[][] dp;
int[] ks;
int[] dp2;
long[] cs;

long go(int ix, int cap){
    if(ix < 0){ return 0; }

    if(dp[ix][cap] != -1){
        return dp[ix][cap];
    }

    long res = go(ix-1, cap);
    if(cap >= ks[ix]){
        long take = go(ix - 1, cap - ks[ix]) + cs[ix];
        res = max(res, take);
    }
    dp[ix][cap] = res;
    return res;
}

void preprocess(){
    dp2[1] = 0;
    for(int k = 1; k <= 1000; ++k){
        for(int x = 1; x < 1002; ++x){
            if(k + k/x < 1002){
                dp2[k + k/x] = min(dp2[k] + 1, dp2[k + k/x]);
            }
        }
    }
}

void solve(){
    cs = [];
    ks = [];
    auto n = scan!int;
    long k = scan;
    auto bs = scanArray;
    cs = scanArray;
    int mcap = min(22005, k.to!int);
    dp = new long[][](n, mcap+1);

    for(int i = 0; i < n; ++i){
        int cnt = dp2[bs[i].to!int];
        /* show(cnt); */
        ks ~= cnt;
    }
    show(ks);
    for(int i = 0; i < n; ++i){ dp[i][] = -1; }

    writeln(go(n-1, mcap));
}

void main(){
    long tests = scan;        // Toggle!
    dp2 = new int[](1005);
    dp2[] = 1005;
    preprocess;
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

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

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

enum int INF = 1<<28;

void solve() {
    enum int L = 1000;
    int N, K; readf("%d %d\n", &N, &K);
    auto B = readarray!int;
    auto C = readarray!int;

    auto Z = new int[L + 1];
    Z[] = INF;
    Z[1] = 0;
    for (int m = 1; m <= L; m++) {
        for (int x = 1; x <= m; x++) {
            int n = m + m / x;
            if (n > L) continue;
            Z[n] = min(Z[n], Z[m] + 1);
        }
    }

    int M = 0; {
        foreach (z; Z) {
            if (z == INF) continue;
            M = max(M, z);
        }
    }

    int X = N * M;
    auto f = new int[][](N + 1, X + 1);
    f[0][0] = 0;
    for (int k = 0; k < N; k++) {
        for (int p = 0; p <= X; p++) {
            f[k + 1][p] = max(f[k + 1][p], f[k][p]);
            if (p + Z[B[k]] <= X) {
                f[k + 1][p + Z[B[k]]] = max(f[k + 1][p + Z[B[k]]], f[k][p] + C[k]);
            }
        }
    }
    int ans = f[N][min(K, X)];
    writeln(ans);

}

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

// cheese-cracker [2022-01-31]

long[][] dp;
int[] ks;
long[] cs;

long go(int ix, int cap){
    if(ix < 0){ return 0; }

    if(dp[ix][cap] != -1){
        return dp[ix][cap];
    }

    long res = go(ix-1, cap);
    if(cap >= ks[ix]){
        long take = go(ix - 1, cap - ks[ix]) + cs[ix];
        res = max(res, take);
    }
    dp[ix][cap] = res;
    return res;
}

void solve(){
    cs = [];
    ks = [];
    auto n = scan!int;
    long k = scan;
    auto bs = scanArray;
    cs = scanArray;
    int mcap = min(22005, k.to!int);
    dp = new long[][](n, mcap+1);

    for(int i = 0; i < n; ++i){
        int cnt = 0;
        long num = bs[i];
        while(num > 1){
            num >>= 1;
            ++cnt;
        }
        num = 1L << cnt;
        long till = num;
        while(num != bs[i]){
            long diff = bs[i] - num;
            long take = 1;
            for(long x = 1; 2*x <= till; ++x){
                if(num / x <= diff){
                    take = max(num / x, take);
                }
            }
            num += take;
            ++cnt;
        }
        ks ~= cnt;
    }
    show(ks);
    for(int i = 0; i < n; ++i){ dp[i][] = -1; }

    writeln(go(n-1, mcap));
    /* show(dp); */
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

// cheese-cracker [2022-01-31]

long[][] dp;
int[] ks;
long[] cs;

long go(int ix, int cap){
    if(ix < 0){ return 0; }

    if(dp[ix][cap] != -1){
        return dp[ix][cap];
    }

    long res = go(ix-1, cap);
    if(cap >= ks[ix]){
        long take = go(ix - 1, cap - ks[ix]) + cs[ix];
        res = max(res, take);
    }
    dp[ix][cap] = res;
    return res;
}

void solve(){
    auto n = scan!int;
    long k = scan;
    auto bs = scanArray;
    cs = [];
    cs = scanArray;

    ks = [];
    for(int i = 0; i < n; ++i){
        int cnt = 0;
        long num = bs[i];
        while(num > 1){
            num >>= 1;
            ++cnt;
        }
        long tim = -1;
        num = bs[i];
        while(num > 0){
            tim += (num & 1);
            num >>= 1;
        }
        cnt += tim;
        ks ~= cnt;
    }
    show(ks);
    int mcap = min(22005, k.to!int);
    dp = new long[][](n+1, mcap+1);
    for(int i = 0; i <= n; ++i){ dp[i][] = -1; }

    writeln(go(n-1, mcap));
    /* show(dp); */
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

// cheese-cracker [2022-01-31]

long[][] dp;
int[] ks;
long[] cs;

long go(int ix, int cap){
    if(ix < 0){ return 0; }

    if(dp[ix][cap] != -1){
        return dp[ix][cap];
    }

    long res = go(ix-1, cap);
    if(cap >= ks[ix]){
        long take = go(ix - 1, cap - ks[ix]) + cs[ix];
        res = max(res, take);
    }
    dp[ix][cap] = res;
    return res;
}

void solve(){
    auto n = scan!int;
    long k = scan;
    auto bs = scanArray;
    cs = [];
    cs = scanArray;

    ks = [];
    for(int i = 0; i < n; ++i){
        int cnt = 0;
        long num = bs[i];
        while(num > 1){
            num >>= 1;
            ++cnt;
        }
        long tim = -1;
        num = bs[i];
        while(num > 0){
            tim += (num & 1);
            num >>= 1;
        }
        cnt += max(tim, 0);
        ks ~= cnt;
    }
    show(ks);
    int mcap = min(10005, k.to!int);
    dp = new long[][](n+1, mcap+1);
    for(int i = 0; i <= n; ++i){ dp[i][] = -1; }

    writeln(go(n-1, mcap));
    /* show(dp); */
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

// cheese-cracker [2022-01-31]

long[][] dp;
int[] ks;
long[] cs;

long go(int ix, int cap){
    if(ix < 0){ return 0; }

    if(dp[ix][cap] != -1){
        return dp[ix][cap];
    }

    long res = go(ix-1, cap);
    if(cap >= ks[ix]){
        long take = go(ix - 1, cap - ks[ix]) + cs[ix];
        res = max(res, take);
    }
    dp[ix][cap] = res;
    return res;
}

void solve(){
    auto n = scan!int;
    long k = scan;
    auto bs = scanArray;
    cs = [];
    cs = scanArray;

    ks = [];
    for(int i = 0; i < n; ++i){
        int cnt = 0;
        long num = bs[i];
        while(num > 1){
            num >>= 1;
            ++cnt;
        }
        long tim = -1;
        num = bs[i];
        while(num > 0){
            tim += (num & 1);
            num >>= 1;
        }
        show(bs[i], " ", tim);
        cnt += max(tim, 0);
        ks ~= cnt;
    }
    show(ks);
    int mcap = min(2005, k.to!int);
    dp = new long[][](n+1, mcap+1);
    for(int i = 0; i <= n; ++i){ dp[i][] = -1; }

    writeln(go(n-1, mcap));
    /* show(dp); */
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }

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

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

enum int INF = 1<<28;

void solve() {
    enum int L = 1000;
    int N, K; readf("%d %d\n", &N, &K);
    auto B = readarray!int;
    auto C = readarray!int;

    auto Z = new int[L + 1];
    Z[] = INF;
    Z[1] = 0;
    for (int m = 1; m <= L; m++) {
        for (int x = 1; x <= m; x++) {
            int n = m + m / x;
            if (n > L) continue;
            Z[n] = min(Z[n], Z[m] + 1);
        }
    }

    int M = 0; {
        foreach (z; Z) {
            if (z == INF) continue;
            M = max(M, z);
        }
    }

    int X = N * M;
    auto f = new int[][](N + 1, X + 1);
    f[0][0] = 0;
    for (int k = 0; k < N; k++) {
        for (int p = 0; p < X; p++) {
            f[k + 1][p] = max(f[k + 1][p], f[k][p]);
            if (p + Z[B[k]] <= X) {
                f[k + 1][p + Z[B[k]]] = max(f[k + 1][p + Z[B[k]]], f[k][p] + C[k]);
            }
        }
    }
    int ans = f[N][min(K, X)];
    writeln(ans);

}

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

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

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

enum int INF = 1<<28;

void solve() {
    enum int L = 1000;
    int N, K; readf("%d %d\n", &N, &K);
    auto B = readarray!int;
    auto C = readarray!int;

    auto Z = new int[L + 1];
    Z[] = INF;
    Z[1] = 0;
    for (int m = 1; m <= L; m++) {
        for (int x = 1; x <= m; x++) {
            int n = m + m / x;
            if (n > L) continue;
            Z[n] = min(Z[n], Z[m] + 1);
        }
    }

    int M = 0; {
        foreach (z; Z) {
            if (z == INF) continue;
            M = max(M, z);
        }
    }

    int X = M * M;
    auto f = new int[][](N + 1, X + 1);
    f[0][0] = 0;
    for (int k = 0; k < N; k++) {
        for (int p = 0; p < X; p++) {
            f[k + 1][p] = max(f[k + 1][p], f[k][p]);
            if (p + Z[B[k]] <= X) {
                f[k + 1][p + Z[B[k]]] = max(f[k + 1][p + Z[B[k]]], f[k][p] + C[k]);
            }
        }
    }
    int ans = f[N][min(K, X)];
    writeln(ans);

}

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


The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.Each cell has one of the symbols 'L', 'R', 'D' or 'U' written on it, indicating the direction in which the robot will move when it gets in that cell — left, right, down or up, respectively.The robot can start its movement in any cell. He then moves to the adjacent square in the direction indicated on the current square in one move.   If the robot moves beyond the edge of the board, it falls and breaks.  If the robot appears in the cell it already visited before, it breaks (it stops and doesn't move anymore). Robot can choose any cell as the starting cell. Its goal is to make the maximum number of steps before it breaks or stops.Determine from which square the robot should start its movement in order to execute as many commands as possible. A command is considered successfully completed if the robot has moved from the square on which that command was written (it does not matter whether to another square or beyond the edge of the board).

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the test. Each test case's description is preceded by a blank line. Next is a line that contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2000$$$; $$$1 \le m \le 2000$$$) — the height and width of the board. This line followed by $$$n$$$ lines, the $$$i$$$-th of which describes the $$$i$$$-th line of the board. Each of them is exactly $$$m$$$ letters long and consists of symbols 'L', 'R', 'D' and 'U'. It is guaranteed that the sum of sizes of all boards in the input does not exceed $$$4\cdot10^6$$$.

For each test case, output three integers $$$r$$$, $$$c$$$ and $$$d$$$ ($$$1 \le r \le n$$$; $$$1 \le c \le m$$$; $$$d \ge 0$$$), which denote that the robot should start moving from cell $$$(r, c)$$$ to make the maximum number of moves $$$d$$$. If there are several answers, output any of them.

7

1 1
R

1 3
RRL

2 2
DL
RU

2 2
UD
RU

3 2
DL
UL
RU

4 4
RRRD
RUUD
URUD
ULLR

4 4
DDLU
RDDU
UUUU
RDLD

// Author: Ivan Kazmenko (gassa@mail.ru)
module solution;
import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int dirs = 4;
immutable int  [dirs] dRow  = [ -1,   0,  +1,   0];
immutable int  [dirs] dCol  = [  0,  -1,   0,  +1];
immutable char [dirs] dName = ['U', 'L', 'D', 'R'];

void main ()
{
	auto tests = readln.strip.to !(int);
multitest_loop:
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		auto board = new int [] [] (rows, cols);
		foreach (row; 0..rows)
		{
			auto s = readln.strip;
			foreach (col; 0..cols)
			{
				board[row][col] = dName[].countUntil (s[col]);
			}
		}

		auto f = new int [] [] (rows, cols);
		auto r = new int [rows * cols];
		auto c = new int [rows * cols];
		foreach (row0; 0..rows)
		{
			foreach (col0; 0..cols)
			{
				if (f[row0][col0] != 0)
				{
					continue;
				}
				int row = row0;
				int col = col0;
				int cur = 0;
				while (0 <= row && row < rows &&
				    0 <= col && col < cols && f[row][col] == 0)
				{
					r[cur] = row;
					c[cur] = col;
					cur += 1;
					f[row][col] = -cur;
					auto dir = board[row][col];
					row += dRow[dir];
					col += dCol[dir];
				}
				int hi = cur;
				if (0 <= row && row < rows &&
				    0 <= col && col < cols)
				{
					if (f[row][col] < 0)
					{
						int dest = -f[row][col];
						int len = cur - dest + 1;
						while (cur > dest)
						{
							cur -= 1;
							f[r[cur]][c[cur]] =
							    len;
						}
					}
					else
					{
						hi = f[row][col] + cur;
					}
				}
				while (cur > 0)
				{
					cur -= 1;
					f[r[cur]][c[cur]] = hi - cur;
				}
			}
		}

		debug {writefln !("\n%(%(%s %)\n%)") (f);}
		auto best = f.map !(maxElement).maxElement;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (f[row][col] == best)
				{
					writeln (row + 1, " ", col + 1,
					    " ", best);
					continue multitest_loop;
				}
			}
		}
		assert (false);
	}
}


There is an n × m rectangular grid, each cell of the grid contains a single integer: zero or one. Let's call the cell on the i-th row and the j-th column as (i, j).Let's define a "rectangle" as four integers a, b, c, d (1 ≤ a ≤ c ≤ n; 1 ≤ b ≤ d ≤ m). Rectangle denotes a set of cells of the grid {(x, y) :  a ≤ x ≤ c, b ≤ y ≤ d}. Let's define a "good rectangle" as a rectangle that includes only the cells with zeros.You should answer the following q queries: calculate the number of good rectangles all of which cells are in the given rectangle.

There are three integers in the first line: n, m and q (1 ≤ n, m ≤ 40, 1 ≤ q ≤ 3·105). Each of the next n lines contains m characters — the grid. Consider grid rows are numbered from top to bottom, and grid columns are numbered from left to right. Both columns and rows are numbered starting from 1.  Each of the next q lines contains a query — four integers that describe the current rectangle, a, b, c, d (1 ≤ a ≤ c ≤ n; 1 ≤ b ≤ d ≤ m).

For each query output an answer — a single integer in a separate line.

NoteFor the first example, there is a 5 × 5 rectangular grid, and the first, the second, and the third queries are represented in the following image.    For the first query, there are 10 good rectangles, five 1 × 1, two 2 × 1, two 1 × 2, and one 1 × 3.  For the second query, there is only one 1 × 1 good rectangle.  For the third query, there are 7 good rectangles, four 1 × 1, two 2 × 1, and one 3 × 1.

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 n, m, q;
	while (readf (" %s %s %s ", &n, &m, &q) > 0)
	{
		string [] e;
		foreach (i; 0..n)
		{
			e ~= readln ().strip ();
		}

		auto f = new bool [] [] [] [] (n, m, n, m);
		foreach (r1; 0..n)
		{
			foreach (c1; 0..m)
			{
				foreach (r2; r1..n)
				{
					foreach (c2; c1..m)
					{
						bool ok = true;
						foreach (r; r1..r2 + 1)
						{
							foreach (c; c1..c2 + 1)
							{
								if (e[r][c] == '1')
								{
									ok = false;
								}
							}
						}
						f[r1][c1][r2][c2] = ok;
					}
				}
			}
		}

		auto g = new int [] [] [] [] (n, m, n, m);
		foreach (h; 1..n + 1)
		{
			foreach (r1; 0..n)
			{
				int r2 = r1 + h - 1;
				if (r2 >= n)
				{
					break;
				}
				foreach (c1; 0..m)
				{
					foreach (c2; c1..m)
					{
						g[r1][c1][r2][c2] = 0;
						foreach (c3; c1..c2 + 1)
						{
							foreach (c4; c3..c2 + 1)
							{
								g[r1][c1][r2][c2] += f[r1][c3][r2][c4];
							}
						}
						if (r1 >= r2)
						{
							continue;
						}
						g[r1][c1][r2][c2] += g[r1][c1][r2 - 1][c2];
						g[r1][c1][r2][c2] += g[r1 + 1][c1][r2][c2];
						g[r1][c1][r2][c2] -= g[r1 + 1][c1][r2 - 1][c2];
					}
				}
			}
		}

		foreach (s; 0..q)
		{
			int a, b, c, d;
			readf (" %s %s %s %s", &a, &b, &c, &d);
			a--;
			b--;
			c--;
			d--;
			writeln (g[a][b][c][d]);
		}
	}
}


On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k.Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?

The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs.

On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs.

NoteIn the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items.In the second example, he can buy all items as they will cost him [5, 10, 17, 22].In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it.

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

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

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

    int f(int k, int S) {
        auto cost = arr.enumerate(1).map!(t => cast(long)t[0] * k + t[1]).array;
        auto nows = cost.sort().take(k).sum;
        return nows <= S ? nows.to!int : 0;
    }

    int lo = 0, hi = n;
    while (lo < hi) {
        auto m = (lo + hi) / 2 + 1;
        if (f(m, s) > 0) lo = m;
        else hi = m-1;
    }

    writeln(lo, ' ', f(lo, s));
}

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

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

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

    arr.sort();

    auto ans = 0, cost = 0;
    auto cur = 0L, cnt = 0L;
    foreach (i, e; arr) {
        cur += cnt;
        cur += e;
        cur += (i+1) * (i+1);
        cnt += (i+1);

        if (cur <= s) {
            ans = cast(int) i+1;
            cost = cur.to!int;
        } else break;
    }

    writeln(ans, ' ', cost);
}


There is a special offer in Vasya's favourite supermarket: if the customer buys $$$a$$$ chocolate bars, he or she may take $$$b$$$ additional bars for free. This special offer can be used any number of times.Vasya currently has $$$s$$$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $$$c$$$ roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. Each of the next $$$t$$$ lines contains four integers $$$s, a, b, c~(1 \le s, a, b, c \le 10^9)$$$ — the number of roubles Vasya has, the number of chocolate bars you have to buy to use the special offer, the number of bars you get for free, and the cost of one bar, respectively.

Print $$$t$$$ lines. $$$i$$$-th line should contain the maximum possible number of chocolate bars Vasya can get in $$$i$$$-th test.

NoteIn the first test of the example Vasya can buy $$$9$$$ bars, get $$$3$$$ for free, buy another bar, and so he will get $$$13$$$ bars.In the second test Vasya buys $$$1000000000$$$ bars and gets $$$1000000000000000000$$$ for free. So he has $$$1000000001000000000$$$ bars.

void main() {
  import std.stdio, std.string, std.conv, std.algorithm;

  int t;
  rd(t);
  while (t--) {
    long s, a, b, c;
    rd(s, a, b, c);
    auto n = s / c;
    writeln(n + n / a * b);
  }
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}


Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.Vladik knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport. To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b.Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i - j| if they belong to different companies.Print the minimum cost Vladik has to pay to get to the olympiad.

The first line contains three integers n, a, and b (1 ≤ n ≤ 105, 1 ≤ a, b ≤ n) — the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach.  The second line contains a string with length n, which consists only of characters 0 and 1. If the i-th character in this string is 0, then i-th airport belongs to first company, otherwise it belongs to the second.

Print single integer — the minimum cost Vladik has to pay to get to the olympiad.

NoteIn the first example Vladik can fly to the airport 2 at first and pay |1 - 2| = 1 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1. In the second example Vladik can fly directly from the airport 5 to the airport 2, because they belong to the same company.

import std.bigint,std.container,std.array,std.algorithm,std.conv,std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.typecons,std.regex,
std.random,std.uni,std.traits;
import core.stdc.stdio:freopen;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree set;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
immutable int mod=1000000007;
T lcm (T)(T a,T b)
{
	return a/gcd(a,b)*b;
}
pure nothrow X binpow(X,Y)(X base,Y exp)
	if(!isFloatingPoint!Y && !is(typeof(exp.im)))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
	if(!isFloatingPoint!Y && !is(typeof(exp.im)))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@property void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(X a,in int n,in int m)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
@property bool getarr(X)(X a,in int n){bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0) {return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
struct pair(X,Y)
{
	X first;
	Y second;
	alias first fi;
	alias second se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
		}
	this(this){fi=fi;se=se;}
	int opCmp(ref const pair!(X,Y) s_) const pure nothrow
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(in X x_,in Y y_) pure nothrow
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(in X a_) pure nothrow @property @nogc {return a_*a_;}
X cub(X)(in X a_) pure nothrow @property @nogc {return a_*a_*a_;}
nothrow @nogc @system void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow @nogc @system void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
auto arread(T)(){return readln.split.map!(to!(T)).array;}
nothrow @property pure size_t lowb(T,X)(in T a,in X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (!(a[l]<g))?l:r;
}
pure @property nothrow size_t upb(T,X)(in T a,in X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(g<a[m])r=m;
		else l=m;
	}
	return (g<a[l])?l:r;
}
pure @property nothrow size_t binf(T,X)(in T a,in X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (g==a[l])?l:a.length;
}
pure @property nothrow bool binary_search(T,X)(in T a,in X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	return binf(a,g)!=a.length;
}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n,a,b;

	while(input(&n,&a,&b))
	{
		readln;
		auto s=readln;
		writeln((s[a-1]-'0')^(s[b-1]-'0'));
	}
}


For the New Year, Polycarp decided to send postcards to all his $$$n$$$ friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size $$$w \times h$$$, which can be cut into pieces.Polycarp can cut any sheet of paper $$$w \times h$$$ that he has in only two cases:   If $$$w$$$ is even, then he can cut the sheet in half and get two sheets of size $$$\frac{w}{2} \times h$$$;  If $$$h$$$ is even, then he can cut the sheet in half and get two sheets of size $$$w \times \frac{h}{2}$$$; If $$$w$$$ and $$$h$$$ are even at the same time, then Polycarp can cut the sheet according to any of the rules above.After cutting a sheet of paper, the total number of sheets of paper is increased by $$$1$$$.Help Polycarp to find out if he can cut his sheet of size $$$w \times h$$$ at into $$$n$$$ or more pieces, using only the rules described above.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three integers $$$w$$$, $$$h$$$, $$$n$$$ ($$$1 \le w, h \le 10^4, 1 \le n \le 10^9$$$) — the width and height of the sheet Polycarp has and the number of friends he needs to send a postcard to.

For each test case, output on a separate line:    "YES", if it is possible to cut a sheet of size $$$w \times h$$$ into at least $$$n$$$ pieces;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

NoteIn the first test case, you can first cut the $$$2 \times 2$$$ sheet into two $$$2 \times 1$$$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $$$1 \times 1$$$. We can choose any three of them and send them to our friends.In the second test case, a $$$3 \times 3$$$ sheet cannot be cut, so it is impossible to get two sheets.In the third test case, you can cut a $$$5 \times 10$$$ sheet into two $$$5 \times 5$$$ sheets.In the fourth test case, there is no need to cut the sheet, since we only need one sheet.In the fifth test case, you can first cut the $$$1 \times 4$$$ sheet into two $$$1 \times 2$$$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $$$1 \times 1$$$.

// Vicfred
// https://codeforces.com/contest/1472/problem/A
// math
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.stdio;
import std.string;

void main() {
    int t = readln.chomp.to!int;
while(t--) {
    long w, h, n;
    readf("%s %s %s\n", &w, &h, &n);

    int x = 1;
    while(w % 2 == 0) {
        w /= 2;
        x *= 2;
    }

    int y = 1;
    while(h % 2 == 0) {
        h /= 2;
        y *= 2;
    }

    if(x*y >= n)
        "Yes".writeln;
    else
        "No".writeln;
}
}

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 a = readln.splitter.map !(to !(int)).array;
		int res = 1;
		foreach (j; 0..2)
		{
			while (a[j] % 2 == 0)
			{
				a[j] /= 2;
				res *= 2;
			}
		}
		writeln (res >= a[2] ? "Yes" : "No");
	}
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(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 long[](t);
	foreach (ti; 0..t)
	{
		auto w = RD;
		auto h = RD;
		auto n = RD;

		long x = 1, y = 1;
		while (w % 2 == 0)
		{
			x *= 2;
			w /= 2;
		}
		while (h % 2 == 0)
		{
			y *= 2;
			h /= 2;
		}

		ans[ti] = x*y >= n;
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush;
	debug readln;
}


Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.

The first line contains the integer n (1 ≤ n ≤ 105). n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≤ ai, bi, ci ≤ 109) — the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.

In the first line print k (1 ≤ k ≤ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to n — the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.

NoteIn the first example we can connect the pairs of stones:  2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1  2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively.  2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5  4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1  5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone:  1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5  2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1  3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5  4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5  5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1  6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.

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

void main() {
  int N = readln().chomp.to!int;
  Tuple!(int, int)[int][int] dict;
  int max_v = 0;
  Tuple!(int, int) max_i;
  int[][]abc = new int[][](N, 3);

  foreach (i; iota(1, N+1)) {
    auto input = readln().split.map!(to!int).array.sort;
    int a = input[0];
    int b = input[1];
    int c = input[2];
    abc[i-1] = [a,b,c];
    if (a > max_v) {
      max_v = a;
      max_i = tuple(i, -1);
    }
    if (!(a in dict) || !(b in dict[a]) || dict[a][b][0] < c)
      dict[a][b] = tuple(c, i);
    if (!(b in dict) || !(c in dict[b]) || dict[b][c][0] < a)
      dict[b][c] = tuple(a, i);
    if (!(c in dict) || !(a in dict[c]) || dict[c][a][0] < b)
      dict[c][a] = tuple(b, i);
  }

  foreach (i; iota(1, N+1)) {
    int a = abc[i-1][0];
    int b = abc[i-1][1];
    int c = abc[i-1][2];
    if (b in dict && c in dict[b] && dict[b][c][1] != i)
      if (max_v < min(b, c, dict[b][c][0]+a)) {
	max_v = min(b, c, dict[b][c][0]+a);
	max_i = tuple(i, dict[b][c][1]);
      }
  }

  if (max_i[1] == -1) {
    writeln(1);
    writeln(max_i[0]);
  } else {
    writeln(2);
    writeln(min(max_i[0], max_i[1]), " ", max(max_i[0], max_i[1]));
  }
}


The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?

The first line contains two integers, n and k (1 ≤ n ≤ 2000; 1 ≤ k ≤ 5). The next line contains n integers: y1, y2, ..., yn (0 ≤ yi ≤ 5), where yi shows the number of times the i-th person participated in the ACM ICPC world championship.

Print a single number — the answer to the problem.

NoteIn the first sample only one team could be made: the first, the fourth and the fifth participants.In the second sample no teams could be created.In the third sample two teams could be created. Any partition into two teams fits.

import std.stdio;
import core.stdc.stdio;
import std.algorithm;
import std.math;
import std.array;

int main(string[] argv)
{
	int n, k;
	scanf("%d %d", &n, &k);
	int eligible_members = 0;
	foreach (int i; 0..n)
	{
		int a;
		scanf("%d", &a);
		eligible_members += (a + k <= 5 ? 1 : 0);
	}
	write (eligible_members / 3);
	return 0;
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;

unittest{
  assert(solve(2,[0,4,5,1,0]) == 1, "Teste 1");
  assert(solve(4,[0,1,2,3,4,5]) == 0, "Teste 2");
  assert(solve(5,[0,0,0,0,0,0]) == 2, "Teste 3");
}

ulong solve(ulong k, ulong[] l){
  ulong max = 5 - k;
  ulong cnt = 0;
  foreach(x;l){
    if (x <= max){
      cnt++;
    }
  }
  debug(1) writeln(cnt/3);
  return cnt/3;
}

void main(){
  size_t n;
  ulong k;
  readf("%s %s ",&n,&k);

  ulong[] l = new ulong[n];
  for(size_t i = 0; i < n; i++){
    ulong t;
    readf("%s ",&t);
    l[i] = t;
  }
  writeln(solve(k,l));
  // auto s = r.map!"to!string(a)".array;
}


One day Om Nom found a thread with n beads of different colors. He decided to cut the first several beads from this thread to make a bead necklace and present it to his girlfriend Om Nelly.  Om Nom knows that his girlfriend loves beautiful patterns. That's why he wants the beads on the necklace to form a regular pattern. A sequence of beads S is regular if it can be represented as S = A + B + A + B + A + ... + A + B + A, where A and B are some bead sequences, " + " is the concatenation of sequences, there are exactly 2k + 1 summands in this sum, among which there are k + 1 "A" summands and k "B" summands that follow in alternating order. Om Nelly knows that her friend is an eager mathematician, so she doesn't mind if A or B is an empty sequence.Help Om Nom determine in which ways he can cut off the first several beads from the found thread (at least one; probably, all) so that they form a regular pattern. When Om Nom cuts off the beads, he doesn't change their order.

The first line contains two integers n, k (1 ≤ n, k ≤ 1 000 000) — the number of beads on the thread that Om Nom found and number k from the definition of the regular sequence above. The second line contains the sequence of n lowercase Latin letters that represent the colors of the beads. Each color corresponds to a single letter.

Print a string consisting of n zeroes and ones. Position i (1 ≤ i ≤ n) must contain either number one if the first i beads on the thread form a regular sequence, or a zero otherwise.

NoteIn the first sample test a regular sequence is both a sequence of the first 6 beads (we can take A = "", B = "bca"), and a sequence of the first 7 beads (we can take A = "b", B = "ca").In the second sample test, for example, a sequence of the first 13 beads is regular, if we take A = "aba", B = "ba".

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 n;
	int k;
	while (readf (" %s %s ", &n, &k) > 0)
	{
		auto s = readln ().strip ();
		int d = -1;
		auto p = [d];
		foreach (i; 0..n)
		{
			while (d >= 0 && s[d] != s[i])
			{
				d = p[d];
			}
			d++;
			p ~= d;
		}
		debug {writeln (p);}
		p.popFront ();
		auto res = new char [n];
		res[] = '0';
		foreach (i; 0..n)
		{
			long r = i + 1 - p[i];
			long q = (i + 1) / r;
			long r2 = r * (q / k);
			debug {writeln (r, ' ', q, ' ', r2);}
			long z = i + 1 - r2 * k;
			if (0 <= z && z <= r2)
			{
				res[i] = '1';
			}
		}
		writeln (res.idup);
	}
}

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 n;
	int k;
	while (readf (" %s %s ", &n, &k) > 0)
	{
		auto s = readln ().strip ();
		int d = -1;
		auto p = [d];
		foreach (i; 0..n)
		{
			while (d >= 0 && s[d] != s[i])
			{
				d = p[d];
			}
			d++;
			p ~= d;
		}
		debug {writeln (p);}
		p.popFront ();
		auto res = new char [n];
		res[] = '0';
		foreach (i; 0..n)
		{
			long r = i + 1 - p[i];
			long q = (i + 1) / r;
			long r2 = r * (q / k);
			debug {writeln (r, ' ', q, ' ', r2);}
			long z = i + 1 - r2 * k;
			if (0 <= z && z < r2)
			{
				res[i] = '1';
			}
		}
		writeln (res.idup);
	}
}


There is a badminton championship in which $$$n$$$ players take part. The players are numbered from $$$1$$$ to $$$n$$$. The championship proceeds as follows: player $$$1$$$ and player $$$2$$$ play a game, then the winner and player $$$3$$$ play a game, and then the winner and player $$$4$$$ play a game, and so on. So, $$$n-1$$$ games are played, and the winner of the last game becomes the champion. There are no draws in the games.You want to find out the result of championship. Currently, you only know the following information:  Each player has either won $$$x$$$ games or $$$y$$$ games in the championship. Given $$$n$$$, $$$x$$$, and $$$y$$$, find out if there is a result that matches this information.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The only line of each test case contains three integers $$$n$$$, $$$x$$$, $$$y$$$ ($$$2 \le n \le 10^5$$$, $$$0 \le x, y < n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Print the answer for each test case, one per line. If there is no result that matches the given information about $$$n$$$, $$$x$$$, $$$y$$$, print $$$-1$$$. Otherwise, print $$$n-1$$$ space separated integers, where the $$$i$$$-th integer is the player number of the winner of the $$$i$$$-th game.  If there are multiple valid results, print any.

NoteIn the first test case, player $$$1$$$ and player $$$4$$$ won $$$x$$$ times, player $$$2$$$ and player $$$3$$$ won $$$y$$$ times.In the second, third, and fifth test cases, no valid result exists.

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n, x, y;
        scanf("%d %d %d\n", &n, &x, &y);
        if (min(x,y) != 0) {
            writeln(-1);
            continue;
        }
        else {
            int r = max(x,y);
            if (r == 0) {
                write(-1);
            }
            else if (r == 1)
                foreach(i; 0 .. n - 1)
                    write(i + 2, " ");
            else if (r == n - 1)
                foreach(i; 0 .. n - 1)
                    write("1 ");
            else {
                if ((n - 1) % r == 0) {
                    int l = 1;
                    int count = 0;
                    foreach(i; 2 .. n + 1) {
                        if (count == r) {
                            count = 0;
                            l = i;
                        }
                        write(l, " ");
                        count++;
                    }
                }
                else
                    write(-1);
            }
        }
        writeln();
    }
}

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n, x, y;
        scanf("%d %d %d\n", &n, &x, &y);
        if (min(x,y) != 0) {
            writeln(-1);
            continue;
        }
        else {
            int r = max(x,y);
            if (r == 0) {
                write(-1);
            }
            else if (r == 1)
                foreach(i; 0 .. n - 1)
                    write(i + 2, " ");
            else if (r == n - 1)
                foreach(i; 0 .. n - 1)
                    write("1 ");
            else if (n % 2 == 0) {
                    write(-1);
            }
            else {
                if ((n - 1) % r == 0) {
                    int l = 1;
                    int count = 0;
                    foreach(i; 2 .. n + 1) {
                        if (count == r) {
                            count = 0;
                            l = i;
                        }
                        write(l, " ");
                        count++;
                    }
                }
                else
                    write(-1);
            }
        }
        writeln();
    }
}

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n, x, y;
        scanf("%d %d %d\n", &n, &x, &y);
        if (min(x,y) != 0) {
            writeln(-1);
            continue;
        }
        else {
            int r = max(x,y);
            if (r == 0) {
                write(-1);
            }
            else if (r == 1)
                foreach(i; 0 .. n - 1)
                    write(i + 2, " ");
            else if (r == n - 1)
                foreach(i; 0 .. n - 1)
                    write("1 ");
            else if (n % 2 == 0) {
                    write(-1);
            }
            else {
                int l = 1;
                if ((n - 1) % r == 0)
                    foreach(i;2..n+1) {
                        write(l, " ");
                        if ((i-1) % r == 0)
                            l = i + 1;

                    }
                else
                    write(-1);
            }
        }
        writeln();
    }
}

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n, x, y;
        scanf("%d %d %d\n", &n, &x, &y);
        if (min(x,y) != 0) {
            writeln(-1);
            continue;
        }
        else {
            int r = max(x,y);
            if (r == 1)
                foreach(i; 0 .. n - 1)
                    write(i + 2, " ");
            else if (r == n - 1)
                foreach(i; 0 .. n - 1)
                    write("1 ");
            else if (n % 2 == 0) {
                    write(-1);
            }
            else {
                if (r == (n-1) / 2)
                    foreach(i;0..n - 1)
                        if (i < (n-1) / 2)
                            write("1 ");
                        else
                            write((n-1) / 2 + 2, " ");
                else
                    write(-1);
            }
        }
        writeln();
    }
}

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n, x, y;
        scanf("%d %d %d\n", &n, &x, &y);
        if (min(x,y) != 0) {
            writeln(-1);
            continue;
        }
        else {
            int r = max(x,y);
            if (n % 2 == 0) {
                if (r == n - 1)
                    foreach(i; 0 .. n - 1)
                        write("1 ");
                else if (r == 1)
                    foreach(i; 0 .. n - 1)
                        write(i + 2, " ");
                else
                    write(-1);
            }
            else {
                if (r == n - 1)
                    foreach(i; 0 .. n - 1)
                        write("1 ");
                else if (r == (n-1) / 2)
                    foreach(i;0..n - 1)
                        if (i < (n-1) / 2)
                            write("1 ");
                        else
                            write((n-1) / 2 + 2, " ");
                else
                    write(-1);
            }
        }
        writeln();
    }
}

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n, x, y;
        scanf("%d %d %d\n", &n, &x, &y);
        if (min(x,y) != 0) {
            writeln(-1);
            continue;
        }
        else {
            int r = max(x,y);
            if (n % 2 == 0) {
                if (r == n - 1)
                    foreach(i; 0 .. n - 1)
                        write("1 ");
                else
                    write(-1);
            }
            else {
                if (r == n - 1)
                    foreach(i; 0 .. n - 1)
                        write("1 ");
                else if (r == (n-1) / 2)
                    foreach(i;0..n - 1)
                        if (i < (n-1) / 2)
                            write("1 ");
                        else
                            write((n-1) / 2 + 2, " ");
                else
                    write(-1);
            }
        }
        writeln();
    }
}

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n, x, y;
        scanf("%d %d %d\n", &n, &x, &y);
        if (min(x,y) != 0) {
            writeln(-1);
            continue;
        }
        else {
            int r = max(x,y);
            if (n % 2 == 0) {
                if (r == n - 1)
                    foreach(i; 0 .. n - 1)
                        write("1 ");
                else
                    write(-1);
            }
            else {
                if (r == (n-1) / 2)
                    foreach(i;0..n - 1)
                        if (i < (n-1) / 2)
                            write("1 ");
                        else
                            write((n-1) / 2 + 2, " ");
                else
                    write(-1);
            }
        }
        writeln();
    }
}

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n, x, y;
        scanf("%d %d %d\n", &n, &x, &y);
        if (min(x,y) != 0) {
            writeln(-1);
            continue;
        }
        else {
            int r = max(x,y);
            if (n % 2 == 0) {
                if (r == n - 1)
                    foreach(i; 0 .. n - 1)
                        write(1);
                else
                    write(-1);
            }
            else {
                if (r == (n-1) / 2)
                    foreach(i;0..n - 1)
                        if (i < (n-1) / 2)
                            write("1 ");
                        else
                            write((n-1) / 2 + 2, " ");
                else
                    write(-1);
            }
        }
        writeln();
    }
}

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n, x, y;
        scanf("%d %d %d\n", &n, &x, &y);
        if (min(x,y) != 0) {
            writeln(-1);
            continue;
        }
        else {
            int r = max(x,y);
            if (n % 2 == 0) {
                if (r == n - 1)
                    foreach(i; 0 .. n - 1)
                        write(1);
                else
                    write(-1);
            }
            else {
                if (r == n / 2)
                    foreach(i;0..n - 1)
                        if (i < n/2)
                            write("1 ");
                        else
                            write(n/2, " ");
                else
                    write(-1);
            }
        }
        writeln();
    }
}


The New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point — the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.

The first line contains an integer n (1 ≤ n ≤ 2·105) which represents the number of houses in the village. The second line contains the coordinates of houses — the sequence x1, x2, ..., xn of integer numbers (1 ≤ xi ≤ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.

Print the required minimal power d. In the second line print three numbers — the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.

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

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

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

    arr.sort();

    bool chk(double d) {
        double reach = 2 * d;
        int st = 0;
        foreach (i; 0 .. 3) {
            int le = st, r = n-1;
            while (le < r) {
                auto m = (le + r + 1) / 2;
                if (arr[m] - arr[st] <= reach) { le = m; }
                else { r = m-1; }
            }

            st = r + 1;
        }

        return st == n;
    }

    double le = 0, r = 10 ^^ 9;
    foreach (_; 0 .. 100) {
        auto m = (le + r) / 2;
        if (chk(m)) { r = m; }
        else { le = m; }
    }

    auto pos = [arr[0] + r];

    int idx = 0;
    while (idx + 1 < n && abs(pos[0] - arr[idx]) <= r) { ++idx; }

    debug { writeln(idx, ' ', arr[idx-1], ' ', arr[idx]); }

    pos ~= arr[idx] + r;

    pos ~= arr[n-1] - r;

    r.writefln!"%.10f";
    pos.writefln!"%(%.10f %)";
}

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

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

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

    arr.sort();

    bool chk(double d) {
        double reach = 2 * d;
        int st = 0;
        foreach (_; 0 .. 3) {
            int le = st, r = n-1;
            while (le < r) {
                auto m = (le + r + 1) / 2;
                if (arr[m] - arr[le] <= reach) { le = m; }
                else { r = m-1; }
            }

            st = r + 1;
        }

        return st == n;
    }

    double le = 0, r = 10 ^^ 9;
    foreach (_; 0 .. 200) {
        auto m = (le + r) / 2;
        if (chk(m)) { r = m; }
        else { le = m; }
    }

    r.writefln!"%.10f";

    auto pos = [arr[0] + r];

    int idx = 0;
    while (idx + 1 < n && abs(pos[0] - arr[idx]) <= r) { ++idx; }

    pos ~= arr[idx] + r;

    pos ~= arr[n-1] - r;

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

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

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

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

    arr.sort();

    bool chk(double d) {
        double reach = 2 * d;
        int st = 0;
        foreach (_; 0 .. 3) {
            int le = st, r = n-1;
            while (le < r) {
                auto m = (le + r + 1) / 2;
                if (arr[m] - arr[le] <= reach) { le = m; }
                else { r = m-1; }
            }

            st = r + 1;
        }

        return st == n;
    }

    double le = 0, r = 10 ^^ 9;
    foreach (_; 0 .. 100) {
        auto m = (le + r) / 2;
        if (chk(m)) { r = m; }
        else { le = m; }
    }

    r.writefln!"%.10f";

    auto pos = [arr[0] + r];

    int idx = 0;
    while (idx + 1 < n && arr[0] + 2*r >= arr[idx]) { ++idx; }

    pos ~= arr[idx] + r;

    pos ~= arr[n-1] - r;

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


Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others.The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal.

Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0".

NoteConsider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090.  If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals.  If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds).  If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds.

import std.stdio;
import std.algorithm;

void main() {
  int n;
  readf(" %s", &n);
  int[][2] times_at_semifinals;
  for (int time_i = 0; time_i < n; time_i++) {
    int time_semifinal_a, time_semifinal_b;
    readf(" %s %s", &time_semifinal_a, &time_semifinal_b);
    times_at_semifinals[0] ~= time_semifinal_a;
    times_at_semifinals[1] ~= time_semifinal_b;
  }
  const all_times = (times_at_semifinals[0] ~ times_at_semifinals[1]).sort;
  const borderline_time = all_times[n];
  for (int semifinal_i = 0; semifinal_i < 2; semifinal_i++) {
    for (int time_i = 0; time_i < n; time_i++) {
      if (time_i < n/2 ||
          times_at_semifinals[semifinal_i][time_i] < borderline_time) {
        write(1);
      } else {
        write(0);
      }
    }
    writeln("");
  }
}

import std.stdio;
import std.algorithm;

void main() {
  int n;
  readf(" %s", &n);
  int[][2] times_at_semifinals;
  for (int time_i = 0; time_i < n; time_i++) {
    int time_semifinal_a, time_semifinal_b;
    readf(" %s %s", &time_semifinal_a, &time_semifinal_b);
    times_at_semifinals[0] ~= time_semifinal_a;
    times_at_semifinals[1] ~= time_semifinal_b;
  }
  const all_times = (times_at_semifinals[0] ~ times_at_semifinals[1]).sort;
  const borderline_time = all_times[n];
  writeln("border ", borderline_time);
  for (int semifinal_i = 0; semifinal_i < 2; semifinal_i++) {
    for (int time_i = 0; time_i < n; time_i++) {
      if (time_i < n/2 ||
          times_at_semifinals[semifinal_i][time_i] < borderline_time) {
        write(1);
      } else {
        write(0);
      }
    }
    writeln("");
  }
}

import std.stdio;
import std.algorithm;

void main() {
  int n;
  readf(" %s", &n);
  int[][2] times_at_semifinals;
  for (int time_i = 0; time_i < n; time_i++) {
    int time_semifinal_a, time_semifinal_b;
    readf(" %s %s", &time_semifinal_a, &time_semifinal_b);
    times_at_semifinals[0] ~= time_semifinal_a;
    times_at_semifinals[1] ~= time_semifinal_b;
  }
  auto all_times = (times_at_semifinals[0] ~
                    times_at_semifinals[1]).sort;
  const borderline_time = all_times[n/2+1];

  for (int semifinal_i = 0; semifinal_i < 2; semifinal_i++) {
    for (int time_i = 0; time_i < n; time_i++) {
      if (time_i < n/2 ||
          times_at_semifinals[semifinal_i][time_i] <= borderline_time) {
        write(1);
      } else {
        write(0);
      }
    }
    writeln("");
  }
}


One night, Mark realized that there is an essay due tomorrow. He hasn't written anything yet, so Mark decided to randomly copy-paste substrings from the prompt to make the essay.More formally, the prompt is a string $$$s$$$ of initial length $$$n$$$. Mark will perform the copy-pasting operation $$$c$$$ times. Each operation is described by two integers $$$l$$$ and $$$r$$$, which means that Mark will append letters $$$s_l s_{l+1} \ldots s_r$$$ to the end of string $$$s$$$. Note that the length of $$$s$$$ increases after this operation.Of course, Mark needs to be able to see what has been written. After copying, Mark will ask $$$q$$$ queries: given an integer $$$k$$$, determine the $$$k$$$-th letter of the final string $$$s$$$.

The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$c$$$, and $$$q$$$ ($$$1\leq n\leq 2\cdot 10^5$$$, $$$1\leq c\leq 40$$$, and $$$1\leq q\leq 10^4$$$) — the length of the initial string $$$s$$$, the number of copy-pasting operations, and the number of queries, respectively. The second line of each test case contains a single string $$$s$$$ of length $$$n$$$. It is guaranteed that $$$s$$$ only contains lowercase English letters. The following $$$c$$$ lines describe the copy-pasting operation. Each line contains two integers $$$l$$$ and $$$r$$$ ($$$1\leq l\leq r\leq 10^{18}$$$). It is also guaranteed that $$$r$$$ does not exceed the current length of $$$s$$$. The last $$$q$$$ lines of each test case describe the queries. Each line contains a single integer $$$k$$$ ($$$1\leq k\leq 10^{18}$$$). It is also guaranteed that $$$k$$$ does not exceed the final length of $$$s$$$. It is guaranteed that the sum of $$$n$$$ and $$$q$$$ across all test cases does not exceed $$$2\cdot 10^5$$$ and $$$10^4$$$, respectively.

For each query, print the $$$k$$$-th letter of the final string $$$s$$$.

NoteIn the first test case, the copy-paste process is as follows.   The first step is pasting string $$$\texttt{mark}$$$ at the end, yielding the string $$$\texttt{mark}\color{red}{\texttt{mark}}$$$.  The second step is pasting string $$$\texttt{mar}$$$ at the end, yielding the string $$$\texttt{markmark}\color{red}{\texttt{mar}}$$$.  The third step is pasting string $$$\texttt{rkmark}$$$ at the end, yielding the string $$$\texttt{markmarkmar}\color{red}{\texttt{rkmark}}$$$. In the second test case, the copy-paste process is as follows.   The first step is pasting string $$$\texttt{re}$$$ at the end, yielding the string $$$\texttt{creamii}\color{red}{\texttt{re}}$$$.  The second step is pasting string $$$\texttt{ea}$$$ at the end, yielding the string $$$\texttt{creamiire}\color{red}{\texttt{ea}}$$$.  The third step is pasting string $$$\texttt{reamiire}$$$ at the end, yielding the string $$$\texttt{creamiireea}\color{red}{\texttt{reamiire}}$$$.

// cheese-cracker [2022-07-15]

int getpos(long pos, ref long[] prefs){
    int j = 0;
    for(; j < prefs.length; ++j){
        if(prefs[j] > pos){
            --j;
            break;
        }
    }
    return j;
}

void solve(){
    int n = scan!int;
    int c = scan!int;
    int q = scan!int;

    auto s = scan!(dchar[]);
    long[] prefs;
    long[] ivals;
    ivals ~= 0;
    prefs ~= 0;
    prefs ~= n;
    long lentt = n;
    for(int k = 0; k < c; ++k){
        long l = scan;
        long r = scan;
        long len = (r - l + 1);
        ivals ~= l - 1;
        lentt += len;
        prefs ~= lentt;
    }
    /* show(prefs); */
    /* show(ivals); */
    for(int m = 0; m < q; ++m){
        long k = scan - 1;
        /* show(k); */
        while(k >= n){
            int j = getpos(k, prefs);
            long kleft = k - prefs[j];
            /* show(k, ivals[j]); */
            k = kleft + ivals[j];
        }
        writeln(s[k.to!int]);
    }
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }


George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer bi.To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a1, at least one with complexity exactly a2, ..., and at least one with complexity exactly an. Of course, the round can also have problems with other complexities.George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c ≥ d), by changing limits on the input data.However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.

The first line contains two integers n and m (1 ≤ n, m ≤ 3000) — the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a1, a2, ..., an (1 ≤ a1 < a2 < ... < an ≤ 106) — the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b1, b2, ..., bm (1 ≤ b1 ≤ b2... ≤ bm ≤ 106) — the complexities of the problems prepared by George.

Print a single integer — the answer to the problem.

NoteIn the first sample the set of the prepared problems meets the requirements for a good round.In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.

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

void main() {
    int n, m; readf("%d %d\n", &n, &m);
    int[] a = stdin.readln.chop.split.map!(to!int).array;
    int[] b = stdin.readln.chop.split.map!(to!int).array;
    a.sort!"a > b";
    b.sort!"a > b";
    int ai = 0, bi = 0;
    int x = n;
    while (ai < n && bi < m) {
        if (a[ai] <= b[bi]) {
            x--;
            ai++;
            bi++;
        } else {
            ai++;
        }
    }
    x.writeln;
}

import std.stdio;
import std.math;

void main()
{
	int n, m;
	int[] a, b;
	scanf("%d %d", &n, &m);
	a.length = n;
	b.length = m;
	foreach (i; 0 .. n) scanf("%d", &a[i]);
	foreach (i; 0 .. m) scanf("%d", &b[i]);
	int result;
	while (b.length) {
		if (a.length == 0) break;
		if (b[0] < a[0]) {
			b = b[1..$];
		} else {
			a = a[1..$];
			b = b[1..$];
		}
	}
	writeln(a.length);
}


Petya recieved a gift of a string s with length up to 105 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game has two possible moves:  Extract the first character of s and append t with this character.  Extract the last character of t and append u with this character. Petya wants to get strings s and t empty and string u lexicographically minimal.You should write a program that will help Petya win the game.

First line contains non-empty string s (1 ≤ |s| ≤ 105), consisting of lowercase English letters.

import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.container, std.math, std.typecons;

char[] s;

void main() {
    s = readln.chomp.to!(char[]);

    int n = s.length.to!int;

    auto t = Stack!(char)(n + 10);
    auto u = new char[](n);

    auto cnt = new int[](26);

    foreach (ch ; s) {
        cnt[ch - 'a']++;
    }

    int ui;

    while (!s.empty) {
        if (t.empty) {
            t.push(s.front.to!char);
            cnt[s.front - 'a']--;
            s.popFront;
        }
        else {
            if (cnt[0 .. (t.top - 'a')].sum > 0) {
                t.push(s.front.to!char);
                cnt[s.front - 'a']--;
                s.popFront;
            }
            else {
                u[ui++] = t.top;
                t.pop;
            }
        }
    }

    while (!t.empty) {
        u[ui++] = t.top;
        t.pop;
    }

    writeln(u);
}

void scan(T...)(ref T args) {
    auto line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    assert(line.empty);
}

struct Stack(T) {
private:
    int N, peek;
    T[] data;

public:
    this(int size)
    {
        N = size;
        data = new T[](N);
    }

    bool empty() @property
    {
        return peek == 0;
    }

    bool full() @property
    {
        return peek == N;
    }

    void push(T x) @property
    {
        assert(!full);
        data[peek++] = x;
    }

    void pop() @property
    {
        assert(!empty);
        --peek;
    }

    T top() @property
    {
        return data[peek - 1];
    }

    void clear() @property
    {
        peek = 0;
    }

    int length() @property
    {
        return peek;
    }

}

import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.container, std.math, std.typecons;

char[] s;

void main() {
    s = readln.chomp.to!(char[]);

    debug {
        writeln("s:", s);
    }

    int n = s.length.to!int;

    int[] acnt = new int[](26);

    foreach (ch ; s) {
        acnt[ch - 'a']++;
    }

    debug {
        writeln("acnt:", acnt);
    }

    auto u = new char[](n);
    int ui = 0;

    auto st = new Stack!char(n + 10);

    while (ui < n) {
        if (s.empty) {
            while (!st.empty) {
                u[ui++] = st.top.to!char;
                st.pop;
            }
            break;
        }
        if (st.empty) {
            st.push(s.front.to!char);
            acnt[s.front - 'a']--;
            s.popFront;
        }
        else {
            debug {
                writeln(st.top, " ", (st.top - 'a').to!int);
                writeln(acnt[0 .. (st.top - 'a').to!int]);
            }
            if (acnt[0 .. (st.top - 'a').to!int].sum > 0) {
                st.push(s.front.to!char);
                acnt[s.front - 'a']--;
                s.popFront;
            }
            else {
                u[ui++] = st.top;
                //acnt[(st.top - 'a').to!int]--;
                st.pop;
            }
        }

        debug {
            //writeln("s:", s);
            writeln("acnt:", acnt);
        }
    }

    writeln(u);
}

void scan(T...)(ref T args) {
    auto line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    assert(line.empty);
}

struct Stack(T) {
private:
    int N, peek;
    T[] data;

public:
    this(int size)
    {
        N = size;
        data = new T[](N);
    }

    bool empty() @property
    {
        return peek == 0;
    }

    bool full() @property
    {
        return peek == N;
    }

    void push(T x) @property
    {
        assert(!full);
        data[peek++] = x;
    }

    void pop() @property
    {
        assert(!empty);
        --peek;
    }

    T top() @property
    {
        return data[peek - 1];
    }

    void clear() @property
    {
        peek = 0;
    }

    int length() @property
    {
        return peek;
    }

}

import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.container, std.math, std.typecons;

dchar[] s;

void main() {
    s = readln.chomp.to!(dchar[]);

    debug {
        writeln("s:", s);
    }

    int n = s.length.to!int;

    int[] acnt = new int[](26);

    foreach (ch ; s) {
        acnt[ch - 'a']++;
    }

    debug {
        writeln("acnt:", acnt);
    }

    auto u = new dchar[](n);
    int ui = 0;

    auto st = new Stack!dchar(n + 10);

    while (ui < n) {
        if (s.empty) {
            while (!st.empty) {
                u[ui++] = st.top.to!dchar;
                st.pop;
            }
            break;
        }
        if (st.empty) {
            st.push(s.front.to!dchar);
            s.popFront;
        }
        else {
            if (acnt[0 .. (st.top - 'a').to!int].sum > 0) {
                st.push(s.front.to!dchar);
                acnt[s.front - 'a']--;
                s.popFront;
            }
            else {
                u[ui++] = st.top;
                st.pop;
            }
        }

        debug {
            writeln("s:", s);
        }
    }

    writeln(u);
}

void scan(T...)(ref T args) {
    auto line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    assert(line.empty);
}

struct Stack(T) {
private:
    int N, peek;
    T[] data;

public:
    this(int size)
    {
        N = size;
        data = new T[](N);
    }

    bool empty() @property
    {
        return peek == 0;
    }

    bool full() @property
    {
        return peek == N;
    }

    void push(T x) @property
    {
        assert(!full);
        data[peek++] = x;
    }

    void pop() @property
    {
        assert(!empty);
        --peek;
    }

    T top() @property
    {
        return data[peek - 1];
    }

    void clear() @property
    {
        peek = 0;
    }

    int length() @property
    {
        return peek;
    }

}


Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;m] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor decided to share it with Sasha.Sasha knows that Teodor likes to show off so he never trusts him. Teodor wants to prove that he can be trusted sometimes, so he decided to convince Sasha that there is no such integer point in his picture, which belongs to each segment. However Teodor is lazy person and neither wills to tell Sasha all coordinates of segments' ends nor wills to tell him their amount, so he suggested Sasha to ask him series of questions 'Given the integer point xi, how many segments in Fedya's picture contain that point?', promising to tell correct answers for this questions.Both boys are very busy studying and don't have much time, so they ask you to find out how many questions can Sasha ask Teodor, that having only answers on his questions, Sasha can't be sure that Teodor isn't lying to him. Note that Sasha doesn't know amount of segments in Teodor's picture. Sure, Sasha is smart person and never asks about same point twice.

First line of input contains two integer numbers: n and m (1 ≤ n, m ≤ 100 000) — amount of segments of Teodor's picture and maximal coordinate of point that Sasha can ask about. ith of next n lines contains two integer numbers li and ri (1 ≤ li ≤ ri ≤ m) — left and right ends of ith segment in the picture. Note that that left and right ends of segment can be the same point. It is guaranteed that there is no integer point, that belongs to all segments.

Single line of output should contain one integer number k – size of largest set (xi, cnt(xi)) where all xi are different, 1 ≤ xi ≤ m, and cnt(xi) is amount of segments, containing point with coordinate xi, such that one can't be sure that there doesn't exist point, belonging to all of segments in initial picture, if he knows only this set(and doesn't know n).

NoteFirst example shows situation where Sasha can never be sure that Teodor isn't lying to him, because even if one knows cnt(xi) for each point in segment [1;4], he can't distinguish this case from situation Teodor has drawn whole [1;4] segment.In second example Sasha can ask about 5 points e.g. 1, 2, 3, 5, 6, still not being sure if Teodor haven't lied to him. But once he knows information about all points in [1;6] segment, Sasha can be sure that Teodor haven't lied to him.

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

int [] fun (int [] a)
{
	auto p = new int [a.length + 1];
	p[] = int.max;
	p[0] = int.min;
	int [] res;
	foreach (c; a)
	{
		int lo = 0;
		int hi = p.length.to !(int) - 1;
		while (lo < hi)
		{
			int me = (lo + hi) / 2;
			if (p[me] <= c)
			{
				lo = me + 1;
			}
			else
			{
				hi = me;
			}
		}
		p[lo] = c;
		res ~= lo;
	}
	debug {writeln (a); writeln (p); writeln (res);}
	return res;
}

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto v = new int [m + 2];
		foreach (i; 0..n)
		{
			int x, y;
			readf (" %s %s", &x, &y);
			v[x] += 1;
			v[y + 1] -= 1;
		}
		foreach (j; 0..m + 1)
		{
			v[j + 1] += v[j];
		}
		v = v[1..$ - 1];

		auto x = fun (v);
		reverse (v);
		auto y = fun (v);
		reverse (y);
		int res = 0;
		foreach (i; 0..x.length)
		{
			res = max (res, x[i] + y[i] - 1);
		}
		writeln (res);
	}
}

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

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

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

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

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

      auto as = new int[M];
      foreach (i; 0 .. N) {
        ++as[L[i]];
        if (R[i] < M) {
          --as[R[i]];
        }
      }
      foreach (j; 1 .. M) {
        as[j] += as[j - 1];
      }
      debug {
        writeln("as = ", as);
      }

      int[] doIt() {
        auto dp = new int[M];
        int[] lis;
        foreach (j; 0 .. M) {
          const pos = lis.upperBound(as[j]);
          if (pos == lis.length) {
            lis ~= as[j];
          } else {
            lis[pos] = as[j];
          }
          dp[j] = pos + 1;
        }
        debug {
          writeln(as, ": ", dp);
        }
        return dp;
      }

      auto dpL = doIt();
      as.reverse;
      auto dpR = doIt();
      as.reverse;
      dpR.reverse;
      int ans;
      foreach (j; 0 .. M) {
        chmax(ans, dpL[j] + dpR[j] - 1);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

int fun (int [] a)
{
	auto p = new int [a.length + 1];
	p[] = int.max;
	p[0] = int.min;
	int res = 0;
	foreach (c; a)
	{
		int lo = 0;
		int hi = p.length.to !(int) - 1;
		while (lo < hi)
		{
			int me = (lo + hi) / 2;
			if (p[me] <= c)
			{
				lo = me + 1;
			}
			else
			{
				hi = me;
			}
		}
		p[lo] = c;
		res = max (res, lo);
	}
	debug {writeln (a); writeln (p);}
	return res;
}

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto v = new int [m + 2];
		foreach (i; 0..n)
		{
			int x, y;
			readf (" %s %s", &x, &y);
			v[x] += 1;
			v[y + 1] -= 1;
		}
		foreach (j; 0..m + 1)
		{
			v[j + 1] += v[j];
		}
		v = v.filter !(x => x > 0).array;

		int res = 0;
		res = max (res, fun (v));
		reverse (v);
		res = max (res, fun (v));
		writeln (res);
	}
}

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

int [] fun (int [] a)
{
	auto p = new int [a.length + 1];
	p[] = int.max;
	p[0] = int.min;
	int [] res;
	foreach (c; a)
	{
		int lo = 0;
		int hi = p.length.to !(int) - 1;
		while (lo < hi)
		{
			int me = (lo + hi) / 2;
			if (p[me] <= c)
			{
				lo = me + 1;
			}
			else
			{
				hi = me;
			}
		}
		p[lo] = c;
		res ~= lo;
	}
	debug {writeln (a); writeln (p); writeln (res);}
	return res;
}

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto v = new int [m + 2];
		foreach (i; 0..n)
		{
			int x, y;
			readf (" %s %s", &x, &y);
			v[x] += 1;
			v[y + 1] -= 1;
		}
		foreach (j; 0..m + 1)
		{
			v[j + 1] += v[j];
		}
		v = v.filter !(x => x > 0).array;

		auto x = fun (v);
		reverse (v);
		auto y = fun (v);
		reverse (y);
		int res = 0;
		foreach (i; 0..x.length)
		{
			res = max (res, x[i] + y[i] - 1);
		}
		writeln (res);
	}
}

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

int fun (int [] a)
{
	auto p = new int [a.length];
	p[] = int.max;
	p[0] = int.min;
	int res = 0;
	foreach (c; a[1..$ - 1])
	{
		int lo = 0;
		int hi = a.length.to !(int) - 1;
		while (lo < hi)
		{
			int me = (lo + hi) / 2;
			if (p[me] <= c)
			{
				lo = me + 1;
			}
			else
			{
				hi = me;
			}
		}
		p[lo] = c;
		res = max (res, lo);
	}
	debug {writeln (a); writeln (p);}
	return res;
}

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto v = new int [m + 2];
		foreach (i; 0..n)
		{
			int x, y;
			readf (" %s %s", &x, &y);
			v[x] += 1;
			v[y + 1] -= 1;
		}
		foreach (j; 0..m + 1)
		{
			v[j + 1] += v[j];
		}

		int res = 0;
		res = max (res, fun (v));
		reverse (v);
		res = max (res, fun (v));
		writeln (res);
	}
}


This is an easier version of the next problem. The difference is only in constraints.You are given a rectangular $$$n \times m$$$ matrix $$$a$$$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $$$i$$$-th row it is equal $$$r_i$$$. What is the maximal possible value of $$$r_1+r_2+\ldots+r_n$$$?

The first line contains an integer $$$t$$$ ($$$1 \le t \le 40$$$), the number of test cases in the input. The first line of each test case contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 4$$$, $$$1 \le m \le 100$$$) — the number of rows and the number of columns in the given matrix $$$a$$$.  Each of the following $$$n$$$ lines contains $$$m$$$ integers, the elements of $$$a$$$ ($$$1 \le a_{i, j} \le 10^5$$$).

Print $$$t$$$ integers: answers for all test cases in the order they are given in the input.

NoteIn the first test case, you can shift the third column down by one, this way there will be $$$r_1 = 5$$$ and $$$r_2 = 7$$$.In the second case you can don't rotate anything at all, this way there will be $$$r_1 = r_2 = 10$$$ and $$$r_3 = 9$$$.

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return read.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtype!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void solve(){
	int t = rint;
	foreach(_; 0 .. t){
		int n = rint, m = rint;
		int[][] af = rint(n, m);

		S[] ss;
		foreach(i; 0 .. n) foreach(j; 0 .. m){
			ss ~= S(i, j, af[i][j]);
		}

		ss.sort!"a.value>b.value"();

		int ans = ss[0 .. n].map!(s => s.value).sum;

		if(n == 4){
			S[] tops = ss[0 .. 4].dup;
			tops.sort!"a.j>b.j"();
			log("ss[0 .. 6]:", ss[0 .. 6]);
			log("tops:", tops);
			if(tops[0].j == tops[1].j && tops[1].j != tops[2].j
					&& tops[2].j == tops[3].j){
				log(" - is AABB");
				if((tops[0].i + 4 - tops[1].i) % 2 != (tops[2].i + 4 - tops[3].i) % 2){
					log(" - is special");
					if((ss[4].j == tops[0].j || ss[4].j == tops[2].j)
							&& ss[3].j == ss[4].j && (ss[3].i + 4 - ss[4].i) % 2 == 0){
						log(" - is super special");
							// 1 2 3 6 v.s. 1 2 4 5
						ans = max(
								ss[0].value + ss[1].value + ss[2].value + ss[5].value,
								ss[0].value + ss[1].value + ss[3].value + ss[4].value
						);
					}
					else{
						log(" - is ordinary special");
						// 1 2 3 5
						ans = ss[0].value + ss[1].value + ss[2].value + ss[4].value;
					}
				}
			}
		}

		ans.writeln;
	}
}

struct S{
	int i, j;
	int value;
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return read.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtype!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void solve(){
	int t = rint;
	foreach(_; 0 .. t){
		int n = rint, m = rint;
		int[][] af = rint(n, m);

		S[] ss;
		foreach(i; 0 .. n) foreach(j; 0 .. m){
			ss ~= S(i, j, af[i][j]);
		}

		ss.sort!"a.value>b.value"();

		int ans = ss[0 .. n].map!(s => s.value).sum;

		if(n == 4){
			S[] tops = ss[0 .. 4];
			tops.sort!"a.j>b.j"();
			if(tops[0].j == tops[1].j && tops[1].j != tops[2].j
					&& tops[2].j == tops[3].j){
				if((tops[0].i + 4 - tops[1].i) % 2 != (tops[2].i + 4 - tops[3].i) % 2){
					if((ss[4].j == tops[0].j || ss[4].j == tops[2].j)
							&& ss[3].j == ss[4].j && (ss[3].i + 4 - ss[4].i) % 2 == 0){
							// 1 2 3 6 v.s. 1 2 4 5
						ans = max(
								ss[0].value + ss[1].value + ss[2].value + ss[5].value,
								ss[0].value + ss[1].value + ss[3].value + ss[4].value
						);
					}
					else{
						// 1 2 3 5
						ans = ss[0].value + ss[1].value + ss[2].value + ss[4].value;
					}
				}
			}
		}

		ans.writeln;
	}
}

struct S{
	int i, j;
	int value;
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return read.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtype!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void solve(){
	int t = rint;
	foreach(_; 0 .. t){
		int n = rint, m = rint;
		int[][] af = rint(n, m);

		S[] ss;
		foreach(i; 0 .. n) foreach(j; 0 .. m){
			ss ~= S(i, j, af[i][j]);
		}

		ss.sort!"a.value>b.value"();

		int ans = ss[0 .. n].map!(s => s.value).sum;

		if(n == 4){
			S[] tops = ss[0 .. 4];
			tops.sort!"a.j>b.j"();
			if(tops[0].j == tops[1].j && tops[1].j != tops[2].j
					&& tops[2].j == tops[3].j){
				if((tops[0].i + 4 - tops[1].i) % 2 != (tops[2].i + 4 - tops[3].i) % 2){
					if(ss[4].j == tops[0].j || ss[4].j == tops[2].j){
						if(ss[3].j == ss[4].j && (ss[3].i + 4 - ss[4].i) % 2 == 0){
							// 1 2 3 6 v.s. 1 2 4 5
							ans = max(
									ss[0].value + ss[1].value + ss[2].value + ss[5].value,
									ss[0].value + ss[1].value + ss[3].value + ss[4].value,
							);
						}
						else{
							// 1 2 3 5
							ans = ss[0].value + ss[1].value + ss[2].value + ss[4].value;
						}
					}
				}
			}
		}

		ans.writeln;
	}
}

struct S{
	int i, j;
	int value;
}