Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $$$n$$$ flowers and so it looks like a pipe with $$$n$$$ holes. Arkady can only use the water that flows from the first hole.Arkady can block some of the holes, and then pour $$$A$$$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $$$s_1, s_2, \ldots, s_n$$$. In other words, if the sum of sizes of non-blocked holes is $$$S$$$, and the $$$i$$$-th hole is not blocked, $$$\frac{s_i \cdot A}{S}$$$ liters of water will flow out of it.What is the minimum number of holes Arkady should block to make at least $$$B$$$ liters of water flow out of the first hole?

The first line contains three integers $$$n$$$, $$$A$$$, $$$B$$$ ($$$1 \le n \le 100\,000$$$, $$$1 \le B \le A \le 10^4$$$) — the number of holes, the volume of water Arkady will pour into the system, and the volume he wants to get out of the first hole. The second line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 10^4$$$) — the sizes of the holes.

Print a single integer — the number of holes Arkady should block.

NoteIn the first example Arkady should block at least one hole. After that, $$$\frac{10 \cdot 2}{6} \approx 3.333$$$ liters of water will flow out of the first hole, and that suits Arkady.In the second example even without blocking any hole, $$$\frac{80 \cdot 3}{10} = 24$$$ liters will flow out of the first hole, that is not less than $$$20$$$.In the third example Arkady has to block all holes except the first to make all water flow out of the first hole.

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;

void main() {
	auto nab = readln.chomp.split.map!(to!int);
	int n = nab[0];
	long a = nab[1];
	long b = nab[2];
	long[] s = readln.chomp.split.map!(to!long).array;
	long S = s.sum;
	long[] t = std.algorithm.sort!"a > b"(s[1..$]).array;
	long f = s[0] * a;
	int ans = n - 1;
	foreach (i, v; t) {
		debug stderr.writefln("[%d] %d %d", i, v, S);
		if (f >= b * S) {
			ans = cast(int) i;
			break;
		}
		S -= v;
	}
	ans.writeln;
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n, a, b; readV(n, a, b);
  int[] s; readA(n, s);

  int t = s.sum;

  auto s2 = s[1..$];
  s2.sort!"a > b";

  auto t2 = 0;
  foreach (i; 0..n) {
    if (a.to!long*s[0] >= b.to!long*(t-t2)) {
      writeln(i);
      return;
    }
    t2 += s2[i];
  }
}

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;

void main() {
	auto nab = readln.chomp.split.map!(to!int);
	int n = nab[0];
	int a = nab[1];
	int b = nab[2];
	int[] s = readln.chomp.split.map!(to!int).array;
	int S = s.sum;
	int[] t = std.algorithm.sort!"a > b"(s[1..$]).array;
	int f = s[0] * a;
	int ans = n - 1;
	foreach (i, v; t) {
		if (f >= b * S) {
			ans = cast(int) i;
			break;
		}
		S -= v;
	}
	ans.writeln;
}

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;

void main() {
	auto nab = readln.chomp.split.map!(to!int);
	int n = nab[0];
	int a = nab[1];
	int b = nab[2];
	int[] s = readln.chomp.split.map!(to!int).array;
	int S = s.sum;
	int f = s[0] * a;
	int ans = n - 1;
	foreach (i, v; s[1..$]) {
		if (f >= b * S) {
			ans = cast(int) i;
			break;
		}
		S -= v;
	}
	ans.writeln;
}


Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell.Help Vasya! Calculate the maximum total weight of mushrooms he can collect.

The first line contains the number n (1 ≤ n ≤ 3·105) — the length of the glade. The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the growth rate of mushrooms in the first row of the glade. The third line contains n numbers b1, b2, ..., bn (1 ≤ bi ≤ 106) is the growth rate of mushrooms in the second row of the glade.

Output one number — the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once.

NoteIn the first test case, the optimal route is as follows:    Thus, the collected weight of mushrooms will be 0·1 + 1·2 + 2·3 + 3·4 + 4·5 + 5·6 = 70.In the second test case, the optimal route is as follows:    Thus, the collected weight of mushrooms will be 0·1 + 1·10 + 2·100 + 3·1000 + 4·10000 + 5·100000 = 543210.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = 2.iota.map!(_ => readln.split.map!(to!long).array).array;
    auto B = new long[][](2, N+1);

    foreach (i; 0..2)
        foreach (j; 0..N)
            B[i][j+1] = B[i][j] + A[i][j];

    long ans = 0;
    long tmp = 0;
    long a = 0;
    long b = 0;
    foreach (i; 0..N) a += i * A[0][i];
    foreach (i; 0..N) a += (N+N-i-1) * A[1][i];

    foreach (i; 1..N) b += (i + 1) * A[1][i];
    foreach (i; 1..N) b += (N+N-i) * A[0][i];

    foreach (i; 0..N) {
        long t = i*2;
        if (i % 2 == 0) {
            ans = max(ans, tmp + a);
            tmp += t * A[0][i];
            tmp += (t + 1) * A[1][i];
            if (i < N-2) {
                a -= t * A[0][i];
                a -= (t+1) * A[0][i+1];
                a += (B[0][N] - B[0][i+2]) * 2;
                a -= (2 * N - 1) * A[1][i];
                a -= (2 * N - 2) * A[1][i+1];
                a += (B[1][N] - B[1][i+2]) * 2;
            }
        } else {
            ans = max(ans, tmp + b);
            tmp += t * A[1][i];
            tmp += (t + 1) * A[0][i];
            if (i < N-2) {
                b -= t * A[1][i];
                b -= (t+1) * A[1][i+1];
                b += (B[1][N] - B[1][i+2]) * 2;
                b -= (2 * N - 1) * A[0][i];
                b -= (2 * N - 2) * A[0][i+1];
                b += (B[0][N] - B[0][i+2]) * 2;
            }
        }
        if (i == N-1) ans = max(ans, tmp);
    }

    ans.writeln;
}

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

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

    int[][] rws;
    foreach (_; 0 .. 2) rws ~= readln.chomp.split.map!(to!int).array;

    debug { rws.writeln; }

    auto mxsum = new long[][] (2, n+1);
    mxsum[0][$-1] = mxsum[1][$-1] = 0;
    auto dp = new long[][] (2, n+1);
    dp[0][$-1] = dp[1][$-1] = 0;
    auto totsum = 0L, updown = 0L, downup = 0L;
    foreach_reverse (i; 0 .. n) {
        updown += totsum + cast(long)(2*(n-i) - 1) * rws[1][i];
        downup += totsum + cast(long)(2*(n-i) - 1) * rws[0][i];

        dp[0][i] = max(updown, cast(long)rws[1][i] + dp[1][i+1] + 2*totsum);
        dp[1][i] = max(downup, cast(long)rws[0][i] + dp[0][i+1] + 2*totsum);

        totsum += rws[0][i] + rws[1][i];
        debug { writeln(dp[0][i], ' ', dp[1][i]); }
    }

    dp[0][0].writeln;
}

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

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

    int[][] rws;
    foreach (_; 0 .. 2) rws ~= readln.chomp.split.map!(to!int).array;

    debug { rws.writeln; }

    auto dp = new long[][] (2, n+1);
    dp[0][$-1] = dp[1][$-1] = 0;
    auto totsum = 0L, updown = 0L, downup = 0L;
    foreach_reverse (i; 0 .. n) {
        updown += totsum + cast(long)(2*(n-i) - 1) * rws[1][i];
        downup += totsum + cast(long)(2*(n-i) - 1) * rws[0][i];

        dp[0][i] = max(updown, cast(long)rws[1][i] + dp[1][i+1] + 2*totsum);
        dp[1][i] = max(downup, cast(long)rws[0][i] + dp[0][i+1] + 2*totsum);

        totsum += rws[0][i] + rws[1][i];

        debug { writeln(dp[0][i], ' ', dp[1][i]); }
    }

    dp[0][0].writeln;
}

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

  int w; rd(w);
  auto a=new long[][](2, w);
  a[0]=readln.split.to!(long[]);
  a[1]=readln.split.to!(long[]);

  auto s=new long[](w+1);
  auto sr=new long[][](2, w+1);
  auto sl=new long[][](2, w+1);
  foreach(j; 0..w){
    s[j+1]=s[j];
    if(j%2==0) s[j+1]+=a[0][j]*(j*2)+a[1][j]*(j*2+1);
    else s[j+1]+=a[1][j]*(j*2)+a[0][j]*(j*2+1);
  }
  auto sub=new long[][](2, w+1);
  foreach(i; 0..2)foreach(j; 0..w) sub[i][j+1]=sub[i][j]+a[i][j];
  foreach(i; 0..2)for(int j=w-1; j>=0; j--){
    sr[i][j]=sr[i][j+1];
    sr[i][j]-=(sub[i][w]-sub[i][j+1]);
    sr[i][j]+=a[i][j]*(j*2); // ちょっとサボる

    sl[i][j]=sl[i][j+1];
    sl[i][j]-=(sub[i][w]-sub[i][j+1]);
    sl[i][j]+=a[i][j]*(w*2-1);
  }
  long mx=0;
  for(int j=0; j<=w; j++){
    if(j%2==0){
      mx=max(mx, s[j]+sr[0][j]+sl[1][j]);
      // writeln(s[j]+sr[0][j]+sl[1][j]);
    }else{
      mx=max(mx, s[j]+sr[1][j]+sl[0][j]);
      // writeln(s[j]+sr[1][j]+sl[0][j]);
    }
  }
  writeln(mx);
}

/*
  s[j]:=j列目までジグザグ (1-indexed)
    j=0, 1, ..., w
    s[0]=0
  sr[i][j]:=i行をj列から右端まで (0-indexed)
  sl[i][j]:=i行を右端からj列まで (0-indexed)

  sl[*][w]=sr[*][w]=0

  j列までジグザグ j=0, 1, ..., w
  jが偶数
    0行目をj+1列目から右端まで、1行目を右端からj+1列目まで
    s[j]+sr[0][j]+sl[1][j]
  jが奇数
    s[j]+sr[1][j]+sl[0][j]

*/

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

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

  int w; rd(w);
  auto a=new long[][](2, w);
  a[0]=readln.split.to!(long[]);
  a[1]=readln.split.to!(long[]);

  auto s=new long[](w+1);
  auto sr=new long[][](2, w+1);
  auto sl=new long[][](2, w+1);
  foreach(j; 0..w){
    s[j+1]=s[j];
    if(j%2==0) s[j+1]+=a[0][j]*(j*2)+a[1][j]*(j*2+1);
    else s[j+1]+=a[1][j]*(j*2)+a[0][j]*(j*2+1);
  }
  auto sub=new long[][](2, w+1);
  foreach(i; 0..2)foreach(j; 0..w) sub[i][j+1]=sub[i][j]+a[i][j];
  foreach(i; 0..2)for(int j=w-1; j>=0; j--){
    sr[i][j]=sr[i][j+1];
    sr[i][j]-=(sub[i][w]-sub[i][j+1]);
    sr[i][j]+=a[i][j]*(j*2); // ちょっとサボる

    sl[i][j]=sl[i][j+1];
    sl[i][j]-=(sub[i][w]-sub[i][j+1]);
    sl[i][j]+=a[i][j]*(w*2-1);
  }
  long mx=0;
  for(int j=0; j<=w; j++){
    if(j%2==0) mx=max(mx, s[j]+sr[0][j]+sl[1][j]);
    else mx=max(mx, s[j]+sr[1][j]+sl[0][j]);
  }
  writeln(mx);
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


You are given a rectangular table 3 × n. Each cell contains an integer. You can move from one cell to another if they share a side.Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximum possible.

The first line contains an integer n (1 ≤ n ≤ 105)  — the number of columns in the table. Next three lines contain n integers each  — the description of the table. The j-th number in the i-th line corresponds to the cell aij ( - 109 ≤ aij ≤ 109) of the table.

Output the maximum sum of numbers on a path from the upper left cell to the bottom right cell of the table, that doesn't visit any of the cells twice.

NoteThe path for the first example:  The path for the second example:

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

long saiki(int idx, int pos, int n, long[][] dp, int[][] a)
{
    if (dp[idx][pos] != -1)
    {
        return dp[idx][pos];
    }
    if (idx == n - 1)
    {
        long val = 0;
        for (int i = 2; i >= 0; -- i)
        {
            val += a[i][n - 1];
            dp[idx][i] = val;
        }
        return dp[idx][pos];
    }
    auto ndp = new long[][](2, 3);
    auto sum = new long[2];
    foreach (i; 0 .. 2)
    {
        sum[i] = 0;
        foreach (j; 0 .. 3)
        {
            sum[i] += a[j][idx + i];
            if (idx + i + 1 < n)
            {
                ndp[i][j] = saiki(idx + i + 1, j, n, dp, a);
            }
        }
    }
    auto res = long.min;
    if (pos == 1)
    {
        res = max(res, ndp[0][pos] + a[pos][idx]);
        res = max(res, ndp[0][0] + a[pos][idx] + a[0][idx]);
        res = max(res, ndp[0][2] + a[pos][idx] + a[2][idx]);
    }
    else
    {
        res = max(res, ndp[0][pos] + a[pos][idx]);
        res = max(res, ndp[0][1] + a[pos][idx] + a[1][idx]);
        if (pos == 0) res = max(res, ndp[0][2] + sum[0]);
        else res = max(res, ndp[0][0] + sum[0]);
        if (idx + 2 < n)
        {
            if (pos == 0) res = max(res, ndp[1][2] + sum[0] + sum[1]);
            else res = max(res, ndp[1][0] + sum[0] + sum[1]);
        }
        if (idx == n - 2 && pos == 0)
        {
            res = max(res, sum[0] + sum[1]);
        }
    }
    dp[idx][pos] = res;
    return res;
}

void solve(int[][] a, int n)
{
    auto dp = new long[][](n, 3);
    foreach (i; 0 .. n)
    {
        fill(dp[i], -1);
    }
    auto ans = saiki(0, 0, n, dp, a);
    writeln(ans);
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new int[][](3, n);
        foreach (i; 0 .. 3)
        {
            foreach (j; 0 .. n)
            {
                readf(" %d", &a[i][j]);
            }
            readln;
        }
        solve(a, n);
    }
    return 0;
}

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

long saiki(int idx, int pos, int n, long[][] dp, int[][] a)
{
    if (dp[idx][pos] != -1)
    {
        return dp[idx][pos];
    }
    if (idx == n - 1)
    {
        long val = 0;
        for (int i = 2; i >= 0; -- i)
        {
            val += a[i][n - 1];
            dp[idx][i] = val;
        }
        return dp[idx][pos];
    }
    long[3][2] ndp;
    long[2] sum;
    foreach (i; 0 .. 2)
    {
        sum[i] = 0;
        foreach (j; 0 .. 3)
        {
            sum[i] += a[j][idx + i];
            if (idx + i + 1 < n)
            {
                ndp[i][j] = saiki(idx + i + 1, j, n, dp, a);
            }
        }
    }
    auto res = long.min;
    if (pos == 1)
    {
        res = max(res, ndp[0][pos] + a[pos][idx]);
        res = max(res, ndp[0][0] + a[pos][idx] + a[0][idx]);
        res = max(res, ndp[0][2] + a[pos][idx] + a[2][idx]);
    }
    else
    {
        res = max(res, ndp[0][pos] + a[pos][idx]);
        res = max(res, ndp[0][1] + a[pos][idx] + a[1][idx]);
        res = max(res, ndp[0][2 - pos] + sum[0]);
        if (idx + 2 < n)
        {
            if (pos == 0) res = max(res, ndp[1][2] + sum[0] + sum[1]);
            else res = max(res, ndp[1][0] + sum[0] + sum[1]);
        }
        if (idx == n - 2 && pos == 0)
        {
            res = max(res, sum[0] + sum[1]);
        }
    }
    dp[idx][pos] = res;
    return res;
}

void solve(int[][] a, int n)
{
    auto dp = new long[][](n, 3);
    foreach (i; 0 .. n)
    {
        fill(dp[i], -1);
    }
    auto ans = saiki(0, 0, n, dp, a);
    writeln(ans);
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new int[][](3, n);
        foreach (i; 0 .. 3)
        {
            foreach (j; 0 .. n)
            {
                readf(" %d", &a[i][j]);
            }
            readln;
        }
        solve(a, n);
    }
    return 0;
}


A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).For a positive integer $$$n$$$, we call a permutation $$$p$$$ of length $$$n$$$ good if the following condition holds for every pair $$$i$$$ and $$$j$$$ ($$$1 \le i \le j \le n$$$) —   $$$(p_i \text{ OR } p_{i+1} \text{ OR } \ldots \text{ OR } p_{j-1} \text{ OR } p_{j}) \ge j-i+1$$$, where $$$\text{OR}$$$ denotes the bitwise OR operation. In other words, a permutation $$$p$$$ is good if for every subarray of $$$p$$$, the $$$\text{OR}$$$ of all elements in it is not less than the number of elements in that subarray. Given a positive integer $$$n$$$, output any good permutation of length $$$n$$$. We can show that for the given constraints such a permutation always exists.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of every test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).

For every test, output any good permutation of length $$$n$$$ on a separate line.

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

void main () {
	foreach (test; 0..readln.strip.to !(int))
		readln.strip.to !(int).iota.map !(q{a + 1}).writefln !("%(%s %)");
}

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string read_string() {
                while (tokens.empty) {
                tokens = readln.split;
        }
        auto token = tokens.front;
                tokens.popFront;
                return token;
        }

        int read_int() {
                return read_string.to!int;
        }

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                for (int i = 1; i <= n; i++) {
                        write(i, " ");
                }
                writeln();
        }
}
/*  CODED BY:-
 ___________________________________
|                       ___         |
|  /\   /\  \ /  |  |  |___   |__|  |
| /~~\ /~~\  |   |__|   ___|  |  |  |
|___________________________________|

*/

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;

		foreach (i; 0..n)
		{
			ans[ti] ~= i+1;
		}
	}

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


You are given a grid with $$$n$$$ rows and $$$m$$$ columns. Rows and columns are numbered from $$$1$$$ to $$$n$$$, and from $$$1$$$ to $$$m$$$. The intersection of the $$$a$$$-th row and $$$b$$$-th column is denoted by $$$(a, b)$$$. Initially, you are standing in the top left corner $$$(1, 1)$$$. Your goal is to reach the bottom right corner $$$(n, m)$$$.You can move in four directions from $$$(a, b)$$$: up to $$$(a-1, b)$$$, down to $$$(a+1, b)$$$, left to $$$(a, b-1)$$$ or right to $$$(a, b+1)$$$.You cannot move in the same direction in two consecutive moves, and you cannot leave the grid. What is the minimum number of moves to reach $$$(n, m)$$$?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of the test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — the size of the grid.

For each test case, print a single integer: $$$-1$$$ if it is impossible to reach $$$(n, m)$$$ under the given conditions, otherwise the minimum number of moves.

NoteTest case $$$1$$$: $$$n=1$$$, $$$m=1$$$, and initially you are standing in $$$(1, 1)$$$ so $$$0$$$ move is required to reach $$$(n, m) = (1, 1)$$$.Test case $$$2$$$: you should go down to reach $$$(2, 1)$$$.Test case $$$3$$$: it is impossible to reach $$$(1, 3)$$$ without moving right two consecutive times, or without leaving the grid.Test case $$$4$$$: an optimal moving sequence could be: $$$(1, 1) \to (1, 2) \to (2, 2) \to (2, 1) \to (3, 1) \to (3, 2) \to (4, 2)$$$. It can be proved that this is the optimal solution. So the answer is $$$6$$$.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

//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 n = RD;
		auto m = RD;

		if (n > m)
			swap(n, m);

		if (n == 1)
			ans[ti] = m == 1 ? 0 : m == 2 ? 1 : -1;
		else
		{
			m -= n;
			ans[ti] = (n-1) * 2;
			ans[ti] += (m / 2) * 4 + (m % 2);
		}
	}

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


Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.Lyft has become so popular so that it is now used by all $$$m$$$ taxi drivers in the city, who every day transport the rest of the city residents — $$$n$$$ riders.Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $$$i$$$ the number $$$a_{i}$$$ — the number of riders that would call the $$$i$$$-th taxi driver when all drivers and riders are at their home?The taxi driver can neither transport himself nor other taxi drivers.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^5$$$) — number of riders and taxi drivers. The second line contains $$$n + m$$$ integers $$$x_1, x_2, \ldots, x_{n+m}$$$ ($$$1 \le x_1 < x_2 < \ldots < x_{n+m} \le 10^9$$$), where $$$x_i$$$ is the coordinate where the $$$i$$$-th resident lives.  The third line contains $$$n + m$$$ integers $$$t_1, t_2, \ldots, t_{n+m}$$$ ($$$0 \le t_i \le 1$$$). If $$$t_i = 1$$$, then the $$$i$$$-th resident is a taxi driver, otherwise $$$t_i = 0$$$. It is guaranteed that the number of $$$i$$$ such that $$$t_i = 1$$$ is equal to $$$m$$$.

Print $$$m$$$ integers $$$a_1, a_2, \ldots, a_{m}$$$, where $$$a_i$$$ is the answer for the $$$i$$$-th taxi driver. The taxi driver has the number $$$i$$$ if among all the taxi drivers he lives in the $$$i$$$-th smallest coordinate (see examples for better understanding).

NoteIn the first example, we have only one taxi driver, which means an order from any of $$$n$$$ riders will go to him.In the second example, the first taxi driver lives at the point with the coordinate $$$2$$$, and the second one lives at the point with the coordinate $$$6$$$. Obviously, the nearest taxi driver to the rider who lives on the $$$3$$$ coordinate is the first one, and to the rider who lives on the coordinate $$$5$$$ is the second one. The rider who lives on the $$$4$$$ coordinate has the same distance to the first and the second taxi drivers, but since the first taxi driver has a smaller coordinate, the call from this rider will go to the first taxi driver.In the third example, we have one rider and the taxi driver nearest to him is the fourth one.

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

void main() {
    int n, m;
    scan(n, m);
    auto x = readln.split.to!(int[]);
    auto t = readln.split.to!(int[]);

    auto r = iota(n + m).filter!(i => !t[i]).map!(i => x[i]).array;
    auto d = iota(n + m).filter!(i => t[i]).map!(i => x[i]).array;

    auto ans = new int[](m);
    int last = n;

    foreach (i ; 0 .. m - 1) {
        int cnt;

        while (!r.empty && (r.front - d[i]) <= (d[i+1] - r.front)) {
            r.popFront();
            cnt++;
        }

        ans[i] = cnt;
        last -= cnt;
    }

    ans[m-1] = last;

    writefln("%(%s %)", ans);
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

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

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


Your task is to maintain a queue consisting of lowercase English letters as follows:   "push $$$c$$$": insert a letter $$$c$$$ at the back of the queue;  "pop": delete a letter from the front of the queue. Initially, the queue is empty. After each operation, you are asked to count the number of distinct palindromic substrings in the string that are obtained by concatenating the letters from the front to the back of the queue.Especially, the number of distinct palindromic substrings of the empty string is $$$0$$$. A string $$$s[1..n]$$$ of length $$$n$$$ is palindromic if $$$s[i] = s[n-i+1]$$$ for every $$$1 \leq i \leq n$$$. The string $$$s[l..r]$$$ is a substring of string $$$s[1..n]$$$ for every $$$1 \leq l \leq r \leq n$$$. Two strings $$$s[1..n]$$$ and $$$t[1..m]$$$ are distinct, if at least one of the following holds.   $$$n \neq m$$$;  $$$s[i] \neq t[i]$$$ for some $$$1 \leq i \leq \min\{n,m\}$$$.

The first line is an integer $$$q$$$ ($$$1 \leq q \leq 10^6$$$), indicating the number of operations. Then $$$q$$$ lines follow. Each of the following lines contains one of the operations as follows.    "push $$$c$$$": insert a letter $$$c$$$ at the back of the queue, where $$$c$$$ is a lowercase English letter;  "pop": delete a letter from the front of the queue.  It is guaranteed that no "pop" operation will be performed when the queue is empty.

After each operation, print the number of distinct palindromic substrings in the string presented in the queue.

12
push a
pop
push a
push a
push b
push b
push a
push a
pop
pop
pop
push b

NoteLet $$$s_k$$$ be the string presented in the queue after the $$$k$$$-th operation, and let $$$c_k$$$ be the number of distinct palindromic substrings of $$$s_k$$$. The following table shows the details of the example. $$$k$$$$$$s_k$$$$$$c_k$$$$$$1$$$$$$a$$$$$$1$$$$$$2$$$$$$\textsf{empty}$$$$$$0$$$$$$3$$$$$$a$$$$$$1$$$$$$4$$$$$$aa$$$$$$2$$$$$$5$$$$$$aab$$$$$$3$$$$$$6$$$$$$aabb$$$$$$4$$$$$$7$$$$$$aabba$$$$$$5$$$$$$8$$$$$$aabbaa$$$$$$6$$$$$$9$$$$$$abbaa$$$$$$5$$$$$$10$$$$$$bbaa$$$$$$4$$$$$$11$$$$$$baa$$$$$$3$$$$$$12$$$$$$baab$$$$$$4$$$ It is worth pointing out that   After the $$$2$$$-nd operation, the string is empty and thus has no substrings. So the answer is $$$0$$$;  After the $$$8$$$-th operation, the string is "$$$aabbaa$$$". The $$$6$$$ distinct palindromic substrings are "$$$a$$$", "$$$aa$$$", "$$$aabbaa$$$", "$$$abba$$$", "$$$b$$$", and "$$$bb$$$".

import std;
immutable int N=1000005;

struct node {
	int fail,len,pos,tot;
    int[26] to;
}

struct S {
    node[] t;
    this(int k) { this.t = new node[k]; }
}
int cnt=1;
int cur=1;
int n=0;
int[N] a;
int l=1;
int ans=0;
int[][N] d;

void extend(int x, ref S z) {
	while (a[n-z.t[cur].len-1]!=a[n]) {
		cur=z.t[cur].fail;
	}
	if (!z.t[cur].to[x]) {
		int u=z.t[cur].fail,v=++cnt;
		while (a[n-z.t[u].len-1]!=a[n]) {
			u=z.t[u].fail;
		}
		z.t[v].fail=z.t[u].to[x];
		z.t[cur].to[x]=v;
		z.t[v].len=z.t[cur].len+2;
	}
	cur=z.t[cur].to[x];
}
void cover(int x,int y, ref S z) {
	if (x<=1) {
		return;
	}
	if (!z.t[x].pos) {
		ans+=!z.t[x].pos;
		z.t[z.t[x].fail].tot++;
	}
	if (z.t[x].pos<y) {
		z.t[x].pos=y;
		d[y-z.t[x].len+1] ~= x;
	}
}
void push(int x, ref S z) {
	a[++n]=x;
	extend(x, z);
	while (z.t[cur].len>n-l+1) {
		cur=z.t[cur].fail;
	}
	cover(cur,n,z);
}

void pop(ref S z) {
	foreach (x;d[l]) {
		if (z.t[x].pos-z.t[x].len+1!=l||z.t[x].tot) {
			continue;
		}
		cover(z.t[x].fail,z.t[x].pos,z);
		z.t[x].pos=0;
        ans--;
        z.t[z.t[x].fail].tot--;
	}
	l++;
}

void main() {
    auto z = S(N);
	a[0]=-1;
	z.t[0].len=0;
    z.t[1].len=-1;
	z.t[0].fail=1;
    z.t[1].fail=0;
	int Q;
	readf!" %d "(Q);
	while (Q--) {
		auto s = readln.strip.split();
		if (s[0]=="push") {
			push(s[1][0]-'a',z);
		} else {
			pop(z);
		}
        writeln(ans);
	}

}

import std;
immutable int N=1000000;

struct node {
	int fail,len,pos,tot;
    int[26] to;
}

struct S {
    node[] t;
    this(int k) { this.t = new node[k]; }
}
int cnt=1;
int cur=1;
int n=0;
int[N] a;
int l=1;
int ans=0;
int[][N] d;

void extend(int x, ref S z) {
	while (a[n-z.t[cur].len-1]!=a[n]) {
		cur=z.t[cur].fail;
	}
	if (!z.t[cur].to[x]) {
		int u=z.t[cur].fail,v=++cnt;
		while (a[n-z.t[u].len-1]!=a[n]) {
			u=z.t[u].fail;
		}
		z.t[v].fail=z.t[u].to[x];
		z.t[cur].to[x]=v;
		z.t[v].len=z.t[cur].len+2;
	}
	cur=z.t[cur].to[x];
}
void cover(int x,int y, ref S z) {
	if (x<=1) {
		return;
	}
	if (!z.t[x].pos) {
		ans+=!z.t[x].pos;
		z.t[z.t[x].fail].tot++;
	}
	if (z.t[x].pos<y) {
		z.t[x].pos=y;
		d[y-z.t[x].len+1] ~= x;
	}
}
void push(int x, ref S z) {
	a[++n]=x;
	extend(x, z);
	while (z.t[cur].len>n-l+1) {
		cur=z.t[cur].fail;
	}
	cover(cur,n,z);
}

void pop(ref S z) {
	foreach (x;d[l]) {
		if (z.t[x].pos-z.t[x].len+1!=l||z.t[x].tot) {
			continue;
		}
		cover(z.t[x].fail,z.t[x].pos,z);
		z.t[x].pos=0;
        ans--;
        z.t[z.t[x].fail].tot--;
	}
	l++;
}

void main() {
    auto z = S(N);
	a[0]=-1;
	z.t[0].len=0;
    z.t[1].len=-1;
	z.t[0].fail=1;
    z.t[1].fail=0;
	int Q;
	readf!" %d "(Q);
	while (Q--) {
		auto s = readln.strip.split();
		if (s[0]=="push") {
			push(s[1][0]-'a',z);
		} else {
			pop(z);
		}
        writeln(ans);
	}

}


You are given a matrix of size $$$n \times n$$$ filled with lowercase English letters. You can change no more than $$$k$$$ letters in this matrix.Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is $$$2n - 1$$$.Find the lexicographically smallest string that can be associated with a path after changing letters in at most $$$k$$$ cells of the matrix.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$, if the first different letter in $$$a$$$ and $$$b$$$ is smaller in $$$a$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2000$$$, $$$0 \le k \le n^2$$$) — the size of the matrix and the number of letters you can change. Each of the next $$$n$$$ lines contains a string of $$$n$$$ lowercase English letters denoting one row of the matrix.

Output the lexicographically smallest string that can be associated with some valid path after changing no more than $$$k$$$ letters in the matrix.

7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz

NoteIn the first sample test case it is possible to change letters 'b' in cells $$$(2, 1)$$$ and $$$(3, 1)$$$ to 'a', then the minimum path contains cells $$$(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)$$$. The first coordinate corresponds to the row and the second coordinate corresponds to the column.

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;

void lower(T)(ref T dest, T source)
{
  dest = min(dest, source);
}
void increase(T)(ref T dest, T source)
{
  dest = max(dest, source);
}

void main(string[] args)
{
  inputFile = stdin;
  auto n = next!int;
  auto k = next!int;
  auto imat = next!string(n);
  auto mat = new char[][](n, n);
  foreach(i; 0 .. n)
    foreach(j; 0 .. n)
      {
	mat[i][j] = imat[i][j];
      }
  auto minuse = new int[][](n, n);
  minuse[0][0] = mat[0][0] != 'a';
  foreach(s; 1 .. 2 * n - 1)
    {
      int i;
      int j;
      i = min(s, n - 1);
      j = s - i;
      for(; i >= 0 && j < n; i--, j++)
	{
	  minuse[i][j] = int.max;
	  if (i - 1 >= 0) lower(minuse[i][j], minuse[i - 1][j] + (mat[i][j] != 'a'));
	  if (j - 1 >= 0) lower(minuse[i][j], minuse[i][j - 1] + (mat[i][j] != 'a'));
	}
    }
  foreach(i; 0 .. n)
    foreach(j; 0 .. n)
      {
	if (minuse[i][j] <= k)
	  mat[i][j] = 'a';
      }
  debug foreach(i; 0 .. n)
    {
      writeln(mat[i]);
    }
  auto used = new bool[][](n, n);
  used[0][0] = true;
  write(mat[0][0]);
  foreach(s; 1 .. 2 * n - 1)
    {
      int i;
      int j;
      i = min(s, n - 1);
      j = s - i;
      char minchar = char.max;
      for(; i >= 0 && j < n; i--, j++)
	{
	  if (i - 1 >= 0 && used[i - 1][j] ||
	      j - 1 >= 0 && used[i][j - 1])
	    minchar = min(minchar, mat[i][j]);
	}
      write(minchar);
      i = min(s, n - 1);
      j = s - i;
      for(; i >= 0 && j < n; i--, j++)
	{
	  if (i - 1 >= 0 && used[i - 1][j] ||
	      j - 1 >= 0 && used[i][j - 1])
	    if (mat[i][j] == minchar)
	      used[i][j] = true;
	}
    }
  writeln;
}
 ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  string toString()
  {
    return to!string(rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;

void lower(T)(ref T dest, T source)
{
  dest = min(dest, source);
}
void increase(T)(ref T dest, T source)
{
  dest = max(dest, source);
}

void main(string[] args)
{
  inputFile = stdin;
  auto n = next!int;
  auto k = next!int;
  auto imat = next!string(n);
  auto mat = new char[][](n, n);
  foreach(i; 0 .. n)
    foreach(j; 0 .. n)
      {
	mat[i][j] = imat[i][j];
      }
  auto visited = new bool[][](n, n);
  auto adjlist(Tuple!(int, int) i)
  {
    auto adjs = new Tuple!(int, int)[](0);
    if (i[0] + 1 < n) adjs ~= tuple(i[0] + 1, i[1]);
    if (i[1] + 1 < n) adjs ~= tuple(i[0], i[1] + 1);
    return adjs;
  }
  auto radjlist(Tuple!(int, int) i)
  {
    auto adjs = new Tuple!(int, int)[](0);
    if (i[0] - 1 >= 0) adjs ~= tuple(i[0] - 1, i[1]);
    if (i[1] - 1 >= 0) adjs ~= tuple(i[0], i[1] - 1);
    return adjs;
  }
  auto toplace = new int[][](n, n);
  toplace[0][0] = k;
  auto q = DList!(Tuple!(int, int))();
  q.insertBack(tuple(0, 0));
  while(!q.empty)
    {
      auto i = q.front;
      q.removeFront;
      if (toplace[i[0]][i[1]] == 0) continue;
      foreach(adj; adjlist(i))
	{
	  auto togive = toplace[i[0]][i[1]] - (mat[i[0]][i[1]] != 'a');
	  increase(toplace[adj[0]][adj[1]], togive);
	  if (!visited[adj[0]][adj[1]])
	    {
	      visited[adj[0]][adj[1]] = true;
	      q.insertBack(adj);
	    }
	}
    }
  debug foreach(i; 0 .. n)
    {
      writeln(toplace[i]);
    }
  foreach(i; 0 .. n)
    foreach(j; 0 .. n)
      {
	if (toplace[i][j] > 0)
	  mat[i][j] = 'a';
      }
  debug foreach(i; 0 .. n)
    {
      writeln(mat[i]);
    }
  auto used = new bool[][](n, n);
  used[0][0] = true;
  write(mat[0][0]);
  foreach(s; 1 .. 2 * n - 1)
    {
      int i;
      int j;
      i = min(s, n - 1);
      j = s - i;
      char minchar = char.max;
      for(; i >= 0 && j < n; i--, j++)
	{
	  if (i - 1 >= 0 && used[i - 1][j] ||
	      j - 1 >= 0 && used[i][j - 1])
	    minchar = min(minchar, mat[i][j]);
	}
      write(minchar);
      i = min(s, n - 1);
      j = s - i;
      for(; i >= 0 && j < n; i--, j++)
	{
	  if (mat[i][j] == minchar)
	    used[i][j] = true;
	}
    }
  writeln;
}
 ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  string toString()
  {
    return to!string(rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.

For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.

NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example:   $$$2, 1, 2, 1, 2, 1$$$  $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto nk = readln.split.to!(int[]);
        auto N = nk[0];
        auto K = nk[1];
        auto as = readln.split.to!(int[]);
        auto ns = new bool[](100);
        foreach (a; as) ns[a-1] = true;
        int c;
        foreach (n; ns) if (n) ++c;
        if (c > K) {
            writeln("-1");
            continue;
        }
        int[] ii;
        foreach (i, n; ns) if (n) ii ~= i.to!int+1;
        while (ii.length < K) ii ~= ii[0];
        int[] ms;
        size_t i;
        foreach (a; as) {
            while (a != ii[i]) {
                ms ~= ii[i++];
                i %= ii.length;
            }
            ms ~= a;
            ++i;
            i %= ii.length;
        }
        writeln(ms.length);
        writeln(ms.to!(string[]).join(" "));
    }
}

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

void main ()
{
	readln;
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		bool [int] vis;
		foreach (ref c; a)
		{
			vis[c] = true;
		}
		if (vis.length > k)
		{
			writeln (-1);
		}
		else
		{
			writeln (n * k);
			writefln !("%(%s %)")
			    (vis.byKey.cycle.take (k).repeat (n).joiner);
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto a = RDA!int;

		bool[int] set;
		foreach (i; 0..n)
		{
			set[a[i]] = true;
		}
		if (set.keys.length > k) continue;

		auto len = (10^^4) / k;
		len *= k;
		ans[ti].length = len;
		auto b = set.keys.dup;
		while (b.length < k)
			b ~= 1;
		foreach (i; 0..len)
		{
			auto pos = i % k;
			ans[ti][i] = b[pos];
		}
	}

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

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

void main ()
{
	readln;
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		bool [int] vis;
		foreach (ref c; a)
		{
			vis[c] = true;
		}
		if (vis.length > k)
		{
			writeln (-1);
		}
		else
		{
			writeln (n * vis.length);
			writefln !("%(%s %)") (vis.byKey.repeat (n).joiner);
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto a = RDA!int;

		bool[int] set;
		foreach (i; 0..n)
		{
			set[a[i]] = true;
		}
		if (set.keys.length > k) continue;

		auto len = (10^^4) / k;
		ans[ti].length = len;
		auto b = set.keys.dup;
		while (b.length < k)
			b ~= 1;
		foreach (i; 0..len)
		{
			auto pos = i % k;
			ans[ti][i] = b[pos];
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto a = RDA!int;

		bool[int] set;
		foreach (i; 0..n)
		{
			set[a[i]] = true;
		}
		if (set.keys.length > k) continue;

		auto len = (10^^4) / k;
		ans[ti].length = len;
		foreach (i; 0..len)
		{
			auto pos = i % k;
			ans[ti][i] = a[pos];
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto a = RDA!int;

		bool[int] set;
		foreach (i; 0..n)
		{
			set[a[i]] = true;
		}
		if (set.keys.length > k) continue;

		auto len = (10^^4) / k;
		ans[ti].length = len;
		auto keys = set.keys;
		foreach (i; 0..len)
		{
			auto pos = i % keys.length;
			ans[ti][i] = keys[pos];
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto a = RDA!int;

		ans[ti] = a.dup;
		int i = k;
		while (i < ans[ti].length)
		{
			if (ans[ti][i] == ans[ti][i-k])
			{
				++i;
				continue;
			}

			bool ok;
			foreach (j; i-k..i)
			{
				if (ans[ti][j] == ans[ti][i])
				{
					ok = true;
					break;
				}
			}
			if (ok)
			{
				ans[ti] = ans[ti][0..i] ~ ans[ti][i-k] ~ ans[ti][i..$];
			}
			else
			{
				ans[ti].length = 0;
				break;
			}
			++i;
			debug writeln(ans[ti]);
		}
	}

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


You are given an integer $$$x$$$ of $$$n$$$ digits $$$a_1, a_2, \ldots, a_n$$$, which make up its decimal notation in order from left to right.Also, you are given a positive integer $$$k < n$$$.Let's call integer $$$b_1, b_2, \ldots, b_m$$$ beautiful if $$$b_i = b_{i+k}$$$ for each $$$i$$$, such that $$$1 \leq i \leq m - k$$$.You need to find the smallest beautiful integer $$$y$$$, such that $$$y \geq x$$$.

The first line of input contains two integers $$$n, k$$$ ($$$2 \leq n \leq 200\,000, 1 \leq k < n$$$): the number of digits in $$$x$$$ and $$$k$$$. The next line of input contains $$$n$$$ digits $$$a_1, a_2, \ldots, a_n$$$ ($$$a_1 \neq 0$$$, $$$0 \leq a_i \leq 9$$$): digits of $$$x$$$.

In the first line print one integer $$$m$$$: the number of digits in $$$y$$$. In the next line print $$$m$$$ digits $$$b_1, b_2, \ldots, b_m$$$ ($$$b_1 \neq 0$$$, $$$0 \leq b_i \leq 9$$$): digits of $$$y$$$.

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

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

    auto s = readln.chomp;

    dchar[] ans;
    foreach (i; 0 .. n) { ans ~= s[i % k]; }

    debug { ans.writeln; }

    foreach (i; k .. n) {
        if (ans[i] > s[i]) { break; }
        if (ans[i] < s[i]) {
            int start = k-1;
            while (s[start] == '9') { --start; }
            foreach (j; n.iota.drop(start).stride(k)) { ans[j] = s[start] + 1; }
            foreach (nxt; start + 1 .. k) {
                foreach (j; n.iota.drop(nxt).stride(k)) { ans[j] = '0'; }
            }
            break;
        }
    }

    ans.length.writeln;
    ans.writeln;
}

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 K = readInt();
      const A = readToken();

      auto b = new char[N];
      foreach (i; 0 .. N) {
        b[i] = A[i % K];
      }
      if (A > b) {
        b[K - 1] += 1;
        foreach_reverse (i; 0 .. K) {
          if (b[i] > '9') {
            b[i] -= 10;
            b[i - 1] += 1;
          }
        }
        foreach (i; K .. N) {
          b[i] = b[i % K];
        }
      }
      writeln(N);
      writeln(b);
    }
  } catch (EOFException e) {
  }
}

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

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

    auto s = readln.chomp;

    dchar[] ans;
    foreach (i; 0 .. n) { ans ~= s[i % k]; }

    debug { ans.writeln; }

    foreach (i; k .. n) {
        if (ans[i] > s[i]) { break; }
        if (ans[i] < s[i]) {
            int start = k-1;
            while (s[start] == '9') { --start; }
            foreach (j; n.iota.drop(start).stride(k)) { ans[j] = s[i]; }
            break;
        }
    }

    ans.length.writeln;
    ans.writeln;
}

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

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

    auto s = readln.chomp;

    dchar[] ans;
    foreach (i; 0 .. n) { ans ~= s[i % k]; }

    debug { ans.writeln; }

    foreach (i; k .. n) {
        if (ans[i] > s[i]) { break; }
        if (ans[i] < s[i]) {
            int start = k-1;
            while (s[start] == '9') { --start; }
            foreach (j; n.iota.drop(start).stride(k)) { ans[j] = s[start] + 1; }
            break;
        }
    }

    ans.length.writeln;
    ans.writeln;
}

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

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

    auto s = readln.chomp;

    dchar[] ans;
    foreach (i; 0 .. n) { ans ~= s[i % k]; }

    debug { ans.writeln; }

    foreach (i; k .. n) {
        if (ans[i] > s[i]) { break; }
        if (ans[i] < s[i]) {
            int start = k-1;
            while (s[start] == '9') { --start; }
            foreach (j; n.iota.drop(start).stride(k)) { ans[j] = s[i]; }
            break;
        }
    }

    ans.writeln;
}

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 K = readInt();
      const A = readToken();

      auto b = new char[N];
      foreach (i; 0 .. N) {
        b[i] = A[i % K];
      }
      if (A > b) {
        b[K - 1] += 1;
        foreach_reverse (i; 0 .. K) {
          if (b[i] > '9') {
            b[i] -= 10;
            b[i - 1] += 1;
          }
        }
        foreach (i; K .. N) {
          b[i] = b[i % K];
        }
      }
      writeln(b);
    }
  } catch (EOFException e) {
  }
}


Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.The building consists of n floors with stairs at the left and the right sides. Each floor has m rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with n rows and m + 2 columns, where the first and the last columns represent the stairs, and the m columns in the middle represent rooms.Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights.Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off.

The first line contains two integers n and m (1 ≤ n ≤ 15 and 1 ≤ m ≤ 100) — the number of floors and the number of rooms in each floor, respectively. The next n lines contains the building description. Each line contains a binary string of length m + 2 representing a floor (the left stairs, then m rooms, then the right stairs) where 0 indicates that the light is off and 1 indicates that the light is on. The floors are listed from top to bottom, so that the last line represents the ground floor. The first and last characters of each string represent the left and the right stairs, respectively, so they are always 0.

Print a single integer — the minimum total time needed to turn off all the lights.

NoteIn the first example, Sagheer will go to room 1 in the ground floor, then he will go to room 2 in the second floor using the left or right stairs.In the second example, he will go to the fourth room in the ground floor, use right stairs, go to the fourth room in the second floor, use right stairs again, then go to the second room in the last floor.In the third example, he will walk through the whole corridor alternating between the left and right stairs at each floor.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1] + 2;
    string[] A;
    bool ok = false;
    foreach (i; 0..N) {
        auto t = readln.chomp;
        if (!ok && t.map!(tt => tt == '0').all) continue;
        ok = true;
        A ~= t;
    }
    N = A.length.to!int;
    A.reverse();

    int[] L = new int[](N);
    int[] R = new int[](N);
    foreach (i; 0..N) {
        L[i] = M-1, R[i] = 0;
        foreach (j; 0..M) {
            if (A[i][j] == '1') {
                L[i] = min(L[i], j);
                R[i] = max(R[i], j);
            }
        }
    }

    if (N == 0) {
        writeln(0);
        return;
    } else if (N == 1) {
        writeln(R[0]);
        return;
    }

    auto dp = new int[][](N, 2);

    dp[0][0] = R[0] * 2;
    dp[0][1] = M - 1;

    foreach (i; 1..N-1) {
        dp[i][0] = min(dp[i-1][0] + R[i] * 2 + 1, dp[i-1][1] + M);
        dp[i][1] = min(dp[i-1][1] + (M - L[i] - 1) * 2 + 1, dp[i-1][0] + M);
    }

    int ans = min(dp[N-2][0] + R[N-1] + 1, dp[N-2][1] + (M - L[N-1] - 1) + 1);
    ans.writeln;
}

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

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

    Tuple!(int, int)[] floors;
    foreach (_; 0 .. n) {
        auto s = readln.chomp;
        if (s.all!(x => x == '0')) floors ~= tuple(m+1, 0);
        else {
            auto le = s.countUntil!(x => x == '1').to!int;
            auto r = m+1 - s.retro.countUntil!(x => x == '1').to!int;
            floors ~= tuple(le, r);
        }
    }

    debug { floors.writeln; }

    auto ansle = 0, ansr = 0;
    foreach (t; floors) {
        auto le = t[0], r = t[1];
        auto nowansle = r + (ansle > 0 ? 1 + min(r + ansle, m+1 - r + ansr) : 0);
        auto nowansr = m+1 - le + (ansle > 0 ? 1 + min(le + ansle, m+1 - le + ansr) : 0);

        ansle = nowansle, ansr = nowansr;
        debug { writeln(ansle, ' ', ansr); }
    }

    ansle.writeln;
}


Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t):  where  is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") =  h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") +  h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") +  h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") =  1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: .Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109 + 7.

The first line of the input contains a single integer n (1 ≤ n ≤ 105). The second line of the input contains a single string of length n, consisting of characters "ACGT".

Print a single number — the answer modulo 109 + 7.

NotePlease note that if for two distinct strings t1 and t2 values ρ(s, t1) и ρ(s, t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0.In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4.In the third sample, ρ("TTT", "TTT") = 27

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

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

void main()
{
    readln;

    auto s = readln.chomp;

    int [char] cnt;
    s.each!(c => ++cnt[c]);

    auto mx = cnt.values.maxCount[1];

    debug { mx.writeln; }

    int ans = 1;
    foreach (_; 0 .. s.length) ans = ans.to!long * mx % MD;
    ans.writeln;
}

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;

immutable int MOD = 1_000_000_007;
immutable string LETTERS = "ACGT";

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		string s = readln ().strip ();
		int [] a;
		int m;
		foreach (c; LETTERS)
		{
			a ~= s.count (c);
			m = max (m, a[$ - 1]);
		}
		string t;
		foreach (i; 0..LETTERS.length)
		{
			if (a[i] == m)
			{
				t ~= LETTERS[i];
			}
		}

		long res = 1;
		foreach (i; 0..s.length)
		{
			res = (res * t.length) % MOD;
		}
		writeln (res);
	}
}

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

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

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

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

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

immutable long MO = 10^^9 + 7;

int N;
string S;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		S = readToken;

		int[] cnt = new int[26];
		foreach (s; S) {
			++cnt[s - 'A'];
		}

		const num = cnt.count(cnt.reduce!max);
		long ans = 1;
		foreach (i; 0 .. N) {
			(ans *= num) %= MO;
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}