This is the hard version of the problem. The only difference is that here $$$2\leq k\leq 100$$$. You can make hacks only if both the versions of the problem are solved.This is an interactive problem!Every decimal number has a base $$$k$$$ equivalent. The individual digits of a base $$$k$$$ number are called $$$k$$$-its. Let's define the $$$k$$$-itwise XOR of two $$$k$$$-its $$$a$$$ and $$$b$$$ as $$$(a + b)\bmod k$$$.The $$$k$$$-itwise XOR of two base $$$k$$$ numbers is equal to the new number formed by taking the $$$k$$$-itwise XOR of their corresponding $$$k$$$-its. The $$$k$$$-itwise XOR of two decimal numbers $$$a$$$ and $$$b$$$ is denoted by $$$a\oplus_{k} b$$$ and is equal to the decimal representation of the $$$k$$$-itwise XOR of the base $$$k$$$ representations of $$$a$$$ and $$$b$$$. All further numbers used in the statement below are in decimal unless specified.You have hacked the criminal database of Rockport Police Department (RPD), also known as the Rap Sheet. But in order to access it, you require a password. You don't know it, but you are quite sure that it lies between $$$0$$$ and $$$n-1$$$ inclusive. So, you have decided to guess it. Luckily, you can try at most $$$n$$$ times without being blocked by the system. But the system is adaptive. Each time you make an incorrect guess, it changes the password. Specifically, if the password before the guess was $$$x$$$, and you guess a different number $$$y$$$, then the system changes the password to a number $$$z$$$ such that $$$x\oplus_{k} z=y$$$. Guess the password and break into the system.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$) denoting the number of test cases. $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) and $$$k$$$ $$$(2\leq k\leq 100)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

NoteTest Case 1:In this case, the hidden password is $$$2$$$.The first query is $$$3$$$. It is not equal to the current password. So, $$$0$$$ is returned, and the password is changed to $$$1$$$ since $$$2\oplus_2 1=3$$$.The second query is $$$4$$$. It is not equal to the current password. So, $$$0$$$ is returned, and the password is changed to $$$5$$$ since $$$1\oplus_2 5=4$$$.The third query is $$$5$$$. It is equal to the current password. So, $$$1$$$ is returned, and the job is done.Test Case 2:In this case, the hidden password is $$$3$$$.The first query is $$$1$$$. It is not equal to the current password. So, $$$0$$$ is returned, and the password is changed to $$$7$$$ since $$$3\oplus_3 7=1$$$. $$$[3=(10)_3$$$, $$$7=(21)_3$$$, $$$1=(01)_3$$$ and $$$(10)_3\oplus_3 (21)_3 = (01)_3]$$$.The second query is $$$4$$$. It is not equal to the current password. So, $$$0$$$ is returned, and the password is changed to $$$6$$$ since $$$7\oplus_3 6=4$$$. $$$[7=(21)_3$$$, $$$6=(20)_3$$$, $$$4=(11)_3$$$ and $$$(21)_3\oplus_3 (20)_3 = (11)_3]$$$.The third query is $$$6$$$. It is equal to the current password. So, $$$1$$$ is returned, and the job is done.Note that these initial passwords are taken just for the sake of explanation. In reality, the grader might behave differently because it is adaptive.

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    int n, k, r;
    readf!"%s %s\n"(n, k);
    stdout.writefln!"0";
    stdout.flush;
    readf!"%s\n"(r);
    int kXor(int x, int y) {
      int c = 0, p = 1;
      while(x > 0 || y > 0) {
        int a = x % k; x /= k;
        int b = y % k; y /= k;
        c += ((a - b + k) % k) * p;
        p *= k;
      }
      return c;
    }
    if (r == 0) {
      foreach(i; 1 .. n) {
        if (i % 2 == 0) {
          stdout.writefln!"%s"(kXor(i, i - 1));
          stdout.flush;
        }
        else {
          stdout.writefln!"%s"(kXor(i - 1, i));
          stdout.flush;
        }
        readf!"%s\n"(r);
        if (r == 1) {
          break;
        }
      }
    }
  }

} // main

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

long n, k, x;

long xorp(long x, long y, long param)
{
  long ans = 0;
  long ansmul = 1;
  while (x > 0 || y > 0) {
    long digitx = x % k;
    long digity = y % k;
    long ansdigit;
    switch (param & 7) {
      case 0:
        ansdigit = 0;
        break;
      case 1:
        ansdigit = k - 1;
        break;
      case 2:
        ansdigit = digitx;
        break;
      case 3:
        ansdigit = (k + digity - digitx) % k;
        break;
      case 4:
        ansdigit = (k + digitx - digity) % k;
        break;
      case 5:
        ansdigit = (digity + digitx) % k;
        break;
      case 6:
        ansdigit = (2 * k - digity - digitx) % k;
        break;
      default:
        ansdigit = digity;
        break;
    }
    ans += ansdigit * ansmul;
    x /= k;
    y /= k;
    ansmul *= k;
  }
  return ans;
}

bool solve(long param, bool function(long) judge)
{
  long param1 = param & 7;
  param >>= 3;
  long param2 = param & 7;
  param >>= 3;
  long param3 = param & 7;
  param >>= 3;
  long param4 = param & 7;
  param >>= 3;
  long param5 = param & 7;
  param >>= 3;
  long param6 = param & 7;
  param >>= 3;

  long distortion = 0;
  foreach (i ; 0 .. n) {
    if (i % 2 == 0) {
      if (judge(xorp(distortion, i, param1)))
        return true;
      distortion = xorp(distortion, xorp(distortion, i, param2), param3);
    } else {
      if (judge(xorp(distortion, i, param4)))
        return true;
      distortion = xorp(distortion, xorp(distortion, i, param5), param6);
    }
  }
  return false;
}

bool interactive_judge(long y)
{
  writeln(y);
  stdout.flush;
  return readln.strip == "1";
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    auto a = readln.strip.split.map!(to!long).array;
    n = a[0];
    k = a[1];
    solve(0x0001C8ED, &interactive_judge);
  }
}

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

long xork(long x, long y, long k)
{
  long ans = 0;
  long ansmul = 1;
  while (ansmul < 10000000) {
    long digitx = x % k;
    long digity = y % k;
    long ansdigit = (digitx + digity) % k;
    ans += ansdigit * ansmul;
    x /= k;
    y /= k;
    ansmul *= k;
  }
  return ans;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n, k;
    auto a = readln.strip.split.map!(to!long).array;
    n = a[0];
    k = a[1];
    long i = 0;
    long distortion = 0;
    while (true) {
      writeln(xork(i, distortion, k));
      stdout.flush;
      string ans = readln;
      if (ans.strip == "1") {
        break;
      }
      distortion = xork(distortion, xork(i, distortion, k), k);
      i++;
    }
  }
}


Natasha travels around Mars in the Mars rover. But suddenly it broke down, namely — the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex $$$1$$$, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, which is output. One bit is fed to each input. One bit is returned at the output.There are four types of logical elements: AND ($$$2$$$ inputs), OR ($$$2$$$ inputs), XOR ($$$2$$$ inputs), NOT ($$$1$$$ input). Logical elements take values from their direct descendants (inputs) and return the result of the function they perform. Natasha knows the logical scheme of the Mars rover, as well as the fact that only one input is broken. In order to fix the Mars rover, she needs to change the value on this input.For each input, determine what the output will be if Natasha changes this input.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$) — the number of vertices in the graph (both inputs and elements). The $$$i$$$-th of the next $$$n$$$ lines contains a description of $$$i$$$-th vertex: the first word "AND", "OR", "XOR", "NOT" or "IN" (means the input of the scheme) is the vertex type. If this vertex is "IN", then the value of this input follows ($$$0$$$ or $$$1$$$), otherwise follow the indices of input vertices of this element: "AND", "OR", "XOR" have $$$2$$$ inputs, whereas "NOT" has $$$1$$$ input. The vertices are numbered from one. It is guaranteed that input data contains a correct logical scheme with an output produced by the vertex $$$1$$$.

Print a string of characters '0' and '1' (without quotes) — answers to the problem for each input in the ascending order of their vertex indices.

10
AND 9 4
IN 1
IN 1
XOR 6 5
AND 3 7
IN 0
NOT 10
IN 1
IN 1
AND 2 8

NoteThe original scheme from the example (before the input is changed):Green indicates bits '1', yellow indicates bits '0'.If Natasha changes the input bit $$$2$$$ to $$$0$$$, then the output will be $$$1$$$.If Natasha changes the input bit $$$3$$$ to $$$0$$$, then the output will be $$$0$$$.If Natasha changes the input bit $$$6$$$ to $$$1$$$, then the output will be $$$1$$$.If Natasha changes the input bit $$$8$$$ to $$$0$$$, then the output will be $$$1$$$.If Natasha changes the input bit $$$9$$$ to $$$0$$$, then the output will be $$$0$$$.

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() {
    enum OP {IN, NOT, AND, OR, XOR};
    auto N = readln.chomp.to!int;
    auto G = new int[][](N, 2);
    auto P = new int[](N);
    auto B = new bool[](N);
    auto V = new bool[](N);
    auto ops = new OP[](N);

    foreach (i; 0..N) {
        auto s = readln.split;
        string op = s[0];
        foreach (j; 1..s.length) {
            int a = s[j].to!int - 1;
            G[i][j-1] = a;
            if (op != "IN")
                P[a] = i;
        }

        if (op == "IN") {
            ops[i] = OP.IN;
            B[i] = s[1] == "1";
        } else if (op == "NOT") {
            ops[i] = OP.NOT;
        } else if (op == "AND") {
            ops[i] = OP.AND;
        } else if (op == "OR") {
            ops[i] = OP.OR;
        } else {
            ops[i] = OP.XOR;
        }
    }

    bool operate(int n) {
        bool a = G[n][0] >= 0 ? B[G[n][0]] : 0;
        bool b = G[n][1] >= 0 ? B[G[n][1]] : 0;
        if (ops[n] == OP.IN) {
            return B[n];
        } else if (ops[n] == OP.NOT) {
            return !a;
        } else if (ops[n] == OP.AND) {
            return a & b;
        } else if (ops[n] == OP.OR) {
            return a | b;
        } else if (ops[n] == OP.XOR) {
            return a ^ b;
        }
        return 0;
    }

    void init(int n) {
        if (ops[n] == OP.IN) {
            return;
        } else if (ops[n] == OP.NOT) {
            int a = G[n][0];
            init(a);
        } else {
            int a = G[n][0];
            int b = G[n][1];
            init(a);
            init(b);
        }
        B[n] = operate(n);
    }

    void dfs(int n, bool valid) {
        V[n] = valid;
        int a = G[n][0];
        int b = G[n][1];
        if (ops[n] == OP.NOT) {
            dfs(a, valid);
        } else if (ops[n] == OP.AND) {
            if (B[a] && B[b]) {
                dfs(a, valid);
                dfs(b, valid);
            } else if (B[a] && !B[b]) {
                dfs(a, false);
                dfs(b, valid);
            } else if (!B[a] && B[b]) {
                dfs(a, valid);
                dfs(b, false);
            } else {
                dfs(a, false);
                dfs(b, false);
            }
        } else if (ops[n] == OP.OR) {
            if (B[a] && B[b]) {
                dfs(a, false);
                dfs(b, false);
            } else if (B[a] && !B[b]) {
                dfs(a, valid);
                dfs(b, false);
            } else if (!B[a] && B[b]) {
                dfs(a, false);
                dfs(b, valid);
            } else {
                dfs(a, valid);
                dfs(b, valid);
            }
        } else if (ops[n] == OP.XOR) {
            dfs(a, valid);
            dfs(b, valid);
        }
    }

    init(0);
    dfs(0, true);
    N.iota.filter!(i => ops[i] == OP.IN).map!(i => V[i] ? !B[0] : B[0]).map!(i => i.to!int.to!string).join("").writeln;
}

import std.algorithm, std.conv, std.range, std.stdio;
struct C {
	int t, l, r, v;
	int [] h;
}

void main () {
	int n;
	readf (" %s ", &n);
	auto c = new C [n];
	foreach (i, ref x; c) with (x) {
		auto z = readln.split;
		t = z[0][0];
		l = r = -1;
		if (t == 'I') {
			v = z[1].to!int;
			h ~= i;
		} else {
			l = z[1].to!int - 1;
			if (z.length > 2) r = z[2].to!int - 1;
		}
	}

	auto m (int a, int b) {
		if (c[a].h.length < c[b].h.length) swap (a, b);
		return (c[a].h ~= c[b].h);
	}

	void f (int u) {
		if (u < 0) return;
		with (c[u]) {
			f (l);
			f (r);
			if (t == 'I') return;
			if (t == 'N') {
				v = !c[l].v;
				h = c[l].h;
				return;
			}
			if (t == 'X') {
				v = c[l].v ^ c[r].v;
				h = m (l, r);
				return;
			}
			int w = c[l].v * 2 + c[r].v;
			v = w == 3;
			if (t == 'O') {
				w = 3 - w;
				v = w != 3;
			}
			h = w == 0 ? null : w == 1 ? c[l].h : w == 2 ? c[r].h : m (l, r);
		}
	}

	f (0);
	auto r = new int [n];
	r[] = c[0].v;
	foreach (i; c[0].h) r[i] ^= 1;
	writefln ("%(%s%)", n.iota.filter !(i => c[i].t == 'I').map !(i => r[i]));
}

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

immutable int NA = -1;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Command = Tuple !(string, q{name}, int, q{left},
		    int, q{right}, int, q{value}, int [], q{inputs});
		auto commands = new Command [n];

		readln;
		foreach (i, ref command; commands)
		{
			with (command)
			{
				auto t = readln.split;
				name = t[0];
				left = NA;
				right = NA;
				if (name == "IN")
				{
					value = t[1].to !(int);
					inputs ~= i;
				}
				else
				{
					left = t[1].to !(int) - 1;
					if (t.length > 2)
					{
						right = t[2].to !(int) - 1;
					}
				}
			}
		}

		int [] mergeInputs (int one, int two)
		{
			if (commands[one].inputs.length <
			    commands[two].inputs.length)
			{
				swap (one, two);
			}
			int [] res = commands[one].inputs;
			res ~= commands[two].inputs;
			return res;
		}

		void recur (int v)
		{
			with (commands[v])
			{
				if (left != NA)
				{
					recur (left);
				}
				if (right != NA)
				{
					recur (right);
				}
				if (name == "IN")
				{
				}
				else if (name == "NOT")
				{
					value = !commands[left].value;
					inputs = commands[left].inputs;
				}
				else if (name == "XOR")
				{
					value = commands[left].value ^
					    commands[right].value;
					inputs = mergeInputs (left, right);
				}
				else if (name == "AND")
				{
					auto w0 = commands[left].value;
					auto w1 = commands[right].value;
					value = w0 & w1;
					if (!w0 && !w1)
					{
						inputs = null;
					}
					if (!w0 && w1)
					{
						inputs = commands[left].inputs;
					}
					if (w0 && !w1)
					{
						inputs = commands[right].inputs;
					}
					if (w0 && w1)
					{
						inputs = mergeInputs (left, right);
					}
					return;
				}
				else if (name == "OR")
				{
					auto w0 = commands[left].value;
					auto w1 = commands[right].value;
					value = w0 | w1;
					if (w0 && w1)
					{
						inputs = null;
					}
					if (w0 && !w1)
					{
						inputs = commands[left].inputs;
					}
					if (!w0 && w1)
					{
						inputs = commands[right].inputs;
					}
					if (!w0 && !w1)
					{
						inputs = mergeInputs (left, right);
					}
					return;
				}
				else
				{
					assert (false);
				}
			}
		}

		recur (0);

		auto res = new int [n];
		res[] = commands[0].value;
		foreach (i; commands[0].inputs)
		{
			res[i] ^= 1;
		}

		writefln ("%(%s%)", n.iota
		    .filter !(i => commands[i].name == "IN")
		    .map !(i => res[i]));
	}
}

import std.algorithm, std.conv, std.range, std.stdio;
immutable int NA = -1;
struct Cmd {
	string name;
	int left, right, value;
	int [] inputs;
}

void main () {
	int n;
	readf (" %s ", &n);
	auto cmds = new Cmd [n];
	foreach (i, ref cmd; cmds) with (cmd) {
		auto t = readln.split;
		name = t[0];
		left = NA;
		right = NA;
		if (name == "IN") {
			value = t[1].to!int;
			inputs ~= i;
		} else {
			left = t[1].to!int - 1;
			if (t.length > 2)
				right = t[2].to!int - 1;
		}
	}

	auto mergeInputs (int one, int two) {
		if (cmds[one].inputs.length < cmds[two].inputs.length)
			swap (one, two);
		auto res = cmds[one].inputs;
		res.assumeSafeAppend ();
		res ~= cmds[two].inputs;
		return res;
	}

	void recur (int v) {
		if (v == NA)
			return;
		with (cmds[v]) {
			recur (left);
			recur (right);
			if (name == "IN")
				return;
			if (name == "NOT") {
				value = !cmds[left].value;
				inputs = cmds[left].inputs;
				return;
			}
			if (name == "XOR") {
				value = cmds[left].value ^ cmds[right].value;
				inputs = mergeInputs (left, right);
				return;
			}
			int w = cmds[left].value * 2 + cmds[right].value;
			value = w == 3;
			if (name == "OR") {
				w = 3 - w;
				value = w != 3;
			}
			inputs = w == 0 ? null : w == 1 ? cmds[left].inputs : w == 2 ? cmds[right].inputs : mergeInputs (left, right);
		}
	}

	recur (0);
	auto res = new int [n];
	res[] = cmds[0].value;
	foreach (i; cmds[0].inputs)
		res[i] ^= 1;
	writefln ("%(%s%)", n.iota.filter !(i => cmds[i].name == "IN").map !(i => res[i]));
}

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;
import std.traits;
import std.variant;
import std.concurrency;

void main(string[] args)
{
  auto n = next!int;
  struct NodeInfo
  {
    enum Type
      {
	and, or, xor, not, input
      };
    Type type;
    int o1, o2;
    int value;
  }
  auto nodes = new NodeInfo[](n);
 nodeInput:foreach(i; 0 .. n)
    {
      auto typeString = next!string;
      final switch(typeString)
	{
	case "AND":
	  nodes[i].type = NodeInfo.Type.and;
	  break;
	case "OR":
	  nodes[i].type = NodeInfo.Type.or;
	  break;
	case "XOR":
	  nodes[i].type = NodeInfo.Type.xor;
	  break;
	case "NOT":
	  nodes[i].type = NodeInfo.Type.not;
	  nodes[i].o1 = next!int - 1;
	  continue nodeInput;
	case "IN":
	  nodes[i].type = NodeInfo.Type.input;
	  nodes[i].value = next!int;
	  continue nodeInput;
	}
      nodes[i].o1 = next!int - 1;
      nodes[i].o2 = next!int - 1;
    }
  auto valueOf = new int[](n);
  int calcValue(int i)
  {
    auto node = nodes[i];
    int res = -1;
    final switch(node.type)
      {
      case NodeInfo.Type.and:
	res = calcValue(node.o1) & calcValue(node.o2);
	break;
      case NodeInfo.Type.or:
	res = calcValue(node.o1) | calcValue(node.o2);
	break;
      case NodeInfo.Type.xor:
	res = calcValue(node.o1) ^ calcValue(node.o2);
	break;
      case NodeInfo.Type.not:
	res = !calcValue(node.o1);
	break;
      case NodeInfo.Type.input:
	res = node.value;
	break;
      }
    valueOf[i] = res;
    return res;
  }
  calcValue(0);
  debug foreach(i; 0 .. n)
    {
      writeln(i + 1, ": ", valueOf[i]);
    }
  auto res = new int[](n);
  res[] = valueOf[0];
  void change(int i)
  {
    auto node = nodes[i];
    auto value = valueOf[i];
    final switch(node.type)
      {
      case NodeInfo.Type.and:
	if (value == 1)
	  {
	    change(node.o1);
	    change(node.o2);
	    return;
	  }
	if (!valueOf[node.o1] && !valueOf[node.o2]) return;
	if (!valueOf[node.o1]) return change(node.o1);
	assert(!valueOf[node.o2]);
	return change(node.o2);
      case NodeInfo.Type.or:
	if (value == 0)
	  {
	    change(node.o1);
	    change(node.o2);
	    return;
	  }
	if (valueOf[node.o1] && valueOf[node.o2]) return;
	if (valueOf[node.o1]) return change(node.o1);
	assert(valueOf[node.o2]);
	return change(node.o2);
      case NodeInfo.Type.xor:
	change(node.o1);
	return change(node.o2);
      case NodeInfo.Type.not:
	return change(node.o1);
      case NodeInfo.Type.input:
	res[i] = !res[i];
      }
  }
  change(0);

  foreach(i; 0 .. n)
    {
      if (nodes[i].type == NodeInfo.Type.input)
	{
	  write(res[i]);
	}
    }
  writeln;
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  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.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}

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()
{
    bool isBinOp(string op) { return ["AND", "OR", "XOR"].canFind(op); }

    debug { isBinOp("AND").writeln; }

    struct node {
        int id;
        string op;
        bool value;
        int le, r;
        bool flip;
    }

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

    auto arr = new node[] (n+1);

    foreach (i; 1 .. n+1) {
        auto vals = readln.chomp.split;
        arr[i].id = i;
        arr[i].op = vals[0];
        if (arr[i].op == "IN") {
            arr[i].value = cast(bool) vals[1].to!int;
            continue;
        }

        arr[i].le = vals[1].to!int;
        if (isBinOp(arr[i].op)) arr[i].r = vals[2].to!int;
    }

    bool dfsUp(int v) {
        if (arr[v].op == "NOT") {
            arr[v].value = ! dfsUp(arr[v].le);
        } else if (isBinOp(arr[v].op)) {
            bool leftVal = dfsUp(arr[v].le);
            bool rightVal = dfsUp(arr[v].r);

            if (arr[v].op == "AND") arr[v].value = leftVal && rightVal;
            if (arr[v].op == "XOR") arr[v].value = leftVal ^ rightVal;
            if (arr[v].op == "OR") arr[v].value = leftVal || rightVal;
        }

        return arr[v].value;
    }

    dfsUp(1);

    debug { arr.each!writeln; }

    void dfsDown(int v) {
        if (arr[v].op == "IN") {
            arr[v].flip = true;
            return;
        }

        if (arr[v].op == "NOT") {
            dfsDown(arr[v].le);
            return;
        }

        bool le = arr[arr[v].le].value, r = arr[arr[v].r].value;
        if (arr[v].op == "AND") {
            if (r) {
                dfsDown(arr[v].le);
            }
            if (le) {
                dfsDown(arr[v].r);
            }

            return;
        }

        if (arr[v].op == "OR") {
            if (!r) {
                dfsDown(arr[v].le);
            }
            if (!le) {
                dfsDown(arr[v].r);
            }
            return;
        }

        //XOR
        dfsDown(arr[v].le);
        dfsDown(arr[v].r);
    }

    dfsDown(1);

    debug { arr.filter!(e => e.op == "IN").map!(e => e.flip).each!writeln; }

    auto ans = arr.filter!(e => e.op == "IN").map!(e => arr[1].value ^ e.flip);

    ans.map!(x => x ? '1' : '0').writeln;
}

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

void main() {
    enum OP {IN, NOT, AND, OR, XOR};
    auto N = readln.chomp.to!int;
    auto G = new int[][](N, 2);
    auto P = new int[](N);
    auto ops = new OP[](N);
    auto bits = new bool[](N);
    auto not = new bool[](N);

    foreach (i; 0..N) {
        auto s = readln.split;
        string op = s[0];
        foreach (j; 1..s.length) {
            int a = s[j].to!int - 1;
            G[i][j-1] = a;
            if (op != "IN")
                P[a] = i;
        }

        if (op == "IN") {
            ops[i] = OP.IN;
            bits[i] = s[1] == "1";
        } else if (op == "NOT") {
            ops[i] = OP.NOT;
            not[i] = true;
        } else if (op == "AND") {
            ops[i] = OP.AND;
        } else if (op == "OR") {
            ops[i] = OP.OR;
        } else {
            ops[i] = OP.XOR;
        }
    }

    void dfs(int n, int pn) {
        if (ops[n] == OP.NOT) {
            int m = G[n][0];
            G[P[n]][pn] = m;
            P[m] = P[n];
            not[m] ^= not[n];
            dfs(m, pn);
        } else if (ops[n] != OP.IN) {
            foreach (i; 0..2) {
                dfs(G[n][i], i);
            }
        }
    }

    bool operate(int n) {
        bool ret;
        bool a = G[n][0] >= 0 ? bits[G[n][0]] : 0;
        bool b = G[n][1] >= 0 ? bits[G[n][1]] : 0;
        if (ops[n] == OP.IN) {
            ret = bits[n];
        } else if (ops[n] == OP.NOT) {
            ret = !a;
        } else if (ops[n] == OP.AND) {
            ret = a & b;
        } else if (ops[n] == OP.OR) {
            ret = a | b;
        } else if (ops[n] == OP.XOR) {
            ret = a ^ b;
        }
        return ret ^ not[n];
    }

    void init(int n) {
        int a = G[n][0];
        int b = G[n][1];
        if (ops[n] == OP.IN) {
            if (not[n]) {
                bits[n] ^= 1;
                not[n] ^= 1;
            }
        } else if (ops[n] == OP.NOT) {
            init(a);
            bits[n] = operate(n);
        } else {
            init(a);
            init(b);
            bits[n] = operate(n);
        }
    }

    void up(int n) {

        bits[n] = operate(n);
        if (n != 0) up(P[n]);
    }

    if (ops[0] == OP.NOT) {
        dfs(G[0][0], 0);
    } else {
        dfs(0, -1);
    }

    bool[] ans;
    init(0);

    foreach (i; 0..N) {
        if (ops[i] != OP.IN)
            continue;
        bits[i] ^= 1;
        up(i);
        ans ~= bits[0];
        bits[i] ^= 1;
        up(i);
    }

    ans.map!(a => a ? "1" : "0").join.writeln;
}

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

void main() {
    enum OP {IN, NOT, AND, OR, XOR};
    auto N = readln.chomp.to!int;
    auto G = new int[][](N, 2);
    auto P = new int[](N);
    auto ops = new OP[](N);
    auto bits = new bool[](N);
    auto not = new bool[](N);

    foreach (i; 0..N) {
        auto s = readln.split;
        string op = s[0];
        foreach (j; 1..s.length) {
            int a = s[j].to!int - 1;
            G[i][j-1] = a;
            if (op != "IN")
                P[a] = i;
        }

        if (op == "IN") {
            ops[i] = OP.IN;
            bits[i] = s[1] == "1";
        } else if (op == "NOT") {
            ops[i] = OP.NOT;
        } else if (op == "AND") {
            ops[i] = OP.AND;
        } else if (op == "OR") {
            ops[i] = OP.OR;
        } else {
            ops[i] = OP.XOR;
        }
    }

    void dfs(int n, int pn) {
        if (ops[n] == OP.NOT) {
            int m = G[n][0];
            G[P[n]][pn] = m;
            P[m] = P[n];
            not[m] ^= not[n];
            dfs(m, pn);
        } else if (ops[n] != OP.IN) {
            foreach (i; 0..2) {
                dfs(G[n][i], i);
            }
        }
    }

    bool operate(int n) {
        bool ret;
        bool a = G[n][0] >= 0 ? bits[G[n][0]] : 0;
        bool b = G[n][1] >= 0 ? bits[G[n][1]] : 0;
        if (ops[n] == OP.IN) {
            ret = bits[n];
        } else if (ops[n] == OP.NOT) {
            ret = !a;
        } else if (ops[n] == OP.AND) {
            ret = a & b;
        } else if (ops[n] == OP.OR) {
            ret = a | b;
        } else if (ops[n] == OP.XOR) {
            ret = a ^ b;
        }
        return ret ^ not[n];
    }

    void init(int n) {
        int a = G[n][0];
        int b = G[n][1];
        if (ops[n] == OP.IN) {
            if (not[n]) {
                bits[n] ^= 1;
                not[n] ^= 1;
            }
        } else if (ops[n] == OP.NOT) {
            init(a);
            bits[n] = operate(n);
        } else {
            init(a);
            init(b);
            bits[n] = operate(n);
        }
    }

    void up(int n) {
        bits[n] = operate(n);
        if (n != 0) up(P[n]);
    }

    if (ops[0] == OP.NOT) {
        dfs(G[0][0], 0);
    } else {
        dfs(0, -1);
    }

    bool[] ans;
    init(0);

    foreach (i; 0..N) {
        if (ops[i] != OP.IN)
            continue;
        bits[i] ^= 1;
        up(i);
        ans ~= bits[0];
        bits[i] ^= 1;
        up(i);
    }

    ans.map!(a => a ? "1" : "0").join.writeln;
}

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

void main() {
    enum OP {IN, NOT, AND, OR, XOR};
    auto N = readln.chomp.to!int;
    auto G = new int[][](N, 2);
    auto P = new int[](N);
    auto ops = new OP[](N);
    auto bits = new bool[](N);
    auto not = new bool[](N);

    foreach (i; 0..N) {
        auto s = readln.split;
        string op = s[0];
        foreach (j; 1..s.length) {
            int a = s[j].to!int - 1;
            G[i][j-1] = a;
            if (op != "IN")
                P[a] = i;
        }

        if (op == "IN") {
            ops[i] = OP.IN;
            bits[i] = s[1] == "1";
        } else if (op == "NOT") {
            ops[i] = OP.NOT;
            not[i] = true;
        } else if (op == "AND") {
            ops[i] = OP.AND;
        } else if (op == "OR") {
            ops[i] = OP.OR;
        } else {
            ops[i] = OP.XOR;
        }
    }

    void dfs(int start) {
        auto stack = new Tuple!(int, int)[](N);
        int p = 0;
        stack[0] = tuple(start, 0);
        while (p >= 0) {
            int n = stack[p][0];
            int pn = stack[p][1];
            --p;
            if (ops[n] == OP.NOT) {
                int m = G[n][0];
                G[P[n]][pn] = m;
                P[m] = P[n];
                not[m] ^= not[n];
                stack[++p] = tuple(m, pn);
            } else if (ops[n] != OP.IN) {
                foreach (i; 0..2) {
                    stack[++p] = tuple(G[n][i], i);
                }
            }
        }
    }

    bool operate(int n) {
        bool ret;
        bool a = G[n][0] >= 0 ? bits[G[n][0]] : 0;
        bool b = G[n][1] >= 0 ? bits[G[n][1]] : 0;
        if (ops[n] == OP.IN) {
            ret = bits[n];
        } else if (ops[n] == OP.NOT) {
            ret = !a;
        } else if (ops[n] == OP.AND) {
            ret = a & b;
        } else if (ops[n] == OP.OR) {
            ret = a | b;
        } else if (ops[n] == OP.XOR) {
            ret = a ^ b;
        }
        return ret ^ not[n];
    }

    void init(int n) {
        int a = G[n][0];
        int b = G[n][1];
        if (ops[n] == OP.IN) {
            if (not[n]) {
                bits[n] ^= 1;
                not[n] ^= 1;
            }
        } else if (ops[n] == OP.NOT) {
            init(a);
            bits[n] = operate(n);
        } else {
            init(a);
            init(b);
            bits[n] = operate(n);
        }
    }

    void up(int n) {
        bits[n] = operate(n);
        if (n != 0) up(P[n]);
    }

    if (ops[0] == OP.NOT) {
        dfs(G[0][0]);
    } else {
        dfs(0);
    }

    bool[] ans;
    init(0);

    foreach (i; 0..N) {
        if (ops[i] != OP.IN)
            continue;
        bits[i] ^= 1;
        up(i);
        ans ~= bits[0];
        bits[i] ^= 1;
        up(i);
    }

    ans.map!(a => a ? "1" : "0").join.writeln;
}

import std.algorithm, std.conv, std.range, std.stdio;
immutable int NA = -1;
struct Cmd {
	string name;
	int left, right, value;
	int [] inputs;
}

void main () {
	int n;
	readf (" %s ", &n);
	auto cmds = new Cmd [n];
	foreach (i, ref cmd; cmds) with (cmd) {
		auto t = readln.split;
		name = t[0];
		left = NA;
		right = NA;
		if (name == "IN") {
			value = t[1].to!int;
			inputs ~= i;
		} else {
			left = t[1].to!int - 1;
			if (t.length > 2)
				right = t[2].to!int - 1;
		}
	}

	auto mergeInputs (int one, int two) {
		if (cmds[one].inputs.length < cmds[two].inputs.length)
			swap (one, two);
		auto res = cmds[one].inputs;
		res.assumeSafeAppend ();
		res ~= cmds[two].inputs;
		return res;
	}

	void recur (int v) {
		if (v == NA)
			return;
		with (cmds[v]) {
			recur (left);
			recur (right);
			if (name == "IN")
				return;
			if (name == "NOT") {
				value = !cmds[left].value;
				inputs = cmds[left].inputs;
				return;
			}
			if (name == "XOR") {
				value = cmds[left].value ^ cmds[right].value;
				inputs = mergeInputs (left, right);
				return;
			}
			int w = cmds[left].value * 2 + cmds[right].value;
			value = w == 3;
			if (name == "OR") {
				w = 3 - w;
				value = w != 0;
			}
			inputs = w == 0 ? null : w == 1 ? cmds[left].inputs : w == 2 ? cmds[right].inputs : mergeInputs (left, right);
		}
	}

	recur (0);
	auto res = new int [n];
	res[] = cmds[0].value;
	foreach (i; cmds[0].inputs)
		res[i] ^= 1;
	writefln ("%(%s%)", n.iota.filter !(i => cmds[i].name == "IN").map !(i => res[i]));
}

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()
{
    bool isBinOp(string op) { return ["AND", "OR", "XOR"].canFind(op); }

    debug { isBinOp("AND").writeln; }

    struct node {
        int id;
        string op;
        bool value;
        int le, r;
        bool flip;
    }

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

    auto arr = new node[] (n+1);

    foreach (i; 1 .. n+1) {
        auto vals = readln.chomp.split;
        arr[i].id = i;
        arr[i].op = vals[0];
        if (arr[i].op == "IN") {
            arr[i].value = cast(bool) vals[1].to!int;
            continue;
        }

        arr[i].le = vals[1].to!int;
        if (isBinOp(arr[i].op)) arr[i].r = vals[2].to!int;
    }

    bool dfsUp(int v) {
        if (arr[v].op == "NOT") {
            arr[v].value = ! dfsUp(arr[v].le);
        } else if (isBinOp(arr[v].op)) {
            bool leftVal = dfsUp(arr[v].le);
            bool rightVal = dfsUp(arr[v].r);

            if (arr[v].op == "AND") arr[v].value = leftVal && rightVal;
            if (arr[v].op == "XOR") arr[v].value = leftVal ^ rightVal;
            if (arr[v].op == "OR") arr[v].value = leftVal || rightVal;
        }

        return arr[v].value;
    }

    dfsUp(1);

    debug { arr.each!writeln; }

    void dfsDown(int v) {
        if (arr[v].op == "IN") {
            arr[v].flip = true;
            return;
        }

        if (arr[v].op == "NOT") {
            dfsDown(arr[v].le);
            return;
        }

        bool le = arr[arr[v].le].value, r = arr[arr[v].r].value;
        if (arr[v].op == "AND") {
            if (le & r) {
                dfsDown(arr[v].le);
                dfsDown(arr[v].r);
            } else if (le) {
                dfsDown(arr[v].r);
            } else if (r) {
                dfsDown(arr[v].le);
            }

            return;
        }

        if (arr[v].op == "OR") {
            if (!(le || r)) {
                dfsDown(arr[v].le);
                dfsDown(arr[v].r);
            } else if (le) {
                dfsDown(arr[v].le);
            } else if (r) {
                dfsDown(arr[v].r);
            }

            return;
        }

        //XOR
        dfsDown(arr[v].le);
        dfsDown(arr[v].r);
    }

    dfsDown(1);

    debug { arr.filter!(e => e.op == "IN").map!(e => e.flip).each!writeln; }

    auto ans = arr.filter!(e => e.op == "IN").map!(e => arr[1].value ^ e.flip);

    ans.map!(x => x ? '1' : '0').writeln;
}


Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters.

For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints.

4

3 2

aab

3 3

aab

7 1

abacaba

2 0

ab

NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab.

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!int;
		auto k = RD!int;
		auto s = RD!string;

		if (k == 0)
		{
			ans[ti] = 1;
			continue;
		}

		int l, r = n-1;
		bool ok = true;
		while (l < r)
		{
			if (s[l] != s[r])
			{
				ok = false;
				break;
			}
			++l; --r;
		}
		if (ok)
			ans[ti] = 1;
		else
			ans[ti] = 2;
	}

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

// cheese-cracker [2022-02-06]

void solve(){
    long n = scan;
    long k = scan;
    auto s = scan!(dchar[]);
    auto rs = s.dup;
    rs.reverse;
    if(s == rs || k == 0){
        writeln(1);
    }else{
        writeln(2);
    }
}

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


Let's call an array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$ a $$$k$$$-extension for some non-negative integer $$$k$$$ if for all possible pairs of indices $$$1 \leq i, j \leq n$$$ the inequality $$$k \cdot |i - j| \leq min(a_i, a_j)$$$ is satisfied. The expansion coefficient of the array $$$a$$$ is the maximal integer $$$k$$$ such that the array $$$a$$$ is a $$$k$$$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.You are given an array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Find its expansion coefficient.

The first line contains one positive integer $$$n$$$ — the number of elements in the array $$$a$$$ ($$$2 \leq n \leq 300\,000$$$). The next line contains $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$, separated by spaces ($$$0 \leq a_i \leq 10^9$$$).

Print one non-negative integer — expansion coefficient of the array $$$a_1, a_2, \ldots, a_n$$$.

NoteIn the first test, the expansion coefficient of the array $$$[6, 4, 5, 5]$$$ is equal to $$$1$$$ because $$$|i-j| \leq min(a_i, a_j)$$$, because all elements of the array satisfy $$$a_i \geq 3$$$. On the other hand, this array isn't a $$$2$$$-extension, because $$$6 = 2 \cdot |1 - 4| \leq min(a_1, a_4) = 5$$$ is false.In the second test, the expansion coefficient of the array $$$[0, 1, 2]$$$ is equal to $$$0$$$ because this array is not a $$$1$$$-extension, but it is $$$0$$$-extension.

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

void main()
{
    auto N = readln.chomp.to!int;
    auto AS = readln.split.to!(int[]);

    auto k = int.max, x = int.max, n = N;
    size_t i, j = N-1;
    while (i <= j) {
        --n;
        x = min(x, AS[i]);
        x = min(x, AS[j]);
        k = min(k, x / n);
        ++i;
        --j;
    }
    writeln(k);
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;
import std.math : abs;

alias Tree = RBT!int;

void main() {
  GC.disable();

  uint n;
  readf(" %s", n);

  auto a = new int[n];
  foreach(i; 0 .. n) {
    readf(" %s", a[i]);
  }

  auto aa = a.enumerate.array.sort!"a.value < b.value";
  int k = 1_000_000_009;
  int maxidx = -1;
  int minidx = n+n;
  for(int i = n-1; i>=0; i--) {
    if (i != n-1){
      k = min(k, aa[i].value/(abs(maxidx - to!int(aa[i].index))));
      k = min(k, aa[i].value/(abs(minidx - to!int(aa[i].index))));
    }

    maxidx = max(maxidx, to!int(aa[i].index));
    minidx = min(minidx, to!int(aa[i].index));
  }

  writeln(k);
}


The Narrator has an integer array $$$a$$$ of length $$$n$$$, but he will only tell you the size $$$n$$$ and $$$q$$$ statements, each of them being three integers $$$i, j, x$$$, which means that $$$a_i \mid a_j = x$$$, where $$$|$$$ denotes the bitwise OR operation.Find the lexicographically smallest array $$$a$$$ that satisfies all the statements.An array $$$a$$$ is lexicographically smaller than an array $$$b$$$ of the same length if and only if the following holds:   in the first position where $$$a$$$ and $$$b$$$ differ, the array $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.

In the first line you are given with two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le q \le 2 \cdot 10^5$$$). In the next $$$q$$$ lines you are given with three integers $$$i$$$, $$$j$$$, and $$$x$$$ ($$$1 \le i, j \le n$$$, $$$0 \le x < 2^{30}$$$) — the statements. It is guaranteed that all $$$q$$$ statements hold for at least one array.

On a single line print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{30}$$$) — array $$$a$$$.

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

alias Tuple!(uint,uint) P;

void main() {
    int N, Q; readf("%d %d\n", &N, &Q);
    P[][] G = new P[][N];
    foreach (q; 0 .. Q) {
        uint i, j, x;
        readf("%d %d %d\n", &i, &j, &x);
        i--;
        j--;
        G[i] ~= P(j, x);
        G[j] ~= P(i, x);
    }

    uint[] ans = new uint[N]; ans[] = ~0;
    uint[] fixed = new uint[N]; fixed[] = 0;
    // if the k-th bit of (a | b) is 0, then both of the k-the bit of a and of b are 0
    for (int i = 0; i < N; i++) {
        foreach (e; G[i]) {
            auto j = e[0], x = e[1];
            if (i == j) {
                ans[i] = x;
                fixed[i] = ~0;
            } else {
                ans[i] &= x;
                fixed[i] |= ~x;
            }
        }
    }
    for (int i = 0; i < N; i++) {
        for (int k = 0; k < 32; k++) {
            if (fixed[i] & (1<<k)) continue;
            bool one = false;
            foreach (e; G[i]) {
                auto j = e[0], x = e[1];
                if (! (fixed[j] & (1<<k))) continue;
                if ( (ans[j] & (1<<k)) == 0 ) {
                    // k-th bit of ans[i] must be 1.
                    one = true;
                    break;
                }
            }
            if (one) {
                // do nothing (ans[i]'s k-the bit is initially 1)
            } else {
                ans[i] &= ~(1<<k);
            }
            fixed[i] |= 1<<k;
        }
    }
    writefln("%(%s %)", ans);
}

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

alias Tuple!(uint,uint) P;

void main() {
    int N, Q; readf("%d %d\n", &N, &Q);
    P[][] G = new P[][N];
    foreach (q; 0 .. Q) {
        uint i, j, x;
        readf("%d %d %d\n", &i, &j, &x);
        i--;
        j--;
        G[i] ~= P(j, x);
        G[j] ~= P(i, x);
    }

    uint[] ans = new uint[N]; ans[] = ~0;
    uint[] fixed = new uint[N]; fixed[] = 0;
    // if the k-th bit of (a | b) is 0, then both of the k-the bit of a and of b are 0
    for (int i = 0; i < N; i++) {
        foreach (e; G[i]) {
            auto j = e[0], x = e[1];
            if (i == j) {
                ans[i] = x;
                fixed[i] = ~0;
            } else {
                ans[i] &= x;
                fixed[i] |= ~x;
            }
        }
    }
    for (int i = 0; i < N; i++) {
        for (int k = 0; k < 32; k++) {
            if (fixed[i] & (1<<k)) continue;
            bool one = false;
            foreach (e; G[i]) {
                auto j = e[0], x = e[1];
                if (! (fixed[j] & (1<<k))) continue;
                if ( (ans[j] & ~(1<<k)) == 0 ) {
                    // k-th bit of ans[i] must be 1.
                    one = true;
                    break;
                }
            }
            if (one) {
                // do nothing (ans[i]'s k-the bit is initially 1)
            } else {
                ans[i] &= ~(1<<k);
            }
            fixed[i] |= 1<<k;
        }
    }
    writefln("%(%s %)", ans);
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(T)(T x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int N, Q; scanf("%d %d\n", &N, &Q);
    auto J = new int[][](N), X = new uint[][](N);
    auto F = new uint[N]; F[] = 0;
    auto B = new uint[N]; B[] = ~0;
    for (int q = 0; q < Q; q++) {
        int i, j, x_;
        scanf("%d %d %d\n", &i, &j, &x_);
        uint x = x_;
        i--; j--;
        if (i > j) swap(i, j);
        if (i == j) {
            F[i] = ~0;
            B[i] = x;
        } else {
            J[i] ~= j;
            X[i] ~= x;
            // (i, j=J[i][?]) -> (or) -> X[i][j]
            F[i] |= ~x; F[j] |= ~x;
            B[i] &= x; B[j] &= x;
        }
    }
    for (int i = 0; i < N; i++) {
        for (int s = 31; s >= 0; s--) {
            if (! (F[i] & (1<<s))) {
                B[i] &= ~(1<<s);
                F[i] |= (1<<s);
            }
            if ( (B[i] & (1<<s)) == 0 ) {
                for (int k = 0; k < J[i].length; k++) {
                    int j = J[i][k];
                    if (X[i][k] & (1<<s)) {
                        F[j] |= (1<<s);
                        // B[j]'s s-th bit is 1.
                        assert( (B[j] & (1<<s)) > 0);
                    }
                }
            }
        }
    }
    writefln("%(%s %)", B);
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(T)(T x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int N, Q; scanf("%d %d\n", &N, &Q);
    auto J = new int[][](N), X = new int[][](N);
    auto F = new uint[N]; F[] = 0;
    auto B = new uint[N]; B[] = ~0;
    for (int q = 0; q < Q; q++) {
        int i, j, x_;
        scanf("%d %d %d\n", &i, &j, &x_);
        uint x = x_;
        i--; j--;
        if (i > j) swap(i, j);
        if (i == j) {
            F[i] = ~0;
            B[i] = x;
        } else {
            J[i] ~= j;
            X[i] ~= x;
            // (i, j=J[i][?]) -> (or) -> X[i][j]
            F[i] |= ~x; F[j] |= ~x;
            B[i] &= x; B[j] &= x;
        }
    }
    for (int i = 0; i < N; i++) {
        for (int s = 31; s >= 0; s--) {
            if (! (F[i] & (1<<s))) {
                B[i] &= ~(1<<s);
                F[i] |= (1<<s);
            }
            if ( (B[i] & (1<<s)) == 0 ) {
                for (int k = 0; k < J[i].length; k++) {
                    int j = J[i][k];
                    if (X[i][k] & (1<<s)) {
                        F[j] |= (1<<s);
                        // B[j]'s s-th bit is 1.
                        assert( (B[j] & (1<<s)) > 0);
                    }
                }
            }
        }
    }
    writefln("%(%s %)", B);
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(T)(T x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int N, Q; scanf("%d %d\n", &N, &Q);
    auto J = new int[][](N), X = new int[][](N);
    auto F = new uint[N]; F[] = 0;
    auto B = new uint[N]; B[] = ~0;
    for (int q = 0; q < Q; q++) {
        int i, j, x_;
        scanf("%d %d %d\n", &i, &j, &x_);
        uint x = x_;
        i--; j--;
        if (i > j) swap(i, j);
        if (i == j) {
            F[i] = ~0;
            B[i] = x;
        } else {
            J[i] ~= j;
            X[i] ~= x;
        }
        // (i, j=J[i][?]) -> (or) -> X[i][j]
        F[i] |= ~x; F[j] |= ~x;
        B[i] &= x; B[j] &= x;
    }
    for (int i = 0; i < N; i++) {
        for (int s = 31; s >= 0; s--) {
            if (! (F[i] & (1<<s))) {
                B[i] &= ~(1<<s);
                F[i] |= (1<<s);
            }
            if ( (B[i] & (1<<s)) == 0 ) {
                for (int k = 0; k < J[i].length; k++) {
                    int j = J[i][k];
                    if (X[i][k] & (1<<s)) {
                        F[j] |= (1<<s);
                        // B[j]'s s-th bit is 1.
                        assert( (B[j] & (1<<s)) > 0);
                    }
                }
            }
            /*
            DBG!s;
            DBG!i;
            writeln(B);
            */
        }
    }
    writefln("%(%s %)", B);
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(T)(T x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int N, Q; scanf("%d %d\n", &N, &Q);
    auto J = new int[][](N), X = new int[][](N);
    auto F = new uint[N]; F[] = 0;
    auto B = new uint[N]; B[] = ~0;
    for (int q = 0; q < Q; q++) {
        int i, j, x_;
        scanf("%d %d %d\n", &i, &j, &x_);
        uint x = x_;
        i--; j--;
        if (i > j) swap(i, j);
        if (i == j) {
            F[i] = ~0;
            B[i] = x;
        } else {
            J[i] ~= j;
            X[i] ~= x;
        }
        // (i, j=J[i][?]) -> (or) -> X[i][j]
        F[i] |= ~x; F[j] |= ~x;
        B[i] &= x; B[j] &= x;
    }
    for (int i = 0; i < N; i++) {
        for (int s = 31; s >= 0; s--) {
            if (! (F[i] & (1<<s))) {
                B[i] &= ~(1<<s);
                F[i] |= (1<<s);
            }
            if ( (B[i] & (1<<s)) == 0 ) {
                for (int k = 0; k < J[i].length; k++) {
                    int j = J[i][k];
                    if (X[i][k] & (1<<s)) {
                        F[j] |= (1<<s);
                        // B[j]'s s-th bit is 1.
                    }
                }
            }
            /*
            DBG!s;
            DBG!i;
            writeln(B);
            */
        }
    }
    writefln("%(%s %)", B);
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(T)(T x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int N, Q; scanf("%d %d\n", &N, &Q);
    auto J = new int[][](N), X = new int[][](N);
    auto F = new uint[N]; F[] = 0;
    auto B = new uint[N]; B[] = ~0;
    for (int q = 0; q < Q; q++) {
        int i, j, x_;
        scanf("%d %d %d\n", &i, &j, &x_);
        uint x = x_;
        i--; j--;
        if (i > j) swap(i, j);
        if (i == j) {
            F[i] = ~0;
            B[i] = x;
        } else {
            J[i] ~= j;
            X[i] ~= x;
        }
        // (i, j=J[i][?]) -> (or) -> X[i][j]
        F[i] |= ~x; F[j] |= ~x;
        B[i] &= x; B[j] &= x;
    }
    for (int s = 31; s >= 0; s--) {
        for (int i = 0; i < N; i++) {
            if (! (F[i] & (1<<s))) {
                B[i] &= ~(1<<s);
                F[i] |= (1<<s);
            }
            if ( (B[i] & (1<<s)) == 0 ) {
                for (int k = 0; k < J[i].length; k++) {
                    int j = J[i][k];
                    if (X[i][k] & (1<<s)) {
                        F[j] |= (1<<s);
                        // B[j]'s s-th bit is 1.
                    }
                }
            }
            /*
            DBG!s;
            DBG!i;
            writeln(B);
            */
        }
    }
    writefln("%(%s %)", B);
}

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(T)(T x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int N, Q; scanf("%d %d\n", &N, &Q);
    auto J = new int[][](N), X = new int[][](N);
    auto F = new uint[N]; F[] = 0;
    auto B = new uint[N]; B[] = ~0;
    for (int q = 0; q < Q; q++) {
        int i, j, x_;
        scanf("%d %d %d\n", &i, &j, &x_);
        uint x = x_;
        i--; j--;
        if (i > j) swap(i, j);
        if (i == j) {
            F[i] = ~0;
            B[i] = x;
        } else {
            J[i] ~= j;
            X[i] ~= x;
        }
        // (i, j=J[i][?]) -> (or) -> X[i][j]
        F[i] |= ~x; F[j] |= ~x;
        B[i] &= x; B[j] &= x;
    }
    for (int s = 32; s >= 0; s--) {
        for (int i = 0; i < N; i++) {
            if (! (F[i] & (1<<s))) {
                B[i] &= ~(1<<s);
                F[i] |= (1<<s);
            }
            if ( (B[i] & (1<<s)) == 0 ) {
                for (int k = 0; k < J[i].length; k++) {
                    int j = J[i][k];
                    if (X[i][k] & (1<<s)) {
                        F[j] |= (1<<s);
                        // B[j]'s s-th bit is 1.
                    }
                }
            }
            /*
            DBG!s;
            DBG!i;
            writeln(B);
            */
        }
    }
    writefln("%(%s %)", B);
}


This is the easy version of the problem. The only difference between the versions is the constraints on $$$n$$$, $$$k$$$, $$$a_i$$$, and the sum of $$$n$$$ over all test cases. You can make hacks only if both versions of the problem are solved.Note the unusual memory limit.You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, and an integer $$$k$$$.The cost of an array of integers $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$ is $$$$$$\max\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right) - \min\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right).$$$$$$Here, $$$\lfloor \frac{x}{y} \rfloor$$$ denotes the integer part of the division of $$$x$$$ by $$$y$$$. Find the minimum cost of an array $$$p$$$ such that $$$1 \le p_i \le k$$$ for all $$$1 \le i \le n$$$.

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, k \le 3000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_1 \le a_2 \le \ldots \le a_n \le 3000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3000$$$.

For each test case, print a single integer — the minimum possible cost of an array $$$p$$$ satisfying the condition above.

NoteIn the first test case, the optimal array is $$$p = [1, 1, 1, 2, 2]$$$. The resulting array of values of $$$\lfloor \frac{a_i}{p_i} \rfloor$$$ is $$$[4, 5, 6, 4, 5]$$$. The cost of $$$p$$$ is $$$\max\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) - \min\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) = 6 - 4 = 2$$$. We can show that there is no array (satisfying the condition from the statement) with a smaller cost.In the second test case, one of the optimal arrays is $$$p = [12, 12, 12, 12, 12]$$$, which results in all $$$\lfloor \frac{a_i}{p_i} \rfloor$$$ being $$$0$$$.In the third test case, the only possible array is $$$p = [1, 1, 1]$$$.

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

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

    int cur_len = int.max;
    int[] ans;
    for (int L = 0; L <= 3000; L++) {
        if (L > A[0]) break;
        int R = L;
        bool valid = true;
        for (int j = 0; j < N; j++) {
            int lb = 1, ub = K;
            bool C(int x) {
                return L <= A[j] / x;
            }
            if (C(ub)) {
                lb = ub;
            } else {
                while (lb + 1 < ub) {
                    int mid = (lb + ub) / 2;
                    (C(mid) ? lb : ub) = mid;
                }
            }
            R = max(R, A[j] / lb);
        }
        if (R - L < cur_len) {
            cur_len = R - L;
            ans = [L, R];
        }
    }
    writeln(cur_len);
}

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

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

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

    //writefln("-- %s %s ---", N, K);
    int[] xs;
    for (int i = 0; i < N; i++) {
        xs ~= A[i] / K;
        xs ~= A[i];
    }
    xs = xs.sort.uniq.array;
    int cur_len = int.max;
    int[] ans;
    for (int i = 0; i < xs.length; i++) {
        int L = xs[i];
        if (L > A[0]) break;
        int R = L;
        bool valid = true;
        for (int j = 0; j < N; j++) {
            bool found = false;
            for (int x = K; x >= 1; x--) {
                if (L <= A[j] / x) {
                    R = max(R, A[j] / x);
                    found = true;
                    break;
                }
            }
            if (!found) {
                valid = false;
                break;
            }
        }
        if (valid && R - L < cur_len) {
            cur_len = R - L;
            ans = [L, R];
        }
    }
    writeln(cur_len);
}

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

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

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

    //writefln("-- %s %s ---", N, K);
    int[] xs;
    for (int i = 0; i < N; i++) {
        xs ~= A[i] / K;
        xs ~= A[i];
    }
    xs = xs.sort.uniq.array;
    int cur_len = int.max;
    int[] ans;
    for (int i = 0; i < xs.length; i++) {
        int L = xs[i];
        if (L > A[0]) break;
        int R = L;
        for (int j = 0; j < N; j++) {
            for (int x = K; x >= 1; x--) {
                if (L <= A[j] / x) {
                    // ok
                    R = max(R, A[j] / x);
                    break;
                }
            }
        }
        if (R - L < cur_len) {
            cur_len = R - L;
            ans = [L, R];
        }
    }
    writeln(cur_len);
}

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


You are given an array $$$a$$$ of $$$n$$$ integers, where $$$n$$$ is odd. You can make the following operation with it:  Choose one of the elements of the array (for example $$$a_i$$$) and increase it by $$$1$$$ (that is, replace it with $$$a_i + 1$$$). You want to make the median of the array the largest possible using at most $$$k$$$ operations.The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $$$[1, 5, 2, 3, 5]$$$ is $$$3$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n$$$ is odd, $$$1 \le k \le 10^9$$$) — the number of elements in the array and the largest number of operations you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print a single integer — the maximum possible median after the operations.

NoteIn the first example, you can increase the second element twice. Than array will be $$$[1, 5, 5]$$$ and it's median is $$$5$$$.In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $$$3$$$.In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $$$[5, 1, 2, 5, 3, 5, 5]$$$ and the median will be $$$5$$$.

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 s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1].to!long;
    auto A = readln.split.map!(to!long).array;
    A.sort();

    long cnt = 1;
    long tmp = A[N/2];
    bool amari = true;

    for (int i = N/2; i < N-1; ++i, ++cnt) {
        long diff = A[i+1] - A[i];
        if (diff * cnt > K) {
            amari = false;
            break;
        }
        K -= diff * cnt;
        tmp = A[i+1];
    }

    if (amari) {
        tmp += K / cnt;
    } else {
        tmp = min(tmp + K / cnt, A[N/2+cnt.to!int]);
    }

    tmp.writeln;
}

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

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

    long cnt = 1;
    long tmp = A[N/2];
    bool amari = true;

    for (int i = N/2; i < N-1; ++i, ++cnt) {
        long diff = A[i+1] - A[i];
        if (diff * cnt > K) {
            amari = false;
            break;
        }
        K -= diff * cnt;
        tmp = A[i+1];
    }

    if (amari) {
        tmp += K / cnt;
    }

    tmp.writeln;
}


International Women's Day is coming soon! Polycarp is preparing for the holiday.There are $$$n$$$ candy boxes in the shop for sale. The $$$i$$$-th box contains $$$d_i$$$ candies.Polycarp wants to prepare the maximum number of gifts for $$$k$$$ girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $$$k$$$. In other words, two boxes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) can be combined as a gift if $$$d_i + d_j$$$ is divisible by $$$k$$$.How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 100$$$) — the number the boxes and the number the girls. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$), where $$$d_i$$$ is the number of candies in the $$$i$$$-th box.

Print one integer — the maximum number of the boxes Polycarp can give as gifts.

NoteIn the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(2, 3)$$$;  $$$(5, 6)$$$;  $$$(1, 4)$$$. So the answer is $$$6$$$.In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(6, 8)$$$;  $$$(2, 3)$$$;  $$$(1, 4)$$$;  $$$(5, 7)$$$. So the answer is $$$8$$$.In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(1, 2)$$$;  $$$(6, 7)$$$. So the answer is $$$4$$$.

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

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

    int[] d = new int[](k);

    foreach (i; 0 .. n) {
        int a;
        readf!" %s"(a);
        d[a%k]++;
    }

    int ans = d[0]/2*2;
    if (k % 2 == 0) {
        ans += d[k/2]/2*2;
    }
    foreach (i; 1 .. k) {
        if (i == k-i) continue;
        ans += min(d[i], d[k-i]);
    }

    writeln(ans);
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(x => x.to!int % K).array;

    auto cnt = new int[](K+1);
    foreach (a; A) cnt[a] += 1;

    int ans = 0;
    foreach (i; 0..K) {
        if (i * 2 % K == 0) {
            ans += cnt[i] / 2;
            cnt[i] /= 2;
        } else {
            int m = min(cnt[i], cnt[K-i]);
            ans += m;
            cnt[i] -= m;
            cnt[K-i] -= m;
        }
    }

    ans *= 2;
    ans.writeln;
}

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

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

    int[] d = new int[](k);

    foreach (i; 0 .. n) {
        int a;
        readf!" %s"(a);
        d[a%k]++;
    }

    int ans = d[0]/2*2;
    foreach (i; 1 .. k) {
        ans += min(d[i], d[k-i]);
    }

    writeln(ans);
}


After rejecting $$$10^{100}$$$ data structure problems, Errorgorn is very angry at Anton and decided to kill him.Anton's DNA can be represented as a string $$$a$$$ which only contains the characters "ANTON" (there are only $$$4$$$ distinct characters). Errorgorn can change Anton's DNA into string $$$b$$$ which must be a permutation of $$$a$$$. However, Anton's body can defend against this attack. In $$$1$$$ second, his body can swap $$$2$$$ adjacent characters of his DNA to transform it back to $$$a$$$. Anton's body is smart and will use the minimum number of moves.To maximize the chance of Anton dying, Errorgorn wants to change Anton's DNA the string that maximizes the time for Anton's body to revert his DNA. But since Errorgorn is busy making more data structure problems, he needs your help to find the best string $$$B$$$. Can you help him?

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 100000)$$$ — the number of testcases. The first and only line of each testcase contains $$$1$$$ string $$$a$$$ ($$$1 \leq |a| \leq 100000$$$). $$$a$$$ consists of only the characters "A", "N", "O" and "T". It is guaranteed that the sum of $$$|a|$$$ over all testcases does not exceed $$$100000$$$.

For each testcase, print a single string, $$$b$$$. If there are multiple answers, you can output any one of them. $$$b$$$ must be a permutation of the string $$$a$$$.

NoteFor the first testcase, it takes $$$7$$$ seconds for Anton's body to transform NNOTA to ANTON: NNOTA $$$\to$$$ NNOAT $$$\to$$$ NNAOT $$$\to$$$ NANOT $$$\to$$$ NANTO $$$\to$$$ ANNTO $$$\to$$$ ANTNO $$$\to$$$ ANTON. Note that you cannot output strings such as AANTON, ANTONTRYGUB, AAAAA and anton as it is not a permutation of ANTON.For the second testcase, it takes $$$2$$$ seconds for Anton's body to transform AANN to NAAN. Note that other strings such as NNAA and ANNA will also be accepted.

import std.stdio;
import std.ascii;
import std.algorithm;
import std.array;
import core.stdc.stdio;
int main()
{
    int t = readInt!int;
    while(t--)
    {
        string astr = readString;
        auto a = new int[](astr.length);
        auto count = new int[](4);
        foreach(i, ref ai; a)
        {
            switch(astr[i])
            {
            case 'A': ai = 0; break;
            case 'N': ai = 1; break;
            case 'T': ai = 2; break;
            case 'O': ai = 3; break;
            default: assert(0);
            }
            count[ai]++;
        }
        long minops = long.min;
        int[] minA;
        foreach(test; [[0, 1, 2, 3],[0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1],
                    [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0],
                    [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3], [2, 1, 3, 0], [2, 3, 0, 1], [2, 3, 1, 0],
                    [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]])
                    {
                        int[] testOrig;
                        foreach(ti; test)
                        {
                            foreach(i; 0 .. count[ti])
                            {
                                testOrig ~= ti;
                            }
                        }
                        long value = fixString(testOrig, a);
                        if (value > minops)
                        {
                            minops = value;
                            minA = testOrig;
                        }
                    }
        string mapi = "ANTO";
        string ans;
        foreach(ai; minA)
        {
            ans ~= mapi[ai];
        }
        writeln(ans);
    }
    return 0;
}

long fixString(int[] orig, int[] dest)
{
    int[][] pos = new int[][](4);
    auto ft = FT(cast(int)orig.length);
    foreach(i, a; dest)
    {
        pos[a] ~= cast(int) i;
    }
    long res = 0;
    foreach(i, a; orig)
    {
        int posCh = pos[a][0];
        pos[a] = pos[a][1 .. $];
        ft.add(posCh, 1);
        res += posCh - ft.sum(0, posCh - 1);
    }
    return res;
}
struct FT {
    int[] bit;
    int n;

    this(int n) {
        this.n = n;
        bit = new int[](n);
    }

    int sum(int r) {
        int ret = 0;
        for (; r >= 0; r = (r & (r + 1)) - 1)
            ret += bit[r];
        return ret;
    }

    int sum(int l, int r) {
        return sum(r) - sum(l - 1);
    }

    void add(int idx, int delta) {
        for (; idx < n; idx = idx | (idx + 1))
            bit[idx] += delta;
    }
};

/* INPUT ROUTINES */
int currChar;
static this()
{
    currChar = getchar();
}
char topChar()
{
    return cast(char) currChar;
}
void popChar()
{
    currChar = getchar();
}
auto readInt(T)()
{
    T num = 0;
    int sgn = 0;
    while (topChar.isWhite) popChar;
    while (topChar == '-' || topChar == '+') { sgn ^= (topChar == '-'); popChar; }
    while (topChar.isDigit) { num *= 10; num += (topChar - '0'); popChar; }
    if (sgn) return -num; return num;
}
string readString()
{
    string res = "";
    while (topChar.isWhite) popChar;
    while (!topChar.isWhite) { res ~= topChar; popChar; }
    return res;
}

import std.stdio;
import std.ascii;
import std.algorithm;
import std.array;
import core.stdc.stdio;
int main()
{
    int t = readInt!int;
    while(t--)
    {
        string astr = readString;
        auto a = new int[](astr.length);
        auto count = new int[](4);
        foreach(i, ref ai; a)
        {
            switch(astr[i])
            {
            case 'A': ai = 0; break;
            case 'N': ai = 1; break;
            case 'T': ai = 2; break;
            case 'O': ai = 3; break;
            default: assert(0);
            }
            count[ai]++;
        }
        long minops = long.min;
        int[] minA;
        foreach(test; [[0, 1, 2, 3],[0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1],
                    [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0],
                    [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3], [2, 1, 3, 0], [2, 3, 0, 1], [2, 3, 0, 1],
                    [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]])
                    {
                        int[] testOrig;
                        foreach(ti; test)
                        {
                            foreach(i; 0 .. count[ti])
                            {
                                testOrig ~= ti;
                            }
                        }
                        long value = fixString(testOrig, a);
                        if (value > minops)
                        {
                            minops = value;
                            minA = testOrig;
                        }
                    }
        string mapi = "ANTO";
        string ans;
        foreach(ai; minA)
        {
            ans ~= mapi[ai];
        }
        writeln(ans);
    }
    return 0;
}

long fixString(int[] orig, int[] dest)
{
    int[][] pos = new int[][](4);
    auto ft = FT(cast(int)orig.length);
    foreach(i, a; dest)
    {
        pos[a] ~= cast(int) i;
    }
    long res = 0;
    foreach(i, a; orig)
    {
        int posCh = pos[a][0];
        pos[a] = pos[a][1 .. $];
        ft.add(posCh, 1);
        res += posCh - ft.sum(0, posCh - 1);
    }
    return res;
}
struct FT {
    int[] bit;
    int n;

    this(int n) {
        this.n = n;
        bit = new int[](n);
    }

    int sum(int r) {
        int ret = 0;
        for (; r >= 0; r = (r & (r + 1)) - 1)
            ret += bit[r];
        return ret;
    }

    int sum(int l, int r) {
        return sum(r) - sum(l - 1);
    }

    void add(int idx, int delta) {
        for (; idx < n; idx = idx | (idx + 1))
            bit[idx] += delta;
    }
};

/* INPUT ROUTINES */
int currChar;
static this()
{
    currChar = getchar();
}
char topChar()
{
    return cast(char) currChar;
}
void popChar()
{
    currChar = getchar();
}
auto readInt(T)()
{
    T num = 0;
    int sgn = 0;
    while (topChar.isWhite) popChar;
    while (topChar == '-' || topChar == '+') { sgn ^= (topChar == '-'); popChar; }
    while (topChar.isDigit) { num *= 10; num += (topChar - '0'); popChar; }
    if (sgn) return -num; return num;
}
string readString()
{
    string res = "";
    while (topChar.isWhite) popChar;
    while (!topChar.isWhite) { res ~= topChar; popChar; }
    return res;
}

import std.stdio;
import std.ascii;
import std.algorithm;
import std.array;
import core.stdc.stdio;
int main()
{
    int t = readInt!int;
    while(t--)
    {
        string astr = readString;
        auto a = new int[](astr.length);
        auto count = new int[](4);
        foreach(i, ref ai; a)
        {
            switch(astr[i])
            {
            case 'A': ai = 0; break;
            case 'N': ai = 1; break;
            case 'T': ai = 2; break;
            case 'O': ai = 3; break;
            default: assert(0);
            }
            count[ai]++;
        }
        long minops = long.max;
        int[] minA;
        foreach(test; [[0, 1, 2, 3],[0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1],
                    [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0],
                    [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3], [2, 1, 3, 0], [2, 3, 0, 1], [2, 3, 0, 1],
                    [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]])
                    {
                        int[] testOrig;
                        foreach(ti; test)
                        {
                            foreach(i; 0 .. count[ti])
                            {
                                testOrig ~= ti;
                            }
                        }
                        long value = fixString(testOrig, a);
                        if (value < minops)
                        {
                            minops = value;
                            minA = testOrig;
                        }
                    }
        string mapi = "ANTO";
        string ans;
        foreach(ai; minA)
        {
            ans ~= mapi[ai];
        }
        writeln(ans);
    }
    return 0;
}

long fixString(int[] orig, int[] dest)
{
    int[][] pos = new int[][](4);
    auto ft = FT(cast(int)orig.length);
    foreach(i, a; dest)
    {
        pos[a] ~= cast(int) i;
    }
    long res = 0;
    foreach(i, a; orig)
    {
        int posCh = pos[a][0];
        pos[a] = pos[a][1 .. $];
        ft.add(posCh, 1);
        res += posCh - ft.sum(0, posCh - 1);
    }
    return res;
}
struct FT {
    int[] bit;
    int n;

    this(int n) {
        this.n = n;
        bit = new int[](n);
    }

    int sum(int r) {
        int ret = 0;
        for (; r >= 0; r = (r & (r + 1)) - 1)
            ret += bit[r];
        return ret;
    }

    int sum(int l, int r) {
        return sum(r) - sum(l - 1);
    }

    void add(int idx, int delta) {
        for (; idx < n; idx = idx | (idx + 1))
            bit[idx] += delta;
    }
};

/* INPUT ROUTINES */
int currChar;
static this()
{
    currChar = getchar();
}
char topChar()
{
    return cast(char) currChar;
}
void popChar()
{
    currChar = getchar();
}
auto readInt(T)()
{
    T num = 0;
    int sgn = 0;
    while (topChar.isWhite) popChar;
    while (topChar == '-' || topChar == '+') { sgn ^= (topChar == '-'); popChar; }
    while (topChar.isDigit) { num *= 10; num += (topChar - '0'); popChar; }
    if (sgn) return -num; return num;
}
string readString()
{
    string res = "";
    while (topChar.isWhite) popChar;
    while (!topChar.isWhite) { res ~= topChar; popChar; }
    return res;
}


An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens:   initially the atom is in the state i, we spend Ek - Ei energy to put the atom in the state k, the atom emits a photon with useful energy Ek - Ej and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ej - Ei, the process repeats from step 1. Let's define the energy conversion efficiency as , i. e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ek - Ei ≤ U.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.

The first line contains two integers n and U (3 ≤ n ≤ 105, 1 ≤ U ≤ 109) — the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1, E2, ..., En (1 ≤ E1 < E2... < En ≤ 109). It is guaranteed that all Ei are given in increasing order.

If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number η — the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to .

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, u; readV(n, u);
  int[] e; readA(n, e);
  auto es = e.assumeSorted;

  auto y = -1.0L;
  foreach (i; 0..n-2) {
    if (e[i+2]-e[i] > u) continue;
    auto ei = e[i], ej = e[i+1];
    auto ek = es.lowerBound(ei+u+1).back;
    y = max(y, (ek-ej).to!real/(ek-ei));
  }

  if (y < 0)
    writeln(-1);
  else
    writefln("%.10f", y);
}

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T t){t=new T(n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(ElementType!T);r.popFront;}}
void readM(T...)(size_t n,ref T t){foreach(ref v;t)v=new typeof(v)(n);foreach(i;0..n){auto r=readln.splitter;foreach(ref v;t){v[i]=r.front.to!(ElementType!(typeof(v)));r.popFront;}}}
void readS(T)(size_t n,ref T t){t=new T(n);foreach(ref v;t){auto r=readln.splitter;foreach(ref j;v.tupleof){j=r.front.to!(typeof(j));r.popFront;}}}

void main()
{
  int n, u; readV(n, u);
  int[] e; readA(n, e);
  auto es = e.assumeSorted;

  auto y = -1.0L;
  foreach (i; 0..n-2) {
    if (e[i+2]-e[i] > u) continue;
    auto ei = e[i], ej = e[i+1];
    auto ek = es.lowerBound(ei+u+1).back;
    y = max(y, (ek-ej).to!real/(ek-ei));
  }

  if (y < 0)
    writeln(-1);
  else
    writefln("%.10f", y);
}

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 U = readLong();
      auto E = new long[N];
      foreach (i; 0 .. N) {
        E[i] = readLong();
      }

      real ans = -1.0L;
      foreach (i; 0 .. N - 1) {
        const j = i + 1;
        const k = E.upperBound(E[i] + U) - 1;
        if (j < k) {
          chmax(ans, cast(real)(E[k] - E[j]) / (E[k] - E[i]));
        }
      }
      if (ans < 0) {
        writeln(-1);
      } else {
        writefln("%.10f", ans);
      }
    }
  } catch (EOFException e) {
  }
}


One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai rating units as a present.The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.Help site X cope with the challenging task of rating distribution. Find the optimal distribution.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of users on the site. The next line contains integer sequence a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a sequence of integers b1, b2, ..., bn. Number bi means that user i gets bi of rating as a present. The printed sequence must meet the problem conditions.  If there are multiple optimal solutions, print any of them.

import std.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;

void main() {
    int n; readf("%d\n", &n);
    int[] as = readln.chomp.split(" ").map!(to!int).array;
    int[int] x;
    foreach (a; as) {
        x[a]++;
    }
    auto bs = redBlackTree!int([]);
    foreach (a; as) {
        int b = a + 1;
        if (!x.get(b, 0)) bs.insert(b);
    }
    int[] r = as.dup;
    foreach (i, a; as) {
        if (x[a] > 1) {
            int b = bs.upperBound(a).front;
            bs.removeKey(b);
            r[i] = b;
            x[a]--;
            if (!x.get(b + 1, 0)) bs.insert(b + 1);
        }
    }
    write(r[0]);
    foreach (e; r[1 .. $]) {
        write(" ", e);
    }
    write("\n");
}

import std.stdio, std.algorithm;

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

    auto a = new int[2][n];
    foreach(i; 0..n) {
        readf(" %d", &a[i][0]);
        a[i][1] = i;
    }
    sort!("a < b", SwapStrategy.stable)(a);

    auto b = new int[n];
    foreach(i; 0..n) {
        b[a[i][1]] = max(a[i][0], i > 0 ? b[a[i-1][1]]+1 : 0);
    }

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

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;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}

		alias Tuple !(int, "x", int, "k") pair;
		pair [] c;
		foreach (i, x; a)
		{
			c ~= pair (x, i);
		}
		sort !("a < b", SwapStrategy.stable) (c);

		int [int] p;
		foreach (e; c)
		{
			int x = e.x;
			while (x in p)
			{
				x = p[x];
			}
			a[e.k] = x;
			p[x] = x + 1;
			int y = e.x;
			while (y in p)
			{
				int z = p[y];
				p[y] = x + 1;
				y = z;
			}
		}

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

import std.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;

void main() {
    int n; readf("%d\n", &n);
    int[] as = readln.chomp.split(" ").map!(to!int).array;
    int[int] x;
    foreach (a; as) {
        x[a]++;
    }
    auto bs = redBlackTree!int([]);
    foreach (a; as) {
        int b = a + 1;
        if (!x.get(b, 0)) bs.insert(b);
    }
    int[] r = as.dup;
    foreach (i, a; as) {
        if (x[a] > 1) {
            int b = bs.upperBound(a).front;
            bs.removeKey(b);
            bs.insert(b + 1);
            r[i] = b;
            x[a]--;
        }
    }
    r.map!(to!string).join(" ").writeln;
}


Vlad, like everyone else, loves to sleep very much.Every day Vlad has to do $$$n$$$ things, each at a certain time. For each of these things, he has an alarm clock set, the $$$i$$$-th of them is triggered on $$$h_i$$$ hours $$$m_i$$$ minutes every day ($$$0 \le h_i < 24, 0 \le m_i < 60$$$). Vlad uses the $$$24$$$-hour time format, so after $$$h=12, m=59$$$ comes $$$h=13, m=0$$$ and after $$$h=23, m=59$$$ comes $$$h=0, m=0$$$.This time Vlad went to bed at $$$H$$$ hours $$$M$$$ minutes ($$$0 \le H < 24, 0 \le M < 60$$$) and asks you to answer: how much he will be able to sleep until the next alarm clock.If any alarm clock rings at the time when he went to bed, then he will sleep for a period of time of length $$$0$$$.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the test. The first line of the case contains three integers $$$n$$$, $$$H$$$ and $$$M$$$ ($$$1 \le n \le 10, 0 \le H < 24, 0 \le M < 60$$$) — the number of alarms and the time Vlad went to bed. The following $$$n$$$ lines contain two numbers each $$$h_i$$$ and $$$m_i$$$ ($$$0 \le h_i < 24, 0 \le m_i < 60$$$) — the time of the $$$i$$$ alarm. It is acceptable that two or more alarms will trigger at the same time. Numbers describing time do not contain leading zeros.

Output $$$t$$$ lines, each containing the answer to the corresponding test case. As an answer, output two numbers  — the number of hours and minutes that Vlad will sleep, respectively. If any alarm clock rings at the time when he went to bed, the answer will be 0 0.

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    long n;
    foreach(_; 0..t)
    {
        auto s = readln.split.to!(int[]);
        TimeOfDay[] less;
        TimeOfDay[] more;
        int min_ind;
        foreach(i; 0..s[0]) {
            auto tmp = readln.split.to!(int[]);
            if ((tmp[0] < s[1]) || ((tmp[0] == s[1]) && (tmp[1] < s[2])))
                less ~= TimeOfDay(tmp[0],tmp[1]);
            else
                more ~= TimeOfDay(tmp[0],tmp[1]);
        }
        if (more.length > 0) {
            auto tmpMin = minElement(more) - TimeOfDay(s[1],s[2]);
            writeln(tmpMin.split.hours, " ", tmpMin.split.minutes);
        }
        else {
            auto tmpMin = minElement(less) + (TimeOfDay(0,0) - TimeOfDay(s[1],s[2]));
            writeln(tmpMin.hour, " ", tmpMin.minute);
        }
    }
}