Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of $$$n$$$ different weapons and exactly one of $$$m$$$ different armor sets. Weapon $$$i$$$ has attack modifier $$$a_i$$$ and is worth $$$ca_i$$$ coins, and armor set $$$j$$$ has defense modifier $$$b_j$$$ and is worth $$$cb_j$$$ coins.After choosing his equipment Roma can proceed to defeat some monsters. There are $$$p$$$ monsters he can try to defeat. Monster $$$k$$$ has defense $$$x_k$$$, attack $$$y_k$$$ and possesses $$$z_k$$$ coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster $$$k$$$ can be defeated with a weapon $$$i$$$ and an armor set $$$j$$$ if $$$a_i > x_k$$$ and $$$b_j > y_k$$$. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.

The first line contains three integers $$$n$$$, $$$m$$$, and $$$p$$$ ($$$1 \leq n, m, p \leq 2 \cdot 10^5$$$) — the number of available weapons, armor sets and monsters respectively. The following $$$n$$$ lines describe available weapons. The $$$i$$$-th of these lines contains two integers $$$a_i$$$ and $$$ca_i$$$ ($$$1 \leq a_i \leq 10^6$$$, $$$1 \leq ca_i \leq 10^9$$$) — the attack modifier and the cost of the weapon $$$i$$$. The following $$$m$$$ lines describe available armor sets. The $$$j$$$-th of these lines contains two integers $$$b_j$$$ and $$$cb_j$$$ ($$$1 \leq b_j \leq 10^6$$$, $$$1 \leq cb_j \leq 10^9$$$) — the defense modifier and the cost of the armor set $$$j$$$. The following $$$p$$$ lines describe monsters. The $$$k$$$-th of these lines contains three integers $$$x_k, y_k, z_k$$$ ($$$1 \leq x_k, y_k \leq 10^6$$$, $$$1 \leq z_k \leq 10^3$$$) — defense, attack and the number of coins of the monster $$$k$$$.

Print a single integer — the maximum profit of the grind.

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

// T, S: monoid
// opTT: T * T -> T
// opST: S * T * int -> T
//   (s t_a) ... (s t_{b-1}) = opST(s, t_a ... t_{b-1}, b - a)
// opSS: S * S -> S
// query(a, b, s): t_a <- s t_a, ..., t_{b-1} <- s t_{b-1};
//   returns t_a ... t_{b-1}
class SegmentTree(T, S, alias opTT, alias opST, alias opSS) {
  import std.functional : binaryFun;
  alias opTTFun = binaryFun!opTT;
  alias opSTFun = opST;
  alias opSSFun = binaryFun!opSS;
  const(T) idT;
  const(S) idS;

  int n;
  T[] ts;
  S[] ss;
  this(int n_, const(T) idT, const(S) idS) {
    this.idT = idT;
    this.idS = idS;
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ss = new S[n << 1];
    ts[] = idT;
    ss[] = idS;
  }
  ref T at(int a) {
    return ts[n + a];
  }
  void build() {
    foreach_reverse (a; 1 .. n) ts[a] = opTTFun(ts[a << 1], ts[a << 1 | 1]);
  }
  T query(int a, int b, const(S) s) {
    return query(1, 0, n, a, b, s);
  }

 private:
  T query(int u, int l, int r, int a, int b, const(S) s) {
    if (a < l) a = l;
    if (b > r) b = r;
    if (a >= b) return idT;
    if (a == l && b == r) {
      ts[u] = opSTFun(s, ts[u], r - l);
      ss[u] = opSSFun(s, ss[u]);
      return ts[u];
    }
    const int uL = u << 1, uR = u << 1 | 1;
    const int mid = (l + r) >> 1;
    // speed-up: if (ss[u] != idS)
    {
      ts[uL] = opSTFun(ss[u], ts[uL], mid - l);
      ts[uR] = opSTFun(ss[u], ts[uR], r - mid);
      ss[uL] = opSSFun(ss[u], ss[uL]);
      ss[uR] = opSSFun(ss[u], ss[uR]);
      ss[u] = idS;
    }
    const T resL = query(uL, l, mid, a, b, s);
    const T resR = query(uR, mid, r, a, b, s);
    ts[u] = opTTFun(ts[uL], ts[uR]);
    return opTTFun(resL, resR);
  }
}

enum INF = 10L^^18;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      const P = readInt();
      auto A = new int[N];
      auto CA = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
        CA[i] = readLong();
      }
      auto B = new int[M];
      auto CB = new long[M];
      foreach (j; 0 .. M) {
        B[j] = readInt();
        CB[j] = readLong();
      }
      auto X = new int[P];
      auto Y = new int[P];
      auto Z = new long[P];
      foreach (k; 0 .. P) {
        X[k] = readInt();
        Y[k] = readInt();
        Z[k] = readLong();
      }

      const E = A.maxElement + 1;
      const F = B.maxElement + 1;
      auto iss = new int[][E];
      foreach (i; 0 .. N) {
        iss[A[i]] ~= i;
      }
      auto kss = new int[][E];
      foreach (k; 0 .. P) {
        kss[X[k]] ~= k;
      }

      auto seg = new SegmentTree!(long, long, max, (s, t, sz) => (s + t), "a + b")(F, -INF, 0);
      auto mxs = new long[F];
      mxs[] = -INF;
      foreach (j; 0 .. M) {
        chmax(mxs[B[j] - 1], -CB[j]);
      }
      foreach_reverse (f; 0 .. F - 1) {
        chmax(mxs[f], mxs[f + 1]);
      }
      debug {
        writeln("mxs = ", mxs);
      }
      foreach (f; 0 .. F) {
        seg.at(f) = mxs[f];
      }
      seg.build;

      long ans = -INF;
      foreach (e; 0 .. E) {
        foreach (i; iss[e]) {
          const res = seg.query(0, F, 0);
          const score = -CA[i] + res;
          debug {
            writeln("res = ", res, ", score = ", score);
          }
          chmax(ans, score);
        }
        foreach (k; kss[e]) {
          debug {
            writeln("add ", Y[k], " ", Z[k]);
          }
          seg.query(Y[k], F, Z[k]);
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are given a string $$$s$$$, consisting of lowercase Latin letters. Every letter appears in it no more than twice.Your task is to rearrange the letters in the string in such a way that for each pair of letters that appear exactly twice, the distance between the letters in the pair is the same. You are not allowed to add or remove letters.It can be shown that the answer always exists. If there are multiple answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases. Each testcase consists of a non-empty string $$$s$$$, consisting of lowercase Latin letters. Every letter appears in the string no more than twice. The length of the string doesn't exceed $$$52$$$.

For each testcase, print a single string. Every letter should appear in it the same number of times as it appears in string $$$s$$$. For each pair of letters that appear exactly twice, the distance between the letters in the pair should be the same. If there are multiple answers, print any of them.

NoteIn the first testcase of the example, the only letter that appears exactly twice is letter 'l'. You can rearrange the letters arbitrarily, since there are no distances to compare.In the second testcase of the example, the letters that appear exactly twice are 'a', 'b' and 'c'. Initially, letters 'a' are distance $$$6$$$ apart, letters 'b' are distance $$$4$$$ apart and letters 'c' are distance $$$2$$$ apart. They are not the same, so we have to rearrange the letters. After rearrangement, letters 'a' are distance $$$2$$$ apart, letters 'b' are distance $$$2$$$ apart and letters 'c' are distance $$$2$$$ apart. They are all the same, so the answer is valid.In the third testcase of the example, there are no letters that appear exactly twice. Thus, any rearrangement is valid. Including not changing the string at all.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		readln.strip.array.sort.text.writeln;
	}
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;
      int[char] counts;
      foreach(c; S) counts[c]++;

      string ans;
      foreach(c, count; counts) {
        if (count == 2) ans ~= c;
      }

      ans ~= ans;
      foreach(c, count; counts) {
        if (count == 1) ans ~= c;
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

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

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int[] s = readln.strip.dup.map!(x => cast(int)x).array;
    s.sort;
    writeln(s.map!(x => cast(char)x).array.idup);
  }
}


Alice has just learned addition. However, she hasn't learned the concept of "carrying" fully — instead of carrying to the next column, she carries to the column two columns to the left.For example, the regular way to evaluate the sum $$$2039 + 2976$$$ would be as shown:   However, Alice evaluates it as shown:   In particular, this is what she does:   add $$$9$$$ and $$$6$$$ to make $$$15$$$, and carry the $$$1$$$ to the column two columns to the left, i. e. to the column "$$$0$$$ $$$9$$$";  add $$$3$$$ and $$$7$$$ to make $$$10$$$ and carry the $$$1$$$ to the column two columns to the left, i. e. to the column "$$$2$$$ $$$2$$$";  add $$$1$$$, $$$0$$$, and $$$9$$$ to make $$$10$$$ and carry the $$$1$$$ to the column two columns to the left, i. e. to the column above the plus sign;  add $$$1$$$, $$$2$$$ and $$$2$$$ to make $$$5$$$;  add $$$1$$$ to make $$$1$$$.  Thus, she ends up with the incorrect result of $$$15005$$$.Alice comes up to Bob and says that she has added two numbers to get a result of $$$n$$$. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $$$n$$$. Note that pairs $$$(a, b)$$$ and $$$(b, a)$$$ are considered different if $$$a \ne b$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 10^9$$$) — the number Alice shows Bob.

For each test case, output one integer — the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $$$n$$$.

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

long solve(long n)
{
  long odd, even;
  long mult = 1;
  while (n > 0) {
    long odddigit = n % 10;
    n /= 10;
    long evendigit = n % 10;
    n /= 10;
    odd += odddigit * mult;
    even += evendigit * mult;
    mult *= 10;
  }
  return (odd + 1) * (even + 1) - 2;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    writeln(solve(n));
  }
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!long;
	int[10] digs;
	foreach(i, ref di; digs)
	{
		di = n%10;
		n/=10;
	}
	debug writeln(digs);
	auto ans = 0L;
	void consider(int carry)
	{
		if (carry&0b11) return;
		int carryAt(int i)
		{
			return int((carry & (1 << i)) != 0);
		}
		long ways = 1;
		foreach(i; 0 .. 10)
		{
			if (carryAt(i+2))
			{
				auto d = digs[i];
				// x1+ci + x2 >= 10
				// (x1+x2)%10 == d
				// if (x1+ci > d) x2 is set, x1+ci + x2 >= 10
				// x1+ci > d x1+ci+9
				long w = void;
				// x1+ci+x2 = 10+d
				// x2 = 10+d-x1-ci
				// x2 >= 0 10+d-x1-ci >= 0 x1 <=
				// x2 < 10 10+d-x1-ci < 10
				// d-x1-ci < 0
				long l = d-carryAt(i)+1;
				long h = 9;
				if (l <= h) w = h-l+1;
				else w = 0;
				ways *= w;
			}
			else
			{
				auto d = digs[i];
				long w = void;
				//x1+ci+x2 = d
				// x2 = d-x1-ci
				// x2 >= 0 -> d-x1-ci >= 0 -> x1 <= d-ci
				// x2 < 10 -> d-x1-ci < 10 -> x1 > d-ci-10
				long l = 0;
				long h = d-carryAt(i);
				if (l <= h) w = h-l+1;
				else w = 0;
				ways *= w;
			}
		}
		ans += ways;
	}
	foreach(int carry; 0 .. (1<<8))
	{
		consider(carry<<2);
	}
	writeln(ans-2);
}

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

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

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

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

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		foreach (i; 0..2^^n.length)
		{
			if (i >> max(0, cast(int)(n.length)-2)) continue;
			long cnt = 1;
			foreach (j; 0..n.length)
			{
				long x = n[j] - '0';
				if (j >= 2)
					if (i & (1L << (j-2)))
						--x;

				long c;
				if (i & (1L << j))
					x += 10;
				foreach (k; 0..10)
				{
					if (inside(x - k, 0, 10))
					{
						++c;
						debug writeln("i:", i, " j:", j, " x:", x, " k:", k);
					}
				}
				cnt *= c;
			}
			if (i == 0)
			{
				if (cnt != 0)
					ans[ti] += cnt-2;
			}
			else
				ans[ti] += cnt;
		}
	}

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


Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $$$n$$$ stations, enumerated from $$$1$$$ through $$$n$$$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $$$i$$$ is station $$$i+1$$$ if $$$1 \leq i < n$$$ or station $$$1$$$ if $$$i = n$$$. It takes the train $$$1$$$ second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver $$$m$$$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $$$1$$$ through $$$m$$$. Candy $$$i$$$ ($$$1 \leq i \leq m$$$), now at station $$$a_i$$$, should be delivered to station $$$b_i$$$ ($$$a_i \neq b_i$$$).    The blue numbers on the candies correspond to $$$b_i$$$ values. The image corresponds to the $$$1$$$-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.

The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 5\,000$$$; $$$1 \leq m \leq 20\,000$$$) — the number of stations and the number of candies, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$; $$$a_i \neq b_i$$$) — the station that initially contains candy $$$i$$$ and the destination station of the candy, respectively.

In the first and only line, print $$$n$$$ space-separated integers, the $$$i$$$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $$$i$$$.

NoteConsider the second sample.If the train started at station $$$1$$$, the optimal strategy is as follows.  Load the first candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the first candy.  Proceed to station $$$1$$$. This step takes $$$1$$$ second.  Load the second candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the second candy.  Proceed to station $$$1$$$. This step takes $$$1$$$ second.  Load the third candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the third candy. Hence, the train needs $$$5$$$ seconds to complete the tasks.If the train were to start at station $$$2$$$, however, it would need to move to station $$$1$$$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $$$5+1 = 6$$$ seconds.

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

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

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

    auto cnt = new int[] (n);
    auto dst = new int[] (n);

    foreach (_; 0 .. m) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        --a, --b;
        cnt[a] += 1;
        int closest = b - a + (b < a ? n : 0);
        dst[a] = dst[a] == 0 ? closest : min(dst[a], closest);
    }

    debug { writeln(dst, ' ', cnt); }

    int[] ans;

    foreach (st; 0 .. n) {
        int cur = 0;
        foreach (mv; 0 .. n) {
            int pos = (st + mv) % n;
            cur = max(cur, mv + (cnt[pos] - 1) * n + dst[pos]);
        }

        ans ~= cur;
    }

    ans.writefln!"%(%s %)";
}

import std.conv, std.functional, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.numeric, std.range, 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)); }

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

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

      auto cnt = new int[N];
      auto mn = new int[N];
      mn[] = N;
      foreach (i; 0 .. M) {
        ++cnt[A[i]];
        chmin(mn[A[i]], (B[i] - A[i] + N) % N);
      }

      foreach (x; 0 .. N) {
        int ans;
        foreach (y; 0 .. N) {
          if (cnt[y] > 0) {
            chmax(ans, (y - x + N) % N + (cnt[y] - 1) * N + mn[y]);
          }
        }
        if (x > 0) {
          write(" ");
        }
        write(ans);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


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

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

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

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

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

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

    auto cnt = new int[](10);
    int ans = 0;
    int day = 0;

    foreach (a; A) {
        ++day;
        cnt[a] += 1;
        foreach (j; 0..10) {
            if (cnt[j] == 0) continue;
            cnt[j] -= 1;
            if (cnt.filter!(x => x != 0).empty || cnt.reduce!max == cnt.filter!(x => x != 0).reduce!min) {
                ans = day;
            }
            cnt[j] += 1;
        }

    }

    ans.writeln;
}

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

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

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

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

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

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

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

	}

	bestx.writeln;

}

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

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

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

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

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

	int bestx = 1;
	int[] ucnt = new int[](10);
	foreach(i; 0 .. n){
		int u = us[i];
		ucnt[u] += 1;
		if(isOk(ucnt)) bestx = i + 1;
	}

	bestx.writeln;

}

bool isOk(int[] ucnt){
	int[int] countcnt;
	foreach(u; 0 .. 10){
		if(ucnt[u] == 0) continue;
		if(!ucnt[u] in countcnt) countcnt[ucnt[u]] = 0;
		countcnt[ucnt[u]] += 1;
	}

	print!1(countcnt);

	int[] ks = countcnt.keys;
	if(ks.length == 1){
		if(ks[0] == 1) return 1;
	}
	else if(ks.length == 2){
		if(ks[0] > ks[1]){
			if(ks[0] - ks[1] == 1 && countcnt[ks[0]] == 1) return 1;
			if(ks[1] == 1 && countcnt[ks[1]] == 1) return 1;
		}
		if(ks[0] < ks[1]){
			if(ks[1] - ks[0] == 1 && countcnt[ks[1]] == 1) return 1;
			if(ks[0] == 1 && countcnt[ks[0]] == 1) return 1;
		}
	}

	return 0;
}

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

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

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

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

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

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

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

	}

	bestx.writeln;

}

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

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

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

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

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

	int bestx = 1;
	int[] ucnt = new int[](10);
	foreach(i; 0 .. n){
		int u = us[i];
		ucnt[u] += 1;
		if(isOk(ucnt)) bestx = i + 1;
	}

	bestx.writeln;

}

bool isOk(int[] ucnt){
	int[int] countcnt;
	foreach(u; 0 .. 10){
		if(ucnt[u] == 0) continue;
		if(!ucnt[u] in countcnt) countcnt[ucnt[u]] = 1;
		countcnt[ucnt[u]] += 1;
	}

	print!1(countcnt);

	int[] ks = countcnt.keys;
	if(ks.length == 1){
		if(ks[0] == 1) return 1;
	}
	else if(ks.length == 2){
		if(ks[0] > ks[1]){
			if(ks[0] - ks[1] == 1 && countcnt[ks[0]] == 1) return 1;
			if(ks[1] == 1 && countcnt[ks[1]] == 1) return 1;
		}
		if(ks[0] < ks[1]){
			if(ks[1] - ks[0] == 1 && countcnt[ks[1]] == 1) return 1;
			if(ks[0] == 1 && countcnt[ks[0]] == 1) return 1;
		}
	}

	return 0;
}


The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:   ti < ti + 1 for each odd i < n;  ti > ti + 1 for each even i < n. For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.Bear Limak has a sequence of positive integers t1, t2, ..., tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.

The first line of the input contains one integer n (2 ≤ n ≤ 150 000) — the length of the sequence. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 150 000) — the initial sequence. It's guaranteed that the given sequence is not nice.

Print the number of ways to swap two elements exactly once in order to get a nice sequence.

NoteIn the first sample, there are two ways to get a nice sequence with one swap:   Swap t2 = 8 with t4 = 7.  Swap t1 = 2 with t5 = 7. In the second sample, there is only one way — Limak should swap t1 = 200 with t4 = 50.

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.math;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);

  auto n = next!int;
  auto t = next!int(n);
  auto badpos = redBlackTree!int();
  foreach(i; 0 .. n - 1)
    {
      if (i % 2 == 0)
	{
	  if (t[i] >= t[i + 1])
	    badpos.insert(i), badpos.insert(i + 1);
	}
      else
	{
	  if (t[i] <= t[i + 1])
	    badpos.insert(i), badpos.insert(i + 1);
	}
    }
  bool isgood(int i)
  {
    if (i < 0 || i >= n - 1) return true;
    if (i % 2 == 0) return t[i] < t[i + 1];
    return t[i] > t[i + 1];
  }
  if (badpos.length > 6) return 0.writeln;
  auto swaps = redBlackTree!(Tuple!(int, int))();
  foreach(i; badpos)
    {
      foreach(j; 0 .. n)
	{
	  swap(t[i], t[j]);
	  if (isgood(i) && isgood(i - 1) && isgood(i + 1)
	      && isgood(j) && isgood(j - 1) && isgood(j + 1))
	    {
	      bool good = true;
	      foreach(b; badpos)
		if (abs(b - i) > 1 && abs(b - j) > 1)
		  good = false;
	      if (good)
		swaps.insert(tuple(min(i, j), max(i, j)));
	    }
	  swap(t[i], t[j]);
	}
    }
  swaps.length.writeln;
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.Ivar has $$$n$$$ warriors, he places them on a straight line in front of the main gate, in a way that the $$$i$$$-th warrior stands right after $$$(i-1)$$$-th warrior. The first warrior leads the attack.Each attacker can take up to $$$a_i$$$ arrows before he falls to the ground, where $$$a_i$$$ is the $$$i$$$-th warrior's strength.Lagertha orders her warriors to shoot $$$k_i$$$ arrows during the $$$i$$$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $$$t$$$, they will all be standing to fight at the end of minute $$$t$$$.The battle will last for $$$q$$$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \leq 200\,000$$$) — the number of warriors and the number of minutes in the battle. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) that represent the warriors' strengths. The third line contains $$$q$$$ integers $$$k_1, k_2, \ldots, k_q$$$ ($$$1 \leq k_i \leq 10^{14}$$$), the $$$i$$$-th of them represents Lagertha's order at the $$$i$$$-th minute: $$$k_i$$$ arrows will attack the warriors.

Output $$$q$$$ lines, the $$$i$$$-th of them is the number of standing warriors after the $$$i$$$-th minute.

NoteIn the first example:   after the 1-st minute, the 1-st and 2-nd warriors die.  after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 — all warriors are alive.  after the 3-rd minute, the 1-st warrior dies.  after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1.  after the 5-th minute, the 2-nd warrior dies.

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

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

    auto s = new long[n];

    long cs = 0;

    foreach(ref v; s)
    {
        long t;
        readf(" %s", t);
        cs += t;
        v = cs;
    }

    auto sorted = assumeSorted(s);

    cs = 0;

    foreach (_; 0 .. q)
    {
        long t;
        readf(" %s", t);
        cs += t;

        if (cs < s.back)
        {
            writeln(sorted.upperBound(cs).length);
        }
        else
        {
            writeln(s.length);
            cs = 0;
        }
    }
}

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

void main()
{
	int n, q;
	readln.chomp.split.tie(n, q);
	ulong[] a = readln.chomp.split.map!(to!ulong).array;
	ulong[] k = readln.chomp.split.map!(to!ulong).array;

	ulong[] b = new ulong[](n);
	b[0] = a[0];
	for (int i = 1; i < n; ++i) {
		b[i] = b[i - 1] + a[i];
	}
	auto c = b.assumeSorted;
	ulong l = 0;
	OutBuffer buf = new OutBuffer();
	foreach (v; k) {
		l += v;
		debug verbose(l, c.upperBound(l));
		auto remain = c.upperBound(l).length;
		if (remain == 0) {
			l = 0;
			remain = n;
		}
		buf.writeln = remain;
	}
	buf.toString.write;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

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

void main()
{
    readln;
    auto a = readln.splitter.map!(to!ulong).cumulativeFold!((a,b) => a+b).array;
    auto q = readln.splitter.map!(to!ulong).array;

    debug { writeln(a); writeln(q); }

    ulong cur = 0;
    ulong [] ans;
    foreach (order; q) {
        cur += order;
        auto rng = a.assumeSorted.upperBound(cur);
        ans ~= rng.length > 0 ? rng.length : a.length;
        if (rng.length == 0) cur = 0;
    }

    ans.each!writeln;
}

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

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

void main()
{
  int n, q; readV(n, q);
  long[] a; readA(n, a);
  long[] k; readA(q, k);

  foreach (i; 1..n) a[i] += a[i-1];
  auto as = a.assumeSorted;

  auto t = 0L;
  foreach (ki; k) {
    t += ki;
    if (t >= as.back) t = 0;
    writeln(as.upperBound(t).length);
  }
}

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

  int n, q; rd(n, q);
  auto as=readln.split.to!(long[]);
  auto bs=readln.split.to!(long[]);
  auto sub=new long[](n+1); // sum(as[l, r])=sub[r]-sub[l-1]; 1-indexed
  foreach(i; 0..n) sub[i+1]=sub[i]+as[i];
  int pos=1;
  long cur=0;
  foreach(b; bs){
    auto rem=(sub[pos]-sub[0])-cur;
    if(b<rem){
      writeln(n-pos+1);
      // writeln("a");
      cur+=b;
    }else{
      auto o=b-rem;
      if((sub[n]-sub[pos])<=o){
        writeln(n);
        // writeln("b");
        pos=1;
        cur=0;
      }else{
        auto tri=sub.assumeSorted.trisect(o+(sub[pos]-sub[0]));
        // if(tri[1].length>0){
        //   pos=tri[0].length+1;
        // }else{

        // }
        pos=(tri[0].length+tri[1].length).to!(int); // aaaaa
        writeln(n-pos+1);
        // writeln("c");
        cur+=b;
      }
    }
    // writeln("cur: ", cur);
    // writeln("pos: ", pos);
  }
}

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


Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n    input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF        //here INF is a number big enoughtot=0for i from 1 to n    for j from (i+1) to n        ++tot        if (p[j].x-p[i].x>=d) then break    //notice that "break" is only to be                                            //out of the loop "for j"        d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?

A single line which contains two space-separated integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ 109).

If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≤ 109) representing the coordinates of the i-th point. The conditions below must be held:   All the points must be distinct.  |xi|, |yi| ≤ 109.  After running the given code, the value of tot should be larger than k.

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		int t = n * (n - 1) / 2;
		if (t <= k)
		{
			writeln ("no solution");
		}
		else
		{
			foreach (i; 0..n)
			{
				writefln ("%s %s", 0, i);
			}
		}
	}
}

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

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    int k;
    readf("%d %d ", &n, &k);
    if (n*(n-1)/2 <= k) {
        writeln("no solution");
    } else {
        foreach (i; 0..n) {
            writeln(0, ' ', i);
        }
    }
}

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

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    int k;
    readf("%d %d ", &n, &k);
    if (n*(n-1)/2 < k) {
        writeln("no solution");
    } else {
        foreach (i; 0..n) {
            writeln(0, ' ', i);
        }
    }
}

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

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    int k;
    readf("%d %d ", &n, &k);
    if (n*(n-1)/2 > k) {
        writeln("no solution");
    } else {
        foreach (i; 0..n) {
            writeln(0, ' ', i);
        }
    }
}


You are given two huge binary integer numbers $$$a$$$ and $$$b$$$ of lengths $$$n$$$ and $$$m$$$ respectively. You will repeat the following process: if $$$b > 0$$$, then add to the answer the value $$$a~ \&~ b$$$ and divide $$$b$$$ by $$$2$$$ rounding down (i.e. remove the last digit of $$$b$$$), and repeat the process again, otherwise stop the process.The value $$$a~ \&~ b$$$ means bitwise AND of $$$a$$$ and $$$b$$$. Your task is to calculate the answer modulo $$$998244353$$$.Note that you should add the value $$$a~ \&~ b$$$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $$$a = 1010_2~ (10_{10})$$$ and $$$b = 1000_2~ (8_{10})$$$, then the value $$$a~ \&~ b$$$ will be equal to $$$8$$$, not to $$$1000$$$.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of $$$a$$$ and the length of $$$b$$$ correspondingly. The second line of the input contains one huge integer $$$a$$$. It is guaranteed that this number consists of exactly $$$n$$$ zeroes and ones and the first digit is always $$$1$$$. The third line of the input contains one huge integer $$$b$$$. It is guaranteed that this number consists of exactly $$$m$$$ zeroes and ones and the first digit is always $$$1$$$.

Print the answer to this problem in decimal notation modulo $$$998244353$$$.

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

void solve(string a, int n, string b, int m)
{
    const static int mod = 998244353;
    auto v = new int[n];
    v[n - 1] = 1;
    for (int i = n - 2; i >= 0; -- i)
    {
        v[i] = v[i + 1] << 1;
        v[i] %= mod;
    }
    auto c = new int[max(n, m)];
    fill(c, 0);
    auto start = n > m ? n - m : 0;
    foreach (i; start .. max(n, m))
    {
        c[i] = b[i - start] == '1' ? 1 : 0;
        if (i > start) c[i] += c[i - 1];
    }
    auto ans = 0;
    auto shift = n > m ? 0 : m - n;
    start = n > m ? n - m : 0;
    foreach (i; start .. n)
    {
        if (a[i] == '1')
        {
            ans += (cast(long)c[i + shift] * v[i]) % mod;
            ans %= mod;
        }
    }
    writeln(ans);
}

int main(string[] args)
{
    int n, m;
    while (readf("%d %d\n", &n, &m) == 2)
    {
        auto a = readln.strip;
        auto b = readln.strip;
        solve(a, n, b, m);
    }
    return 0;
}

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

  int n, m;
  rd(n, m);
  auto a = readln.chomp
    .to!(char[])
    .map!((ch) => (ch - '0'))
    .array
    .to!(long[]);
  auto b = readln.chomp
    .to!(char[])
    .map!((ch) => (ch - '0'))
    .array
    .to!(long[]);

  if (n < m) {
    a.reverse;
    foreach (_; 0 .. (m - n))
      a ~= 0;
    a.reverse;
  } else {
    b.reverse;
    foreach (_; 0 .. (n - m))
      b ~= 0;
    b.reverse;
  }

  foreach (i; 1 .. b.length)
    b[i] += b[i - 1];
  const long mod = 998244353;
  long pow2 = 1, ans = 0;
  foreach_reverse (i; 0 .. a.length) {
    if (a[i]) {
      ans += pow2 * b[i] % mod;
      ans %= mod;
    }
    pow2 *= 2;
    pow2 %= mod;
  }
  writeln(ans);

}

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

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

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

void solve(string a, int n, string b, int m)
{
    const static int mod = 998244353;
    auto v = new int[n];
    v[n - 1] = 1;
    for (int i = n - 2; i >= 0; -- i)
    {
        v[i] = v[i + 1] << 1;
        v[i] %= mod;
    }
    auto c = new int[max(n, m)];
    fill(c, 0);
    auto start = n > m ? n - m : 0;
    foreach (i; start .. max(n, m))
    {
        c[i] = b[i] == '1' ? 1 : 0;
        if (i > start) c[i] += c[i - 1];
    }
    auto ans = 0;
    start = n > m ? n - m : m - n;
    foreach (i; start .. start + n)
    {
        if (a[i - start] == '1')
        {
            ans += (cast(long)c[i] * v[i - start]) % mod;
            ans %= mod;
        }
    }
    writeln(ans);
}

int main(string[] args)
{
    int n, m;
    while (readf("%d %d\n", &n, &m) == 2)
    {
        auto a = readln.strip;
        auto b = readln.strip;
        solve(a, n, b, m);
    }
    return 0;
}

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

void solve(string a, int n, string b, int m)
{
    const static int mod = 998244353;
    auto v = new int[n];
    v[n - 1] = 1;
    for (int i = n - 2; i >= 0; -- i)
    {
        v[i] = v[i + 1] << 1;
        v[i] %= mod;
    }
    auto c = new int[max(n, m)];
    auto start = 0;
    if (n > m)
    {
        start = n - m;
        foreach (i; 0 .. n - m)
        {
            c[i] = 0;
        }
    }
    foreach (i; start .. max(n, m))
    {
        c[i] = b[i] == '1' ? 1 : 0;
        if (i > start) c[i] += c[i - 1];
    }
    auto ans = 0;
    start = m > n ? m - n : 0;
    foreach (i; start .. start + n)
    {
        if (a[i - start] == '1')
        {
            ans += (cast(long)c[i] * v[i - start]) % mod;
            ans %= mod;
        }
    }
    writeln(ans);
}

int main(string[] args)
{
    int n, m;
    while (readf("%d %d\n", &n, &m) == 2)
    {
        auto a = readln.strip;
        auto b = readln.strip;
        solve(a, n, b, m);
    }
    return 0;
}


Toad Zitz has an array of integers, each integer is between $$$0$$$ and $$$m-1$$$ inclusive. The integers are $$$a_1, a_2, \ldots, a_n$$$.In one operation Zitz can choose an integer $$$k$$$ and $$$k$$$ indices $$$i_1, i_2, \ldots, i_k$$$ such that $$$1 \leq i_1 < i_2 < \ldots < i_k \leq n$$$. He should then change $$$a_{i_j}$$$ to $$$((a_{i_j}+1) \bmod m)$$$ for each chosen integer $$$i_j$$$. The integer $$$m$$$ is fixed for all operations and indices.Here $$$x \bmod y$$$ denotes the remainder of the division of $$$x$$$ by $$$y$$$.Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 300\,000$$$) — the number of integers in the array and the parameter $$$m$$$. The next line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < m$$$) — the given array.

Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print $$$0$$$. It is easy to see that with enough operations Zitz can always make his array non-decreasing.

NoteIn the first example, the array is already non-decreasing, so the answer is $$$0$$$.In the second example, you can choose $$$k=2$$$, $$$i_1 = 2$$$, $$$i_2 = 5$$$, the array becomes $$$[0,0,1,3,3]$$$. It is non-decreasing, so the answer is $$$1$$$.

/+ dub.sdl:
    name "A"
    dependency "dunkelheit" version="1.0.1"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dkh.foundation, dkh.scanner, dkh.algorithm;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    int n, m;
    int[] v;
    sc.read(n, m, v);

    bool calc(int md) {
        int bk = 0;
        foreach (d; v) {
            //[d, d + md]
            int nx = m + 10;
            if (bk <= d + md) nx = min(nx, max(bk, d));
            if (d + md >= m && bk <= d + md - m) nx = bk;

            if (nx == m + 10) return false;
            bk = nx;
        }
        return true;
    }
    writeln(binSearch!(md => calc(md))(-1, m));
    return 0;
}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/algorithm.d */
// module dkh.algorithm;

import std.traits : isFloatingPoint, isIntegral;

T binSearch(alias pred, T)(T l, T r) if (isIntegral!T) {
    while (r-l > 1) {
        T md = l + (r-l) / 2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

T binSearch(alias pred, T)(T l, T r, int cnt = 60) if (isFloatingPoint!T) {
    foreach (i; 0..cnt) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

import std.range.primitives;

E minimum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? a : b)(seed, range);
}

ElementType!Range minimum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "minimum: range must not empty");
    auto e = range.front; range.popFront;
    return minimum!pred(range, e);
}

E maximum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? b : a)(seed, range);
}

ElementType!Range maximum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "maximum: range must not empty");
    auto e = range.front; range.popFront;
    return maximum!pred(range, e);
}

Rotator!Range rotator(Range)(Range r) {
    return Rotator!Range(r);
}

struct Rotator(Range)
if (isForwardRange!Range && hasLength!Range) {
    size_t cnt;
    Range start, now;
    this(Range r) {
        cnt = 0;
        start = r.save;
        now = r.save;
    }
    this(this) {
        start = start.save;
        now = now.save;
    }
    @property bool empty() const {
        return now.empty;
    }
    @property auto front() const {
        assert(!now.empty);
        import std.range : take, chain;
        return chain(now, start.take(cnt));
    }
    @property Rotator!Range save() {
        return this;
    }
    void popFront() {
        cnt++;
        now.popFront;
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    private File f;

    this(File f) {
        this.f = f;
    }
    private char[512] lineBuf;
    private char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    assert(succW());
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }

    void read(Args...)(auto ref Args args) {
        import std.exception : enforce;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }

    bool hasNext() {
        return succ();
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/


You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.

The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).

Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.

module main;

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

int binSearch( int[] a, int num ) {

    int left = -1;
    int right = a.length;

    while (right - left > 1) {
        int middle = (left + right) / 2;
        // debug {writeln(middle);};
        if (a[middle] > num)
            right = middle;
        else
            left = middle;
    }

    // debug {writeln(num, ' ', "Done!");};
    return right;
}

int main()
{
    readln();

    auto a = readln()
             .strip()
             .split()
             .map! (to! (int))
             .array();

    auto b = readln()
             .strip()
             .split()
             .map! (to! (int))
             .array();

    sort(a);

    auto result = new int[b.length];
    foreach (i; 0..b.length)
        result[i] = binSearch(a, b[i]);

    writefln("%(%s %)", result);

	return 0;
}


Vasya has a string $$$s$$$ of length $$$n$$$. He decides to make the following modification to the string:   Pick an integer $$$k$$$, ($$$1 \leq k \leq n$$$).  For $$$i$$$ from $$$1$$$ to $$$n-k+1$$$, reverse the substring $$$s[i:i+k-1]$$$ of $$$s$$$. For example, if string $$$s$$$ is qwer and $$$k = 2$$$, below is the series of transformations the string goes through:   qwer (original string)  wqer (after reversing the first substring of length $$$2$$$)  weqr (after reversing the second substring of length $$$2$$$)  werq (after reversing the last substring of length $$$2$$$)  Hence, the resulting string after modifying $$$s$$$ with $$$k = 2$$$ is werq. Vasya wants to choose a $$$k$$$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $$$k$$$. Among all such $$$k$$$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 5000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the length of the string $$$s$$$. The second line of each test case contains the string $$$s$$$ of $$$n$$$ lowercase latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.

For each testcase output two lines: In the first line output the lexicographically smallest string $$$s'$$$ achievable after the above-mentioned modification.  In the second line output the appropriate value of $$$k$$$ ($$$1 \leq k \leq n$$$) that you chose for performing the modification. If there are multiple values of $$$k$$$ that give the lexicographically smallest string, output the smallest value of $$$k$$$ among them.

6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p

abab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1

NoteIn the first testcase of the first sample, the string modification results for the sample abab are as follows :   for $$$k = 1$$$ : abab  for $$$k = 2$$$ : baba  for $$$k = 3$$$ : abab  for $$$k = 4$$$ : babaThe lexicographically smallest string achievable through modification is abab for $$$k = 1$$$ and $$$3$$$. Smallest value of $$$k$$$ needed to achieve is hence $$$1$$$.

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.random;

int ri () {
  return readln.stripRight.to!int;
}

string slow (string z, int k) {
  auto s = z.dup;
  for (int i = 0; i + k <= s.length; ++i) {
    reverse (s[i .. i + k]);
  }
  return s.idup;
}

void research (int k) {
  string p = "1234567890";
  foreach (i; 1 .. k + 1) {
    stderr.writeln (slow (p[0 .. k], i));
  }
}

void reseach0 () {
  research (5);
  stderr.writeln;
  research (6);
  stderr.writeln;
  research (7);
  stderr.writeln;
  research (9);
}

void main() {
  debug reseach0 ();
  const nt = ri ();
  foreach (tid; 0 .. nt) {
    const n = ri ();
    const s = readln.stripRight;
    auto z = new byte[2*n];
    foreach (i; 0 .. 2*n) z[i] = s[i%n].to!byte;
    int best = n - 1;
    byte[] ans = z[0 .. n].dup;
    reverse (ans);
    auto u = new byte[n];
    foreach_reverse (k; 0 .. n - 1) {
      u[] = z[k .. k + n][];
/*
123456 0
234561 1
345612 2
456321 3
561234 4
654321 5

123456789 0
234567891 1
345678921 2
456789123 3
567894321 4
678912345 5
789654321 6
891234567 7
987654321 8
*/
      if ((k & 1) != (n & 1)) {
        reverse (u[n - k .. n]);
      }
      if (cmp (u, ans) <= 0) {
        ans = u.dup;
        best = k;
      }
    }
    foreach (i; ans) {
      write(i.to!char);
    }
    writeln;
    writeln (best+1);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. scan!int){
        int n = scan!int;
        char[] s = scan!(char[]);

        char[] ans;
        foreach(c; s) ans ~= c;
        long best = 0;
        foreach(k; 0 .. n){
            char[] t;
            foreach(c; s[k .. n]) t ~= c;
            if((n - k) % 2) foreach_reverse(c; s[0 .. k]) t ~= c;
            else foreach(c; s[0 .. k]) t ~= c;
            log("s:", s, "k:", k, "t:", t, "ans:", ans, "best:", best);

            if(ans <= t) continue;
            else ans = t, best = k;
        }

        ans.writeln;
        (best + 1).writeln;

    }

}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new string[](t);
	auto k = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!string;
		auto list = new int[][](n);
		foreach (i; 0..n)
		{
			foreach (j; i..n)
				list[i] ~= s[j]-'a';
			if ((n-i) % 2 == 0)
			{
				foreach (j; 0..i)
					list[i] ~= s[j]-'a';
			}
			else
			{
				foreach_reverse (j; 0..i)
					list[i] ~= s[j]-'a';
			}
		}
		auto pos = list.MIN_POS();
		k[ti] = cast(int)(pos+1);
		foreach (i; 0..n)
		{
			ans[ti] ~= cast(char)(list[pos][i]+'a');
		}
	}

	foreach (ti; 0..t)
	{
		writeln(ans[ti]);
		writeln(k[ti]);
	}
	stdout.flush;
	debug readln;
}


Stephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'!To compose a story, Stephen wrote out $$$n$$$ words consisting of the first $$$5$$$ lowercase letters of the Latin alphabet. He wants to select the maximum number of words to make an interesting story.Let a story be a sequence of words that are not necessarily different. A story is called interesting if there exists a letter which occurs among all words of the story more times than all other letters together.For example, the story consisting of three words "bac", "aaada", "e" is interesting (the letter 'a' occurs $$$5$$$ times, all other letters occur $$$4$$$ times in total). But the story consisting of two words "aba", "abcde" is not (no such letter that it occurs more than all other letters in total).You are given a sequence of $$$n$$$ words consisting of letters 'a', 'b', 'c', 'd' and 'e'. Your task is to choose the maximum number of them to make an interesting story. If there's no way to make a non-empty story, output $$$0$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of the words in the sequence. Then $$$n$$$ lines follow, each of them contains a word — a non-empty string consisting of lowercase letters of the Latin alphabet. The words in the sequence may be non-distinct (i. e. duplicates are allowed). Only the letters 'a', 'b', 'c', 'd' and 'e' may occur in the words. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$; the sum of the lengths of all words over all test cases doesn't exceed $$$4 \cdot 10^5$$$.

For each test case, output the maximum number of words that compose an interesting story. Print 0 if there's no way to make a non-empty interesting story.

6
3
bac
aaada
e
3
aba
abcde
aba
2
baba
baba
4
ab
ab
c
bc
5
cbdca
d
a
d
e
3
b
c
ca

NoteIn the first test case of the example, all $$$3$$$ words can be used to make an interesting story. The interesting story is "bac aaada e".In the second test case of the example, the $$$1$$$-st and the $$$3$$$-rd words can be used to make an interesting story. The interesting story is "aba aba". Stephen can't use all three words at the same time.In the third test case of the example, Stephen can't make a non-empty interesting story. So the answer is $$$0$$$.In the fourth test case of the example, Stephen can use the $$$3$$$-rd and the $$$4$$$-th words to make an interesting story. The interesting story is "c bc".

import std.stdio;
import std.ascii;
import std.algorithm;
import std.range;
import core.stdc.stdio;

void main()
{
	int t = readInt!int;
	while (t--)
	{
		solve();
	}
}

void solve()
{
	int n = readInt!int;
	auto words = new char[][](n);
	foreach(ref word; words)
	{
		word = cast(char[])readString;
	}
	int maxwords = 0;
	void tryChar(char ch)
	{
		auto diff = new int[](n);
		foreach(i; 0 .. n)
		{
			diff[i] = 0;
			foreach(c; words[i])
			{
				if (c == ch) diff[i]++;
				else diff[i]--;
			}
		}
		sort!((a, b) => a > b)(diff);
		int maxlen = 0;
		int prefsum = 0;
		foreach(i, di; diff)
		{
			prefsum += di;
			if (prefsum > 0) maxlen = cast(int)i + 1;
		}
		maxwords = max(maxwords, maxlen);
	}
	foreach(ch; ['a', 'b', 'c', 'd', 'e'])
	{
		tryChar(ch);
	}
	maxwords.writeln;
}

/* 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;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else
			static assert(text("Operator ", operator, " not supported"));
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}

import std.algorithm, std.range, std.stdio, std.numeric, std.array, std.exception,
       std.container, std.typecons, std.conv, std.random, std.bigint;

void read(S...)(ref S args) {
  auto input = readln.split;
  assert(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

string[] words;

int solve(char c) {
  int[] arr = new int[words.length];

  foreach (i, w; words) {
    auto a = w.count(c).to!int;
    arr[i] = a - (w.length.to!int - a);
  }

  sort(arr);
  reverse(arr);

  if (arr[0] < 1) return 0;

  long total = arr[0];
  int answer = 1;

  foreach (i; 1 .. arr.length) {
    total += arr[i];
    if (total <= 0) break;
    answer++;
  }

  return answer;
}

void main() {
  int t;
  read(t);

  while (t--) {
    int n;
    read(n);
    words = new string[n];

    foreach (i; 0 .. n) words[i] = readln[0 .. $ - 1];

    int answer = 0;
    foreach (c; 'a' .. 'f') {
      answer = max(answer, solve(c));
    }

    writeln(answer);
  }
}


In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1 = 1; F2 = 1; Fn = Fn - 1 + Fn - 2 (n > 2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1, a2, ..., an. Moreover, there are m queries, each query has one of the two types:  Format of the query "1 l r". In reply to the query, you need to add Fi - l + 1 to each element ai, where l ≤ i ≤ r.  Format of the query "2 l r". In reply to the query you should output the value of  modulo 1000000009 (109 + 9). Help DZY reply to all the queries.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 300000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1 ≤ l ≤ r ≤ n holds.

For each query of the second type, print the value of the sum on a single line.

NoteAfter the first query, a = [2, 3, 5, 7].For the second query, sum = 2 + 3 + 5 + 7 = 17.After the third query, a = [2, 4, 6, 9].For the fourth query, sum = 2 + 4 + 6 = 12.

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

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

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

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

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

immutable long MO = 1000000009;
immutable long SQRT5 = 383008016;
immutable long[] G = [ (1 + SQRT5 + MO) / 2, (1 - SQRT5 + MO) / 2 ];
immutable long[] H = [ MO - G[1], MO - G[0] ];

immutable LIM = 300005;
long[][] GG, HH;
long[][] GGSum;

int N, M;
long[] A;

long[][] adds;
long[][] sums;

long query(int s, int u, int L, int R, int a, int b, long val) {
// writeln("query ",s," ",u," ",L," ",R," ",a," ",b," ",val);
	chmax(a, L);
	chmin(b, R);
	if (a == L && b == R) {
		(adds[s][u] += val) %= MO;
	}
	if (adds[s][u] != 0) {
		if (R - L > 1) {
			(adds[s][u << 1 | 0] += adds[s][u]) %= MO;
			(adds[s][u << 1 | 1] += adds[s][u]) %= MO;
		}
		(sums[s][u] += GGSum[s][R - L] * adds[s][u]) %= MO;
		adds[s][u] = 0;
	}
	if (a >= b) {
		return 0;
	}
	if (a == L && b == R) {
		return sums[s][u];
	}
	const Mid = (L + R) / 2;
	const resL = query(s, u << 1 | 0, L, Mid, a, b, val);
	const resR = query(s, u << 1 | 1, Mid, R, a, b, val);
	sums[s][u] = (sums[s][u << 1 | 0] + GG[s][Mid - L] * sums[s][u << 1 | 1]) % MO;
	return (resL + GG[s][Mid - L] * resR) % MO;
}

void main(string[] args) {
	/*
	foreach (s; 0 .. MO) {
		if ((s * s) % MO == 5) {
			writeln(s);
			break;
		}
	}
	*/
	assert((SQRT5 * SQRT5) % MO == 5);
	assert((G[0] + G[1]) % MO == 1);
	assert((G[0] * G[1]) % MO == MO - 1);
	assert((G[0] * H[0]) % MO == 1);
	assert((G[1] * H[1]) % MO == 1);

	long SQRT5INV = 1;
	{
		long x = SQRT5;
		for (long e = MO - 2; e; e >>= 1, (x *= x) %= MO) if (e & 1) {
			(SQRT5INV *= x) %= MO;
		}
	}
	assert((SQRT5 * SQRT5INV) % MO == 1);

	GG = new long[][](2, LIM);
	HH = new long[][](2, LIM);
	foreach (s; 0 .. 2) {
		GG[s][0] = 1;
		HH[s][0] = 1;
		foreach (i; 1 .. LIM) {
			GG[s][i] = (GG[s][i - 1] * G[s]) % MO;
			HH[s][i] = (HH[s][i - 1] * H[s]) % MO;
		}
		assert((GG[s][$ - 1] * HH[s][$ - 1]) % MO == 1);
	}

	GGSum = new long[][](2, LIM + 1);
	foreach (s; 0 .. 2) {
		foreach (i; 0 .. LIM) {
			GGSum[s][i + 1] = (GGSum[s][i] + GG[s][i]) % MO;
		}
// writeln(GGSum[s][0..10]);
	}

	try {
	for (; ; ) {
		N = readInt;
		M = readInt;
		A = new long[N];
		foreach (i; 0 .. N) {
			A[i] = readLong;
		}

		adds = new long[][](2, N * 4);
		sums = new long[][](2, N * 4);
		foreach (i; 0 .. N) {
			query(0, 1, 0, N, i, i + 1, (((SQRT5 * HH[0][i]) % MO) * A[i]) % MO);
		}

		for (; M--; ) {
// foreach(a;0..N+1)foreach(b;0..N+1)if(a<b)writeln(a," ",b," : ",(SQRT5INV*(query(0,1,0,N,a,b,0)-query(1,1,0,N,a,b,0))%MO+MO)%MO);writeln;
			switch (readInt) {
				case 1: {
					const a = readInt - 1;
					const b = readInt;
					foreach (s; 0 .. 2) {
						query(s, 1, 0, N, a, b, (G[s] * HH[s][a]) % MO);
					}
				} break;
				case 2: {
					const a = readInt - 1;
					const b = readInt;
					long[] res = new long[2];
					foreach (s; 0 .. 2) {
						res[s] = query(s, 1, 0, N, a, b, 0);
					}
					long ans = (SQRT5INV * (res[0] - res[1])) % MO;
					ans = (ans % MO + MO) % MO;
					writeln(ans);
				} break;
				default: assert(false);
			}
		}
	}
	} catch (EOFException) {}
}


This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string $$$s$$$, consisting of lowercase English letters. Find the longest string, $$$t$$$, which satisfies the following conditions:   The length of $$$t$$$ does not exceed the length of $$$s$$$.  $$$t$$$ is a palindrome.  There exists two strings $$$a$$$ and $$$b$$$ (possibly empty), such that $$$t = a + b$$$ ( "$$$+$$$" represents concatenation), and $$$a$$$ is prefix of $$$s$$$ while $$$b$$$ is suffix of $$$s$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case is a non-empty string $$$s$$$, consisting of lowercase English letters. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$10^6$$$.

For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.

5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba

NoteIn the first test, the string $$$s = $$$"a" satisfies all conditions.In the second test, the string "abcdfdcba" satisfies all conditions, because:  Its length is $$$9$$$, which does not exceed the length of the string $$$s$$$, which equals $$$11$$$.  It is a palindrome.  "abcdfdcba" $$$=$$$ "abcdfdc" $$$+$$$ "ba", and "abcdfdc" is a prefix of $$$s$$$ while "ba" is a suffix of $$$s$$$. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string "c" is correct, because "c" $$$=$$$ "c" $$$+$$$ "" and $$$a$$$ or $$$b$$$ can be empty. The other possible solution for this test is "s".

// Code By H~$~C

module main;

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

// FIXME
int[] buildZ(in string s) {
  int n = cast(int)(s.length);
  int[] z; z.length = n;
  for (int i = 1, l = 0, r = 0; i < n; ++i) {
    if (i <= r) z[i] = (z[i - l] < r - i + 1 ? z[i - l] : r - i + 1);
    while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i];
    if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1;
  }
  return z;
}

void solve(in int testcase) {
  string s, t;
  s.read;
  int n = cast(int)(s.length), m;
  for (int i = 0; i < n; ++i)
    t ~= s[n - i - 1];
  if (s == t) {
    s.writeln;
    return ;
  }
  int[] z = buildZ(s ~ '$' ~ t);
  int x = z[n + 1];
  string ans1 = s[0 .. x];
  string ans2 = "";
  int mx = 0;
  string p = s[x .. n - x];
  string o;
  {
    n = cast(int)(p.length), m = n * 2 + 1;
    t = "";
    for (int i = 0; i < n; ++i)
      t ~= p[n - i - 1];
    o = p ~ '$' ~ t;
    z = buildZ(o);
    for (int i = m - 1; i >= 0; --i) {
      if (z[i] == m - i && mx < m - i) {
        mx = m - i;
        ans2 = o[i .. $];
      }
    }
  }
  p = t;
  {
    n = cast(int)(p.length), m = n * 2 + 1;
    t = "";
    for (int i = 0; i < n; ++i)
      t ~= p[n - i - 1];
    o = p ~ '$' ~ t;
    z = buildZ(o);
    for (int i = m - 1; i >= 0; --i) {
      if (z[i] == m - i && mx < m - i) {
        mx = m - i;
        ans2 = o[i .. $];
      }
    }
  }
  string ans3;
  for (int i = 0; i < x; ++i)
    ans3 ~= ans1[x - i - 1];
  (ans1 ~ ans2 ~ ans3).writeln;
}

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

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

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

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

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

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

immutable int q1 = 987_654_319;
immutable int q2 = 987_654_299;
immutable int maxN = 1_000_007;

void main ()
{
	int p1 = uniform (123_456_789, 444_333_222) * 2 + 1;
	int p2 = uniform (123_456_789, 444_333_222) * 2 + 1;
	int [] p1pow = [1];
	p1pow.reserve (maxN + 1);
	int [] p2pow = [1];
	p2pow.reserve (maxN + 1);
	foreach (i; 0..maxN)
	{
		p1pow ~= (p1pow.back * 1L * p1) % q1;
		p2pow ~= (p2pow.back * 1L * p2) % q2;
	}

	int tests;
	readf !(" %s") (tests);
	readln;
	foreach (test; 0..tests)
	{
		auto s = readln.strip;

		string lo = "";
		while (s.length >= 2 && s[0] == s[$ - 1])
		{
			lo ~= s[0];
			s = s[1..$ - 1];
		}
		string hi = lo.retro.text;

		auto n = s.length.to !(int);

		void calc (ref int [] h1, ref int [] h2, const ref string r)
		{
			h1[0] = 0;
			h2[0] = 0;
			foreach (i; 0..n)
			{
				h1[i + 1] = (h1[i] * 1L * p1 + r[i]) % q1;
				h2[i + 1] = (h2[i] * 1L * p2 + r[i]) % q2;
			}
		}

		auto h1lo = new int [n + 1];
		auto h2lo = new int [n + 1];
		calc (h1lo, h2lo, s);

		auto t = s.retro.text;
		auto h1hi = new int [n + 1];
		auto h2hi = new int [n + 1];
		calc (h1hi, h2hi, t);
		reverse (h1hi);
		reverse (h2hi);

		int bestLo = 0;
		foreach (i; 1..n + 1)
		{
			if ((h1hi[0] - h1hi[i] * 1L * p1pow[i] -
			    h1lo[i]) % q1 == 0 &&
			    (h2hi[0] - h2hi[i] * 1L * p2pow[i] -
			    h2lo[i]) % q2 == 0)
			{
				bestLo = i;
			}
		}

		reverse (h1lo);
		reverse (h2lo);
		reverse (h1hi);
		reverse (h2hi);
		swap (h1lo, h1hi);
		swap (h2lo, h2hi);
		int bestHi = 0;
		foreach (i; 1..n + 1)
		{
			if ((h1hi[0] - h1hi[i] * 1L * p1pow[i] -
			    h1lo[i]) % q1 == 0 &&
			    (h2hi[0] - h2hi[i] * 1L * p2pow[i] -
			    h2lo[i]) % q2 == 0)
			{
				bestHi = i;
			}
		}

		if (bestLo > bestHi)
		{
			lo ~= s[0..bestLo];
		}
		else
		{
			hi = s[$ - bestHi..$] ~ hi;
		}
		writeln (lo, hi);
	}
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    A: foreach(_; 0 .. scan!int){
        string s = scan;
        int n = s.length.to!int;

        int a = 0, b = n - 1;
        while(a < b){
            log("a:", a, "b:", b, "s[a]:", s[a], "s[b]:", s[b]);
            if(s[a] != s[b]) break;
            a ++, b --;
        }
        if(a >= b){
            s.writeln;
            continue A;
        }
        log("a:", a, "b:", b);

        string s2 = s.split("").join("$");
        int[] mana1 = manacher(s);
        int[] manatmp = manacher(s2);
        int[] mana2; foreach(i; 0 .. manatmp.length / 2) mana2 ~= manatmp[1 + i * 2] / 2;
        log("mana1:", mana1);
        log("mana2:", mana2);

        bool isPalin(int u, int v){ // s[u .. v] is palin.
            log("u:", u, "v:", v, "s[u..v]:", s[u .. v]);
            if((v - u) % 2){
                int r = mana1[u + (v - u) / 2];
                log("odd;", "r:", r);
                return r - 1 + r >= v - u;
            }
            else{
                int r = mana2[(u + v - 1) / 2];
                log("even;", "r:", r);
                return r + r >= v - u;
            }
        }

        foreach_reverse(i; 0 .. b - a + 1){
            if(isPalin(a, a + i)){
                (s[0 .. a + i] ~ s[b + 1 .. $]).writeln;
                continue A;
            }
            if(isPalin(b - i + 1, b + 1)){
                (s[0 .. a] ~ s[b - i + 1 .. $]).writeln;
                continue A;
            }
        }
    }
}

// Manacher's algorithm
// https://snuke.hatenablog.com/entry/2014/12/02/235837
int[] manacher(string s){
    int n = s.length.to!int;
    int[] res = new int[](n);
    int i = 0, j = 0;
    while(i < n){
        while(i - j >= 0 && i + j < n && s[i - j] == s[i + j]) ++j;
        res[i] = j;
        int k = 1;
        while(i - k >= 0 && i + k < n && k + res[i - k] < j) res [i + k] = res[i - k], ++k;
        i += k; j -= k;
    }
    return res;
}

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

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

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

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

int[] manacher(T)(T a) {
  const n = cast(int)(a.length);
  auto r = new int[n * 2];
  for (int i = 0, j = 0, k; i < n * 2; i += k, j = max(j - k, 0)) {
    for (; 0 <= i - j && i + j + 1 < n * 2 && a[(i - j) / 2] == a[(i + j + 1) / 2]; ++j) {}
    r[i] = j;
    for (k = 1; 0 <= i - k && 0 <= j - k && r[i - k] != j - k; ++k) {
      r[i + k] = min(r[i - k], j - k);
    }
  }
  return r;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const S = readToken();
        const L = cast(int)(S.length);

        const rads = manacher(S);
        debug {
          writeln("rads = ", rads);
        }

        auto ls = new int[L + 1];
        ls[] = -1;
        foreach (x; 0 .. L) {
          // x - rads[x] <= 2 k
          chmax(ls[(x - rads[x] + 1) / 2], x);
        }
        foreach (k; 1 .. L + 1) {
          chmax(ls[k], ls[k - 1]);
        }
        auto rs = new int[L + 1];
        rs[] = 2 * L;
        foreach (x; L - 1 .. 2 * L - 1) {
          // 2 (L - 1 - k) <= x + rads[x]
          chmin(rs[(2 * (L - 1) - x - rads[x] + 1) / 2], x);
        }
        foreach (k; 1 .. L + 1) {
          chmin(rs[k], rs[k - 1]);
        }
        debug {
          writeln("ls = ", ls);
          writeln("rs = ", rs);
        }

        int ansA, ansB;
        void check(int a, int b) {
          if (ansA + ansB < a + b) {
            ansA = a;
            ansB = b;
          }
        }
        foreach (k; 0 .. L + 1) {
          check(k, k);
          if (ls[k] != -1) {
            const i = k;
            const j = ls[k] - i;
            check(k + (j - i + 1), k);
          }
          if (rs[k] != 2 * L) {
            const i = L - 1 - k;
            const j = rs[k] - i;
            check(k, (i - j + 1) + k);
          }
          if ((k + 1) + (k + 1) > L) {
            break;
          }
          if (S[k] != S[L - 1 - k]) {
            break;
          }
        }
        writeln(S[0 .. ansA] ~ S[L - ansB .. L]);
      }
    }
  } catch (EOFException e) {
  }
}