This is the easy 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 1000$$$), 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 $$$5000$$$.

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".

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

// 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.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);

        bool isPalin(int u, int v){ // s[u .. v] is palin.
            log("u:", u, "v:", v, "s[u..v]:", s[u .. v]);
            int i = u, j = v - 1;
            while(i < j){
                if(s[i] != s[j]) return 0;
                i ++, j --;
            }
            return 1;
        }

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

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


Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?

The first line contains one integer n (1 ≤ n ≤ 105) — the amount of bars on the table. The second line contains a sequence t1, t2, ..., tn (1 ≤ ti ≤ 1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).

Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.

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

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

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

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

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                int[] arr = new int[n];
                for (int i = 0; i < n; i++) {
                        arr[i] = cin.read_int;
                }
                int[] alice = new int[n];
                int[] bob = new int[n];

                alice[0] = arr[0];
                for (int i = 1; i < n; i++) {
                        alice[i] = alice[i - 1] + arr[i];
                }

                reverse(arr);

                bob[0] = arr[0];
                for (int i = 1; i < n; i++) {
                        bob[i] = bob[i - 1] + arr[i];
                }

                reverse(arr);

                int total_time = sum(arr[0..$]);
                bool[] eaten = new bool[n];

                int alice_a = 0;
                int bob_a = 0;
                int curr_a = 0;
                int curr_b = 0;

                for (int i = 0; i <= total_time; i++) {
                        if (i == alice[curr_a] && eaten[curr_a] == false) {
                                eaten[curr_a] = true;
                                alice_a++;
                                curr_a++;
                        }
                        if (i == bob[curr_b] && eaten[n - 1 - curr_b] == false) {
                                eaten[n - 1 - curr_b] = true;
                                bob_a++;
                                curr_b++;
                        }
                }
                writeln(alice_a, " ", bob_a);
        }
}

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

int main() {
    debug stdin = File("in.txt", "r");

    int n;
    readf(" %s\n", &n);
    int[] bar = new int[n + 2];
    int[] cumbar = new int[n + 2];
    foreach (i ; 1 .. n + 1) {
        readf(" %s", &bar[i]);
        cumbar[i] = bar[i] + cumbar[i - 1];
    }
    int cumrev;
    int alice, bob;
    foreach_reverse (i ; 2 .. n + 2) {
        cumrev += bar[i];
        if (cumbar[i - 2] - cumrev <= bar[i - 1]) {
            if (cumrev < cumbar[i - 2]) alice = i - 2;
            else alice = i - 1;
            bob = n - alice;
            break;
        }
    }
    writeln(alice, " ", bob);

    return 0;
}

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

void main(char[][] args)
{
    version(MY_SUPER_PUPER_ONLINE_JUDGE)
    {
        stdin.open("src/input.txt", "rt");
        stdout.open("src/output.txt","wt");
    }
    int n;
    readf("%d\n", &n);
    int[] a = new int[n], sum = new int[n + 1];
    sum[0] = 0;
    for(int i = 0; i < n; ++i)
    {
        readf("%d ", &a[i]);
    }
    int sum1 = 0, sum2 = 0, x = 0, y = n - 1;
    while(y >= x)
    {
        if(sum1 < sum2)
        {
            sum1 += a[x];
            x++;
        }
        else
        if(sum1 > sum2)
        {
            sum2 += a[y];
            y--;
        }
        else
        {
            sum1 += a[x];
            x++;
            if(y >= x)
            {
                sum2 += a[y];
                y--;
            }
        }
    }
    write(x, " ", n - y - 1);
}


There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where:  <hostname> — server name (consists of words and maybe some dots separating them),  /<path> — optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa — for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where:   <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20.  <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20.  Addresses are not guaranteed to be distinct.

First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.

10
http://abacaba.ru/test
http://abacaba.ru/
http://abacaba.com
http://abacaba.com/test
http://abacaba.de/
http://abacaba.ru/test
http://abacaba.de/test
http://abacaba.com/
http://abacaba.com/t
http://abacaba.com/test

14
http://c
http://ccc.bbbb/aba..b
http://cba.com
http://a.c/aba..b/a
http://abc/
http://a.c/
http://ccc.bbbb
http://ab.ac.bc.aa/
http://a.a.a/
http://ccc.bbbb/
http://cba.com/
http://cba.com/aba..b
http://a.a.a/aba..b/a
http://abc/aba..b/a

2
http://cba.com http://ccc.bbbb
http://a.a.a http://a.c http://abc

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		string [] [string] d;
		foreach (i; 0..n)
		{
			auto s = readln.strip;
			auto t = s.split ('/');
			d[t[2]] ~= t.drop (3).map !(x => "/" ~ x).join ();
		}

		string [] [string] e;
		foreach (k, v; d)
		{
			e[v.sort ().uniq ().join (' ')] ~= k;
		}
		writeln (e.byKeyValue.count !(x => x.value.length > 1));
		foreach (k, v; e)
		{
			if (v.length > 1)
			{
				v.map !(x => "http://" ~ x).join (' ').writeln;
			}
		}
	}
}

import std.algorithm, std.conv, std.range, std.stdio, std.string;
void main () {
	auto n = readln.strip.to!int;
	string [] [string] d, e;
	foreach (i; 0..n)
	{
		auto t = readln.strip.split ('/');
		d[t[2]] ~= t[3..$].map !(x => "/" ~ x).join;
	}
	foreach (k, v; d)
		e[v.sort ().uniq.join (' ')] ~= k;
	auto r = e.byValue.filter !(x => x.length > 1);
	writefln ("%s\n%(%-(http://%s %)\n%)", r.walkLength, r);
}


Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell $$$(0, 0)$$$. Robot can perform the following four kinds of operations:   U — move from $$$(x, y)$$$ to $$$(x, y + 1)$$$;  D — move from $$$(x, y)$$$ to $$$(x, y - 1)$$$;  L — move from $$$(x, y)$$$ to $$$(x - 1, y)$$$;  R — move from $$$(x, y)$$$ to $$$(x + 1, y)$$$. Vasya also has got a sequence of $$$n$$$ operations. Vasya wants to modify this sequence so after performing it the robot will end up in $$$(x, y)$$$.Vasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: $$$maxID - minID + 1$$$, where $$$maxID$$$ is the maximum index of a changed operation, and $$$minID$$$ is the minimum index of a changed operation. For example, if Vasya changes RRRRRRR to RLRRLRL, then the operations with indices $$$2$$$, $$$5$$$ and $$$7$$$ are changed, so the length of changed subsegment is $$$7 - 2 + 1 = 6$$$. Another example: if Vasya changes DDDD to DDRD, then the length of changed subsegment is $$$1$$$. If there are no changes, then the length of changed subsegment is $$$0$$$. Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them.Help Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from $$$(0, 0)$$$ to $$$(x, y)$$$, or tell him that it's impossible.

The first line contains one integer number $$$n~(1 \le n \le 2 \cdot 10^5)$$$ — the number of operations. The second line contains the sequence of operations — a string of $$$n$$$ characters. Each character is either U, D, L or R. The third line contains two integers $$$x, y~(-10^9 \le x, y \le 10^9)$$$ — the coordinates of the cell where the robot should end its path.

Print one integer — the minimum possible length of subsegment that can be changed so the resulting sequence of operations moves the robot from $$$(0, 0)$$$ to $$$(x, y)$$$. If this change is impossible, print $$$-1$$$.

NoteIn the first example the sequence can be changed to LULUU. So the length of the changed subsegment is $$$3 - 1 + 1 = 3$$$.In the second example the given sequence already leads the robot to $$$(x, y)$$$, so the length of the changed subsegment is $$$0$$$.In the third example the robot can't end his path in the cell $$$(x, y)$$$.

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 S = readln.chomp;
    auto s = readln.split.map!(to!long);
    auto X = s[0];
    auto Y = s[1];

    bool check(int len, long x, long y) {
        return (len >= abs(x) + abs(y)) && (len % 2 == (abs(x) + abs(y)) % 2);
    }

    if (!check(N, X, Y)) {
        writeln(-1);
        return;
    }

    auto A = new long[](N+1);
    auto B = new long[](N+1);

    foreach (i; 0..N) {
        A[i+1] = A[i];
        B[i+1] = B[i];
        if      (S[i] == 'R') A[i+1] += 1;
        else if (S[i] == 'L') A[i+1] -= 1;
        else if (S[i] == 'U') B[i+1] += 1;
        else if (S[i] == 'D') B[i+1] -= 1;
    }

    if (A[N] == X && B[N] == Y) {
        writeln(0);
        return;
    }

    int hi = N;
    int lo = -1;
    while (hi - lo > 1) {
        int mid = (hi + lo) / 2;
        bool ok = false;
        foreach (l; 0..N-mid+1) {
            int r = l + mid - 1;
            long x1 = A[r+1] - A[l];
            long y1 = B[r+1] - B[l];
            long x2 = A[N] - x1;
            long y2 = B[N] - y1;
            long x = X - x2;
            long y = Y - y2;
            if (check(mid, x, y)) {
                ok = true;
                break;
            }
        }
        (ok ? hi : lo) = mid;
    }

    hi.writeln;
}

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;

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

    auto s = readln.chomp;

    int x, y;
    readf("%s %s", &x, &y);
    readln;

    if (abs(x) + abs(y) > n || (abs(x) + abs(y)) % 2 != n % 2) {
        writeln(-1);
        return;
    }

    auto p = new int[][] (n+1, 2);
    p[] = [0, 0];
    foreach (i, e; s) {
        int xstep = 0, ystep = 0;
        if (e == 'U') { ystep = 1; }
        if (e == 'R') { xstep = 1; }
        if (e == 'D') { ystep = -1; }
        if (e == 'L') { xstep = -1; }

        p[i+1] = [p[i][0] + xstep, p[i][1] + ystep];
    }

    int chk(ref string s, int x, int y) {
        if (abs(x) + abs(y) > s.length) { return -1; }

        bool reachable(int m) {
            int cx = p[m][0], cy = p[m][1];
            int len = s.length.to!int - m;
            return abs(x - cx) + abs(y - cy) <= len;
        }

        int le = 0, r = s.length.to!int;
        while (le < r) {
            int m = (le + r) / 2 + 1;
            if (reachable(m)) { le = m; }
            else { r = m-1; }
        }

        return s.length.to!int - r;
    }

    auto ans = chk(s, x, y);
    while (! s.empty()) {
        auto e = s.back;
        s.popBack();

        if (e == 'U') { y -= 1; }
        if (e == 'R') { x -= 1; }
        if (e == 'D') { y += 1; }
        if (e == 'L') { x += 1; }

        auto cur = chk(s, x, y);

        if (cur == -1) { continue; }
        if (cur < ans) { ans = cur; }
    }

    ans.writeln;
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;
    auto s = readln.split.map!(to!long);
    auto X = s[0];
    auto Y = s[1];

    bool check(int len, long x, long y) {
        return (len >= abs(x) + abs(y)) && (len % 2 == (abs(x) + abs(y)) % 2);
    }

    if (check(0, X, Y)) {
        writeln(0);
        return;
    }

    if (!check(N, X, Y)) {
        writeln(-1);
        return;
    }

    auto A = new long[](N+1);
    auto B = new long[](N+1);

    foreach (i; 0..N) {
        A[i+1] = A[i];
        B[i+1] = B[i];
        if      (S[i] == 'R') A[i+1] += 1;
        else if (S[i] == 'L') A[i+1] -= 1;
        else if (S[i] == 'U') B[i+1] += 1;
        else if (S[i] == 'D') B[i+1] -= 1;
    }

    int hi = N;
    int lo = -1;
    while (hi - lo > 1) {
        int mid = (hi + lo) / 2;
        bool ok = false;
        foreach (l; 0..N-mid+1) {
            int r = l + mid - 1;
            long x1 = A[r+1] - A[l];
            long y1 = B[r+1] - B[l];
            long x2 = A[N] - x1;
            long y2 = B[N] - y1;
            long x = X - x2;
            long y = Y - y2;
            if (check(mid, x, y)) {
                ok = true;
                break;
            }
        }
        (ok ? hi : lo) = mid;
    }

    hi.writeln;
}


You are given an array $$$a$$$ of size $$$n$$$.You can perform the following operation on the array:   Choose two different integers $$$i, j$$$ $$$(1 \leq i < j \leq n$$$), replace $$$a_i$$$ with $$$x$$$ and $$$a_j$$$ with $$$y$$$. In order not to break the array, $$$a_i | a_j = x | y$$$ must be held, where $$$|$$$ denotes the bitwise OR operation. Notice that $$$x$$$ and $$$y$$$ are non-negative integers. Please output the minimum sum of the array you can get after using the operation above any number of times.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \leq t \leq 1000)$$$. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(2 \leq n \leq 100)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots ,a_n$$$ $$$(0 \leq a_i < 2^{30})$$$.

For each test case, print one number in a line — the minimum possible sum of the array.

NoteIn the first example, you can perform the following operations to obtain the array $$$[1, 0, 2]$$$:1. choose $$$i = 1, j = 2$$$, change $$$a_1 = 1$$$ and $$$a_2 = 2$$$, it's valid since $$$1 | 3 = 1 | 2$$$. The array becomes $$$[1, 2, 2]$$$.2. choose $$$i = 2, j = 3$$$, change $$$a_2 = 0$$$ and $$$a_3 = 2$$$, it's valid since $$$2 | 2 = 0 | 2$$$. The array becomes $$$[1, 0, 2]$$$.We can prove that the minimum sum is $$$1 + 0 + 2 = 3$$$In the second example, We don't need any operations.

import std.stdio, std.string, std.conv;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
import std.typecons;

void solution(ref File input, ref File output) {
    auto t = input.readln.chomp.to!int;
    while (t-- > 0) {
        auto _ = input.readln;
        auto answer = input.readln.chomp.split(' ')
            .map!(to!int)
            .fold!((x, y) => x | y)(0);
        output.writeln(answer);
    }
}
void main()
{
    File input, output;
    debug(1) {
        input = File("input.txt", "r");
        output = File("output.txt", "w");
    } else {
        input = stdin;
        output = stdout;
    }
    solution(input, output);
}


The only difference with E2 is the question of the problem..Vlad built a maze out of $$$n$$$ rooms and $$$n-1$$$ bidirectional corridors. From any room $$$u$$$ any other room $$$v$$$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.Vlad invited $$$k$$$ friends to play a game with them.Vlad starts the game in the room $$$1$$$ and wins if he reaches a room other than $$$1$$$, into which exactly one corridor leads.Friends are placed in the maze: the friend with number $$$i$$$ is in the room $$$x_i$$$, and no two friends are in the same room (that is, $$$x_i \neq x_j$$$ for all $$$i \neq j$$$). Friends win if one of them meets Vlad in any room or corridor before he wins.For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time. Friends know the plan of a maze and intend to win. Vlad is a bit afraid of their ardor. Determine if he can guarantee victory (i.e. can he win in any way friends play).In other words, determine if there is such a sequence of Vlad's moves that lets Vlad win in any way friends play.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. The input contains an empty string before each test case. The first line of the test case contains two numbers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2\cdot 10^5$$$) — the number of rooms and friends, respectively. The next line of the test case contains $$$k$$$ integers $$$x_1, x_2, \dots, x_k$$$ ($$$2 \le x_i \le n$$$) — numbers of rooms with friends. All $$$x_i$$$ are different. The next $$$n-1$$$ lines contain descriptions of the corridors, two numbers per line $$$v_j$$$ and $$$u_j$$$ ($$$1 \le u_j, v_j \le n$$$) — numbers of rooms that connect the $$$j$$$ corridor. All corridors are bidirectional. From any room, you can go to any other by moving along the corridors. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test is not greater than $$$2\cdot10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be "YES" if Vlad can guarantee himself a victory and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes" and "YES" will all be recognized as positive answers).

NoteIn the first test case, regardless of the strategy of his friends, Vlad can win by going to room $$$4$$$. The game may look like this:  The original locations of Vlad and friends. Vlad is marked in green, friends — in red.   Locations after one unit of time.   End of the game. Note that if Vlad tries to reach the exit at the room $$$8$$$, then a friend from the $$$3$$$ room will be able to catch him.

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

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

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

enum int INF = 1<<29;

void solve() {
    readln;
    int N, K; readf("%d %d\n", &N, &K);
    auto X = readarray!int;
    foreach (ref x; X) x--;
    auto G = new int[][N];
    foreach (i; 0 .. N - 1) {
        int U, V; readf("%d %d\n", &U, &V);
        U--; V--;
        G[U] ~= V;
        G[V] ~= U;
    }

    void bfs(in int[] ss, ref int[] d) {
        d[] = INF;
        DList!int Q;
        foreach (s; ss) {
            Q.insert(s);
            d[s] = 0;
        }
        while (! Q.empty) {
            auto c = Q.front; Q.removeFront;
            foreach (next; G[c]) {
                if (d[next] <= d[c] + 1) continue;
                d[next] = d[c] + 1;
                Q.insert(next);
            }
        }
    }
    int[] fromR = new int[N];
    int[] fromF = new int[N];
    bfs([0], fromR);
    bfs(X, fromF);
    bool f() {
        foreach (v; 1 .. N) {
            if (G[v].length != 1) continue;
            if (fromR[v] < fromF[v]) return true;
        }
        return false;
    }
    writeln(f() ? "YES" : "NO");
}

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

void main(string[ ] args) {
    int t;
    readf!"%s"(t);
    readln;

    while (t--) {
        readln;

        int n, k;
        readf!"%s %s"(n, k);
        readln;

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

        auto g = new int[][] (n+1);
        foreach (i; 0 .. n-1) {
            int x, y;
            readf!"%s %s"(x, y);
            readln;

            g[x] ~= y;
            g[y] ~= x;
        }

        auto pos = new bool[n+1];
        pos[] = true;
        f.each!(v => pos[v] = false);

        alias r = Tuple!(bool, "good", int, "enemyDepth");

        immutable int INF = 10 ^^ 6;

        r dfs(int v, int fr, int d) {
            if (!pos[v]) {
                return r(false, d);
            }

            if (d != 0 && g[v].length == 1) {
                return r(true, INF);
            }

            int minEnemyDepth = INF;
            bool pathExists = false;
            foreach (u; g[v]) {
                if (u == fr) { continue; }

                auto res = dfs(u, v, d + 1);
                pathExists |= res.good;
                minEnemyDepth = min(minEnemyDepth, res.enemyDepth);
            }

            auto enemyStepsToReach = minEnemyDepth - d;

            return r(pathExists && enemyStepsToReach > d, minEnemyDepth);
        }

        auto ans = dfs(1, 0, 0);

        writeln(ans.good ? "YES" : "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;

struct node { int vlad_dist = -1, friend_dist = -1; };
alias PairII = Tuple!(int, int);

void dfs(int s, int[][] adj, node[] a, int dist)
{
  a[s].vlad_dist = dist;
  foreach (d ; adj[s]) {
    if (a[d].vlad_dist != -1)
      continue;
    dfs(d, adj, a, dist + 1);
  }
}

void bfs(int[] friends, int[][] adj, node[] a)
{
  auto queue = new DList!PairII;
  foreach (friend ; friends) {
    a[friend].friend_dist = 0;
    queue.insertBack(tuple(friend, 0));
  }
  while (!queue.empty) {
    auto x = queue.front;
    queue.removeFront;
    int s = x[0];
    int dist = x[1];
    foreach (d ; adj[s]) {
      if (a[d].friend_dist != -1)
        continue;
      a[d].friend_dist = dist + 1;
      queue.insertBack(tuple(d, dist + 1));
    }
  }
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, k;
    readf!" %d %d "(n, k);
    auto friends = readln.splitter.map!(x => x.to!int - 1).array;
    node[] a = new node[](n);
    int[][] adj = new int[][](n);
    foreach (i ; 0 .. n - 1) {
      int v, u;
      readf!" %d %d "(v, u);
      v--;
      u--;
      adj[v] ~= u;
      adj[u] ~= v;
    }
    dfs(0, adj, a, 0);
    bfs(friends, adj, a);
    bool vlad_wins = false;
    foreach (i ; 1 .. n) {
      if (adj[i].length != 1)
        continue;
      if (a[i].vlad_dist < a[i].friend_dist) {
        vlad_wins = true;
        break;
      }
    }
    writeln(vlad_wins ? "YES" : "NO");
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;

		auto x = readln.splitter.map !(to !(int)).array;
		x[] -= 1;
		auto b = new bool [n];
		foreach (ref c; x)
		{
			b[c] = true;
		}

		auto g = new int [] [n];
		foreach (j; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			g[u] ~= v;
			g[v] ~= u;
		}

		auto depth = new int [n];

		void recurDepth (int v, int p, int cur)
		{
			depth[v] = cur;
			foreach (u; g[v])
			{
				if (u == p)
				{
					continue;
				}
				recurDepth (u, v, cur + 1);
			}
		}

		recurDepth (0, -1, 0);

		auto friend = new int [n];

		void recurFriend (int v, int p)
		{
			int res = n;
			if (b[v])
			{
				res = 0;
			}
			foreach (u; g[v])
			{
				if (u == p)
				{
					continue;
				}
				recurFriend (u, v);
				res = min (res, friend[u] + 1);
			}
			friend[v] = res;
		}

		recurFriend (0, -1);

		bool recurVisit (int v, int p)
		{
			if (friend[v] <= depth[v])
			{
				return false;
			}
			if (v != 0 && g[v].length == 1)
			{
				return true;
			}
			foreach (u; g[v])
			{
				if (u == p)
				{
					continue;
				}
				if (recurVisit (u, v))
				{
					return true;
				}
			}
			return false;
		}

		auto res = recurVisit (0, -1);

		writeln (res ? "YES" : "NO");
	}
}


This is an interactive problem.$$$n$$$ people sitting in a circle are trying to shuffle a deck of cards. The players are numbered from $$$1$$$ to $$$n$$$, so that players $$$i$$$ and $$$i+1$$$ are neighbours (as well as players $$$1$$$ and $$$n$$$). Each of them has exactly $$$k$$$ cards, where $$$k$$$ is even. The left neighbour of a player $$$i$$$ is player $$$i - 1$$$, and their right neighbour is player $$$i + 1$$$ (except for players $$$1$$$ and $$$n$$$, who are respective neighbours of each other).Each turn the following happens: if a player has $$$x$$$ cards, they give $$$\lfloor x / 2 \rfloor$$$ to their neighbour on the left and $$$\lceil x / 2 \rceil$$$ cards to their neighbour on the right. This happens for all players simultaneously.However, one player $$$p$$$ is the impostor and they just give all their cards to their neighbour on the right. You know the number of players $$$n$$$ and the number of cards $$$k$$$ each player has initially, but $$$p$$$ is unknown to you. Your task is to determine the value of $$$p$$$, by asking questions like "how many cards does player $$$q$$$ have?" for an index $$$q$$$ of your choice. After each question all players will make exactly one move and give their cards to their neighbours. You need to find the impostor by asking no more than $$$1000$$$ questions.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$4 \le n \le 10^5$$$, $$$2 \le k \le 10^9$$$, $$$k$$$ is even) — the number of players and the number of cards.

NoteIn the example the cards are transferred in the following way:  $$$2$$$ $$$2$$$ $$$2$$$ $$$2$$$ — player $$$1$$$ has $$$2$$$ cards. $$$1$$$ $$$2$$$ $$$3$$$ $$$2$$$ — player $$$1$$$ has $$$1$$$ card.After this turn the number of cards remains unchanged for each player.

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

void main ()
{
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		int pos = 0;
		int step = cast (int) (sqrt (n * 1.0));
		int cur = -1;

		int ask (int p)
		{
			writeln ("? ", p + 1);
			stdout.flush ();
			cur = readln.strip.to !(int);
			return cur;
		}

		while (ask (pos) == k)
		{
			pos = (pos + step + uniform (0, 2)) % n;
		}

		step = (cur < k) ? 1 : (n - 1);
		do
		{
			pos = (pos + step) % n;
		}
		while (ask (pos) != k);

		writeln ("! ", pos + 1);
		stdout.flush ();
	}
}

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

void main ()
{
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		int pos = 0;
		int step = cast (int) (sqrt (n * 1.0));
		int cur = -1;

		int ask (int p)
		{
			writeln ("? ", p + 1);
			stdout.flush ();
			cur = readln.strip.to !(int);
			return cur;
		}

		while (ask (pos) == k)
		{
			pos = (pos + step + uniform (0, 2)) % n;
		}

		step = (cur < k) ? (+1) : (-1);
		do
		{
			pos = (pos + step) % n;
		}
		while (ask (pos) != k);

		writeln ("! ", pos + 1);
		stdout.flush ();
	}
}


Your program fails again. This time it gets "Wrong answer on test 233".This is the harder version of the problem. In this version, $$$1 \le n \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.The problem is to finish $$$n$$$ one-choice-questions. Each of the questions contains $$$k$$$ options, and only one of them is correct. The answer to the $$$i$$$-th question is $$$h_{i}$$$, and if your answer of the question $$$i$$$ is $$$h_{i}$$$, you earn $$$1$$$ point, otherwise, you earn $$$0$$$ points for this question. The values $$$h_1, h_2, \dots, h_n$$$ are known to you in this problem.However, you have a mistake in your program. It moves the answer clockwise! Consider all the $$$n$$$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.Formally, the mistake moves the answer for the question $$$i$$$ to the question $$$i \bmod n + 1$$$. So it moves the answer for the question $$$1$$$ to question $$$2$$$, the answer for the question $$$2$$$ to the question $$$3$$$, ..., the answer for the question $$$n$$$ to the question $$$1$$$.We call all the $$$n$$$ answers together an answer suit. There are $$$k^n$$$ possible answer suits in total.You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $$$1$$$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $$$998\,244\,353$$$.For example, if $$$n = 5$$$, and your answer suit is $$$a=[1,2,3,4,5]$$$, it will submitted as $$$a'=[5,1,2,3,4]$$$ because of a mistake. If the correct answer suit is $$$h=[5,2,2,3,4]$$$, the answer suit $$$a$$$ earns $$$1$$$ point and the answer suite $$$a'$$$ earns $$$4$$$ points. Since $$$4 > 1$$$, the answer suit $$$a=[1,2,3,4,5]$$$ should be counted.

The first line contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le k \le 10^9$$$) — the number of questions and the number of possible answers to each question. The following line contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$, ($$$1 \le h_{i} \le k)$$$ — answers to the questions.

Output one integer: the number of answers suits satisfying the given condition, modulo $$$998\,244\,353$$$.

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

struct ModInt(int M_) {
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op)() const if (op == "-") { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

enum MO = 998244353;
alias Mint = ModInt!MO;

enum LIM = 10^^6;
Mint[] inv, fac, invFac;
void prepare() {
  inv = new Mint[LIM];
  fac = new Mint[LIM];
  invFac = new Mint[LIM];
  inv[1] = 1;
  foreach (i; 2 .. LIM) {
    inv[i] = -(Mint.M / i) * inv[cast(size_t)(Mint.M % i)];
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM) {
    fac[i] = fac[i - 1] * i;
    invFac[i] = invFac[i - 1] * inv[i];
  }
}
Mint binom(long n, long k) {
  if (0 <= k && k <= n) {
    assert(n < LIM);
    return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] * invFac[cast(size_t)(n - k)];
  } else {
    return Mint(0);
  }
}

void main() {
  prepare();

  try {
    for (; ; ) {
      const N = readInt();
      const K = readLong();
      auto H = new int[N];
      foreach (i; 0 .. N) {
        H[i] = readInt();
      }

      int l, m;
      foreach (i; 0 .. N) {
        const ha = H[i];
        const hb = H[(i + 1) % N];
        if (ha == hb) {
          ++l;
        } else {
          ++m;
        }
      }
      debug {
        writeln("l = ", l, ", m = ", m);
      }

      auto pw2 = new Mint[m + 1];
      auto pwKm2 = new Mint[m + 1];
      pw2[0] = 1;
      pwKm2[0] = 1;
      foreach (i; 1 .. m + 1) {
        pw2[i] = pw2[i - 1] * Mint(2);
        pwKm2[i] = pwKm2[i - 1] * Mint(K - 2);
      }
      Mint ans;
      foreach (z; 0 .. m + 1) {
        /*
          x + y = z
          x < y
        */
        Mint prod = binom(m, z) * pwKm2[m - z];
        Mint s = pw2[z];
        if (z % 2 == 0) {
          s -= binom(z, z / 2);
        }
        s *= inv[2];
        ans += prod * s;
      }

      ans *= Mint(K)^^l;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Your city has n junctions. There are m one-way roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions.To ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction i can protect junction j if either i = j or the police patrol car can go to j from i and then come back to i.Building checkposts costs some money. As some areas of the city are more expensive than others, building checkpost at some junctions might cost more money than other junctions.You have to determine the minimum possible money needed to ensure the security of all the junctions. Also you have to find the number of ways to ensure the security in minimum price and in addition in minimum number of checkposts. Two ways are different if any of the junctions contains a checkpost in one of them and do not contain in the other.

In the first line, you will be given an integer n, number of junctions (1 ≤ n ≤ 105). In the next line, n space-separated integers will be given. The ith integer is the cost of building checkpost at the ith junction (costs will be non-negative and will not exceed 109). The next line will contain an integer m (0 ≤ m ≤ 3·105). And each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; u ≠ v). A pair ui, vi means, that there is a one-way road which goes from ui to vi. There will not be more than one road between two nodes in the same direction.

Print two integers separated by spaces. The first one is the minimum possible money needed to ensure the security of all the junctions. And the second one is the number of ways you can ensure the security modulo 1000000007 (109 + 7).

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

immutable long MOD = 1000000007;

int n, m;
long[] a;
int[][] g;
int[][] rg;

int[] tsort(int[][] g) {
  auto n = cast(int)g.length;
  bool[] used;
  used.length = n;
  int[] vs;
  void dfs(int v) {
    used[v] = true;
    foreach (u; g[v]) {
      if (!used[u]) {
        dfs(u);
      }
    }
    vs ~= v;
  }
  foreach (v; 0..n) {
    if (!used[v]) {
      dfs(v);
    }
  }
  vs.reverse();
  return vs;
}

class SCC {
  int[][] g, rg;
  int V, U;
  int[] group;

  this(int n) {
    V = n;
    g.length = n;
    rg.length = n;
  }

  void addEdge(int u, int v) {
    g[u] ~= v;
    rg[v] ~= u;
  }

  void build() {
    auto vs = tsort(g);
    bool[] used;
    used.length = V;
    group.length = V;
    U = 0;
    void dfs(int v, int id) {
      group[v] = id;
      used[v] = true;
      foreach(u; rg[v]) {
        if (!used[u]) {
          dfs(u, id);
        }
      }
    }
    foreach(v; vs) {
      if (!used[v]) {
        dfs(v, U);
        U++;
      }
    }
  }

}

void main() {
  n = readln.strip.to!int;
  a = readln.split.map!(to!long).array;
  m = readln.strip.to!int;
  auto scc = new SCC(n);
  foreach(i; 0..m) {
    int u, v;
    scanf("%d%d", &u, &v);
    u--, v--;
    scc.addEdge(u, v);
  }
  scc.build();
  auto nn = scc.U;
  long[] cost, count;
  cost.length = nn;
  count.length = nn;
  cost.fill(long.max);
  foreach (v; 0..n) {
    int x = scc.group[v];
    if (cost[x] > a[v]) {
      cost[x] = a[v];
      count[x] = 0;
    }
    if (cost[x] == a[v]) {
      count[x]++;
    }
  }
  long ans_ct = 1, ans_val = 0;
  foreach (v; 0..nn) {
    ans_ct = ans_ct * count[v] % MOD;
    ans_val += cost[v];
  }
  writeln(ans_val, ' ', ans_ct);
}

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

immutable long MOD = 1000000007;

int n, m;
int[] a;
int[][] g;
int[][] rg;

int[] tsort(int[][] g) {
  auto n = cast(int)g.length;
  bool[] used;
  used.length = n;
  int[] vs;
  void dfs(int v) {
    used[v] = true;
    foreach (u; g[v]) {
      if (!used[u]) {
        dfs(u);
      }
    }
    vs ~= v;
  }
  foreach (v; 0..n) {
    if (!used[v]) {
      dfs(v);
    }
  }
  vs.reverse();
  return vs;
}

class SCC {
  int[][] g, rg;
  int V, U;
  int[] group;

  this(int n) {
    V = n;
    g.length = n;
    rg.length = n;
  }

  void addEdge(int u, int v) {
    g[u] ~= v;
    rg[v] ~= u;
  }

  void build() {
    auto vs = tsort(g);
    bool[] used;
    used.length = V;
    group.length = V;
    U = 0;
    void dfs(int v, int id) {
      group[v] = id;
      used[v] = true;
      foreach(u; rg[v]) {
        if (!used[u]) {
          dfs(u, id);
        }
      }
    }
    foreach(v; vs) {
      if (!used[v]) {
        dfs(v, U);
        U++;
      }
    }
  }

}

void main() {
  n = readln.strip.to!int;
  a = readln.split.map!(to!int).array;
  m = readln.strip.to!int;
  auto scc = new SCC(n);
  foreach(i; 0..m) {
    int u, v;
    scanf("%d%d", &u, &v);
    u--, v--;
    scc.addEdge(u, v);
  }
  scc.build();
  auto nn = scc.U;
  long[] cost, count;
  cost.length = nn;
  count.length = nn;
  cost.fill(1L << 28);
  foreach (v; 0..n) {
    int x = scc.group[v];
    if (cost[x] > a[v]) {
      cost[x] = a[v];
      count[x] = 0;
    }
    if (cost[x] == a[v]) {
      count[x]++;
    }
  }
  long ans_ct = 1, ans_val = 0;
  foreach (v; 0..nn) {
    ans_ct = ans_ct * count[v] % MOD;
    ans_val += cost[v];
  }
  writeln(ans_val, ' ', ans_ct);
}

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

immutable long MOD = 1000000007;

int n, m;
int[] a;
int[][] g;
int[][] rg;

int[] tsort(int[][] g) {
  auto n = cast(int)g.length;
  bool[] used;
  used.length = n;
  int[] vs;
  void dfs(int v) {
    used[v] = true;
    foreach (u; g[v]) {
      if (!used[u]) {
        dfs(u);
      }
    }
    vs ~= v;
  }
  foreach (v; 0..n) {
    if (!used[v]) {
      dfs(v);
    }
  }
  vs.reverse();
  return vs;
}

class SCC {
  int[][] g, rg;
  int V, U;
  int[] group;

  this(int n) {
    V = n;
    g.length = n;
    rg.length = n;
  }

  void addEdge(int u, int v) {
    g[u] ~= v;
    rg[v] ~= u;
  }

  void build() {
    auto vs = tsort(g);
    bool[] used;
    used.length = V;
    group.length = V;
    U = 0;
    void dfs(int v, int id) {
      group[v] = id;
      used[v] = true;
      foreach(u; rg[v]) {
        if (!used[u]) {
          dfs(u, id);
        }
      }
    }
    foreach(v; vs) {
      if (!used[v]) {
        dfs(v, U);
        U++;
      }
    }
  }

}

void main() {
  n = readln.strip.to!int;
  a = readln.split.map!(to!int).array;
  m = readln.strip.to!int;
  auto scc = new SCC(n);
  foreach(i; 0..m) {
    int u, v;
    scanf("%d%d", &u, &v);
    u--, v--;
    scc.addEdge(u, v);
  }
  scc.build();
  auto nn = scc.U;
  int[] cost, count;
  cost.length = nn;
  count.length = nn;
  cost.fill(1 << 28);
  foreach (v; 0..n) {
    int x = scc.group[v];
    if (cost[x] > a[v]) {
      cost[x] = a[v];
      count[x] = 0;
    }
    if (cost[x] == a[v]) {
      count[x]++;
    }
  }
  long ans_ct = 1, ans_val = 0;
  foreach (v; 0..nn) {
    ans_ct = ans_ct * count[v] % MOD;
    ans_val += cost[v];
  }
  writeln(ans_val, ' ', ans_ct);
}


Let's denote as  the number of bits set ('1' bits) in the binary representation of the non-negative integer x.You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and  is maximum possible. If there are multiple such numbers find the smallest of them.

The first line contains integer n — the number of queries (1 ≤ n ≤ 10000). Each of the following n lines contain two integers li, ri — the arguments for the corresponding query (0 ≤ li ≤ ri ≤ 1018).

For each query print the answer in a separate line.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		foreach (i; 0..n)
		{
			long l, r;
			readf (" %s %s", &l, &r);
			long res = 0;

			int popcntl (long x)
			{
				return popcnt (cast (uint) (x)) +
				    popcnt (cast (uint) (x >> 32));
			}

			void check (long x)
			{
				debug {writeln (x, ' ', popcntl (x));}
				if (popcntl (res) < popcntl (x) ||
				    (popcntl (res) == popcntl (x) &&
				    res > x))
				{
					res = x;
				}
			}

			check (l);
			check (r);
			foreach (j; 0..60)
			{
				long v = l | ((1L << j) - 1);
				if (v <= r)
				{
					check (v);
				}

				if (r & (1L << j))
				{
					long w = (r ^ (1L << j)) |
					    ((1L << j) - 1);
					if (w >= l)
					{
						check (w);
					}
				}
			}
			debug {writefln ("%60b\n%60b\n%60b", l, res, r);}
			writeln (res);
		}
	}
}


The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of $$$n$$$ vertices. Each vertex $$$i$$$ has its own value $$$a_i$$$. All vertices are connected in series by edges. Formally, for every $$$1 \leq i < n$$$ there is an edge between the vertices of $$$i$$$ and $$$i+1$$$.Denote the function $$$f(l, r)$$$, which takes two integers $$$l$$$ and $$$r$$$ ($$$l \leq r$$$):    We leave in the tree only vertices whose values range from $$$l$$$ to $$$r$$$.    The value of the function will be the number of connected components in the new graph. Your task is to calculate the following sum: $$$$$$\sum_{l=1}^{n} \sum_{r=l}^{n} f(l, r) $$$$$$

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of vertices in the tree. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the values of the vertices.

Print one number — the answer to the problem.

NoteIn the first example, the function values will be as follows:   $$$f(1, 1)=1$$$ (there is only a vertex with the number $$$2$$$, which forms one component)  $$$f(1, 2)=1$$$ (there are vertices $$$1$$$ and $$$2$$$ that form one component)  $$$f(1, 3)=1$$$ (all vertices remain, one component is obtained)  $$$f(2, 2)=1$$$ (only vertex number $$$1$$$)  $$$f(2, 3)=2$$$ (there are vertices $$$1$$$ and $$$3$$$ that form two components)  $$$f(3, 3)=1$$$ (only vertex $$$3$$$)  Totally out $$$7$$$.In the second example, the function values will be as follows:   $$$f(1, 1)=1$$$  $$$f(1, 2)=1$$$  $$$f(1, 3)=1$$$  $$$f(1, 4)=1$$$  $$$f(2, 2)=1$$$  $$$f(2, 3)=2$$$  $$$f(2, 4)=2$$$  $$$f(3, 3)=1$$$  $$$f(3, 4)=1$$$  $$$f(4, 4)=0$$$ (there is no vertex left, so the number of components is $$$0$$$)  Totally out $$$11$$$.

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!(to!long).array;

    long ans = A[0] * (N - A[0] + 1);

    foreach (i; 1..N) {
        if (A[i-1] < A[i]) {
            ans += (A[i] - A[i-1]) * (N - A[i] + 1);
        } else if (A[i-1] > A[i]) {
            ans += (A[i-1] - A[i]) * A[i];
        }
    }

    ans.writeln;
}

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;

    long ans = A[0] * (N - A[0] + 1) % MOD;

    foreach (i; 1..N) {
        if (A[i-1] < A[i]) {
            ans += (A[i] - A[i-1]) * (N - A[i] + 1) % MOD;
            ans %= MOD;
        } else if (A[i-1] > A[i]) {
            ans += (A[i-1] - A[i]) * A[i] % MOD;
        }
        ans %= MOD;
    }

    ans.writeln;
}


A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number. After all the swaps each compartment should either have no student left, or have a company of three or four students.

The first line contains integer n (1 ≤ n ≤ 106) — the number of compartments in the carriage. The second line contains n integers a1, a2, ..., an showing how many students ride in each compartment (0 ≤ ai ≤ 4). It is guaranteed that at least one student is riding in the train.

If no sequence of swapping seats with other people leads to the desired result, print number "-1" (without the quotes). In another case, print the smallest number of people you need to persuade to swap places.

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    int N; scanf("%d\n", &N);
    auto xs = readln.chomp.split(" ").map!(to!int).array;
    auto cs = new int[5];
    foreach (x; xs) {
        cs[x]++;
    }

    if ([1, 2, 5].count(xs.reduce!"a + b") >= 1) {
        writeln(-1);
        return;
    }

    int ans = 0;
    int t = min(cs[1], cs[2]);
    ans += t;
    cs[1] -= t; cs[2] -= t; cs[3] += t;
    assert(cs[1] == 0 || cs[2] == 0);

    if (cs[1] > 0) {
        t = cs[1] / 3;
        ans += t * 2;
        cs[1] %= 3;
        cs[3] += t;
    }
    if (cs[2] > 0) {
        t = cs[2] / 3;
        ans += t * 2;
        cs[2] %= 3;
        cs[3] += t * 2;
    }

    int count1() {
        if (cs[1] == 0) return 0;
        auto prev = cs.dup;
        int ret = int.max / 2;
        if (cs[1] >= 2 && cs[4] >= 1) {
            cs[1] -= 2; cs[3] += 2; cs[4]--;
            ret = min(ret, count1() + 2);
            cs = prev.dup;
        }
        if (cs[3] >= 1) {
            cs[1]--; cs[3]--; cs[4]++;
            ret = min(ret, count1() + 1);
            cs = prev.dup;
        }
        if (cs[4] >= 2) {
            cs[1]--; cs[3] += 3; cs[4] -= 2;
            ret = min(ret, count1() + 2);
            cs = prev.dup;
        }
        return ret;
    }

    int count2() {
        if (cs[2] == 0) return 0;
        if (cs[2] >= 2) return 2;
        if (cs[2] >= 1) {
            if (cs[4] >= 1) return 1;
            if (cs[3] >= 2) return 2;
        }
        return int.max / 2;
    }

    ans += count1();
    ans += count2();
    writeln(ans);
}


Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."The class can be represented as a matrix with n rows and m columns with a student in each cell. Two students are neighbors if cells in which they sit have a common side.Let's enumerate students from 1 to n·m in order of rows. So a student who initially sits in the cell in row i and column j has a number (i - 1)·m + j. You have to find a matrix with n rows and m columns in which all numbers from 1 to n·m appear exactly once and adjacent numbers in the original matrix are not adjacent in it, or determine that there is no such matrix.

The only line contains two integers n and m (1 ≤ n, m ≤ 105; n·m ≤ 105) — the number of rows and the number of columns in the required matrix.

If there is no such matrix, output "NO" (without quotes).  Otherwise in the first line output "YES" (without quotes), and in the next n lines output m integers which form the required matrix.

NoteIn the first test case the matrix initially looks like this:1 2 3 45 6 7 8It's easy to see that there are no two students that are adjacent in both matrices.In the second test case there are only two possible seatings and in both of them students with numbers 1 and 2 are neighbors.

/+ dub.sdl:
    name "B"
    dependency "dunkelheit" version=">=0.9.0"
+/

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

import std.math;

int n, m;
int[2][][] res;

int[] getBig(int n) {
    int[] v;
    foreach (i; 0..n) {
        if (i % 2 == 0) continue;
        v ~= i;
    }
    foreach (i; 0..n) {
        if (i % 2) continue;
        v ~= i;
    }
    return v;
}

// import dkh.dungeon;

bool check() {
    bool nei(int[2] id1, int[2] id2) {
        int dr = abs(id1[0] - id2[0]);
        int dc = abs(id1[1] - id2[1]);
        if (dr == 0 && dc == 1) return true;
        if (dr == 1 && dc == 0) return true;
        return false;
    }
    foreach (i; 0..n) {
        foreach (j; 0..m) {
            foreach (np; neighbors4([i, j], Dungeon(n, m))) {
                if (nei(res[i][j], res[np[0]][np[1]])) {
                    writeln("same ", i, " ", j, " ", np);
                    return false;
                }
            }
        }
    }
    return true;
}

bool solve() {
    if (n >= 4) {
        auto h = getBig(n);
        auto w = getBig(m);
        foreach (i; 0..n) {
            foreach (j; 0..m) {
                res[i][j] = [h[i], w[j]];
            }
        }
        return true;
    }
    if (n == 1 && m >= 4) {
        auto w = getBig(m);
        foreach (j; 0..m) {
            res[0][j] = [0, w[j]];
        }
        return true;
    }
    if (m >= 4) {
        foreach (i; 0..n) {
            foreach (j; 0..m) {
                res[i][j] = [i, j];
            }
        }
        foreach (i; 0..n) {
            if (i % 2) continue;
            bringToFront(res[i][0..2], res[i][2..$]);
        }
        foreach (j; 0..m) {
            if (j % 2) continue;
            int[2][] buf = new int[2][n];
            foreach (k; 0..n) {
                buf[k] = res[k][j];
            }
            bringToFront(buf[0..1], buf[1..$]);
            foreach (k; 0..n) {
                res[k][j] = buf[k];
            }
        }
        return true;
    }

    int[] idxBase = iota(n * m).array;
    foreach (idx; idxBase.permutations) {
        foreach (i; 0..n) {
            foreach (j; 0..m) {
                int u = idx[i*m+j];
                res[i][j] = [u/m, u%m];
            }
        }
        bool nei(int[2] id1, int[2] id2) {
            int dr = abs(id1[0] - id2[0]);
            int dc = abs(id1[1] - id2[1]);
            if (dr == 0 && dc == 1) return true;
            if (dr == 1 && dc == 0) return true;
            return false;
        }
        bool ok = true;
        foreach (i; 0..n) {
            foreach (j; 0..m) {
                foreach (np; neighbors4([i, j], Dungeon(n, m))) {
                    if (nei(res[i][j], res[np[0]][np[1]])) {
                        ok = false;
                        break;
                    }
                }
            }
        }
        if (ok) return true;
    }
    return false;
}
/*
void main() {
    foreach (d; 1..10) {
        foreach (e; d..10) {
            n = d; m = e;
            res = new int[2][][](n, m);
            bool f = solve();
//            writeln(d, " ", e, " ", f);
//            writeln(res);
            if (f) assert(check());
        }
    }
}*/

int main() {
    Scanner sc = new Scanner(stdin);
    sc.read(n, m);
    bool rev = (n > m);
    if (rev) swap(n, m);
    res = new int[2][][](n, m);
    bool f = solve();
    if (!f) {
        writeln("NO");
        return 0;
    }
    writeln("YES");
    if (rev) {
        swap(n, m);
        auto nres = new int[2][][](n, m);
        foreach (i; 0..n) {
            foreach (j; 0..m) {
                nres[i][j] = res[j][i];
                swap(nres[i][j][0], nres[i][j][1]);
            }
        }
        res = nres;
    }

    int[][] idx = new int[][](n, m);
    foreach (i; 0..n) {
        foreach (j; 0..m) {
            idx[i][j] = res[i][j][0] * m + res[i][j][1] + 1;
        }
        writeln(idx[i].map!(to!string).join(" "));
    }
    assert(check());
    return 0;
}
/* IMPORT /Users/yosupo/Program/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 /Users/yosupo/Program/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 /Users/yosupo/Program/dunkelheit/source/dkh/dungeon.d */
// module dkh.dungeon;

immutable static int[2][4] direction4 = [
    [1, 0], [0, 1], [-1, 0], [0, -1],
];

immutable static int[2][8] direction8 = [
    [1, 0],
    [1, 1],
    [0, 1],
    [-1, 1],
    [-1, 0],
    [-1, -1],
    [0, -1],
    [1, -1],
];

static int[2] addInt2(in int[2] a, in int[2] b) {
    int[2] c;
    c[] = a[] + b[];
    return c;
}

struct Dungeon {

    static int[2] move4(int[2] p, int dir) {
        return addInt2(p, direction4[dir]);
    }

    static int[2] move8(int[2] p, int dir) {
        return addInt2(p, direction8[dir]);
    }

    immutable int R, C;

    this(int R, int C) {
        this.R = R;
        this.C = C;
    }

    bool isInside(int[2] p) const {
        int r = p[0], c = p[1];
        return 0 <= r && r < R && 0 <= c && c < C;
    }

    int getID(int[2] p) const {
        int r = p[0], c = p[1];
        return r*R+c;
    }
}

auto neighbors4(int[2] p) {
    static struct Rng {
        int[2] center;
        size_t i;
        bool empty() const { return i == 4;}
        int[2] front() const { return addInt2(center, direction4[i]); }
        void popFront() { i++; }
    }
    return Rng(p, 0);
}

auto neighbors4(int[2] p, in Dungeon dg) {
    static struct Rng {
        int[2] center;
        Dungeon dg;
        size_t i;
        this(in int[2] center, in Dungeon dg) {
            this.center = center;
            this.dg = dg;
            while (!empty() && !dg.isInside(front)) i++;
        }
        bool empty() const { return i == 4;}
        int[2] front() const { return addInt2(center, direction4[i]); }
        void popFront() {
            i++;
            while (!empty() && !dg.isInside(front)) i++;
        }
    }
    return Rng(p, dg);
}

/* IMPORT /Users/yosupo/Program/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;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    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) {
                    bool f = succW();
                    assert(f);
                    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 read(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);
        }
    }
}

/*
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)
*/


Let $$$LCM(x, y)$$$ be the minimum positive integer that is divisible by both $$$x$$$ and $$$y$$$. For example, $$$LCM(13, 37) = 481$$$, $$$LCM(9, 6) = 18$$$.You are given two integers $$$l$$$ and $$$r$$$. Find two integers $$$x$$$ and $$$y$$$ such that $$$l \le x < y \le r$$$ and $$$l \le LCM(x, y) \le r$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. Each test case is represented by one line containing two integers $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le 10^9$$$).

For each test case, print two integers:   if it is impossible to find integers $$$x$$$ and $$$y$$$ meeting the constraints in the statement, print two integers equal to $$$-1$$$;  otherwise, print the values of $$$x$$$ and $$$y$$$ (if there are multiple valid answers, you may print any of them).

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int a, b;
		readf !(" %s %s") (a, b);
		if (a * 2 <= b)
		{
			writeln (a, " ", a * 2);
		}
		else
		{
			writeln (-1, " ", -1);
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (l*2 > r)
			ans[ti] = [-1, -1];
		else
			ans[ti] = [l, l*2];
	}

	foreach (e; ans)
	{
		writeln(e[0], " ", e[1]);
	}
	stdout.flush;
	debug readln;
}


Masha has $$$n$$$ types of tiles of size $$$2 \times 2$$$. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.Masha decides to construct the square of size $$$m \times m$$$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.Symmetric with respect to the main diagonal matrix is such a square $$$s$$$ that for each pair $$$(i, j)$$$ the condition $$$s[i][j] = s[j][i]$$$ holds. I.e. it is true that the element written in the $$$i$$$-row and $$$j$$$-th column equals to the element written in the $$$j$$$-th row and $$$i$$$-th column.Your task is to determine if Masha can construct a square of size $$$m \times m$$$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 100$$$) — the number of types of tiles and the size of the square Masha wants to construct. The next $$$2n$$$ lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines.  The first line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the bottom left corner of the tile and the number written in the bottom right corner of the tile of the current type. It is forbidden to rotate tiles, it is only allowed to place them in the orientation they have in the input.

For each test case print the answer: "YES" (without quotes) if Masha can construct the square of size $$$m \times m$$$ which is a symmetric matrix. Otherwise, print "NO" (withtout quotes).

NoteThe first test case of the input has three types of tiles, they are shown on the picture below.  Masha can construct, for example, the following square of size $$$4 \times 4$$$ which is a symmetric matrix:

// Vicfred
// https://codeforces.com/contest/1426/problem/B
// greedy
import std.stdio;

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

    int n, m;
    int a, b, c, d;
    while(t--) {
        readf("%s %s\n", &n, &m);
        bool found = false;
        for(int i = 0; i < n; ++i) {
            readf("%s %s\n%s %s\n", &a, &b, &c, &d);
            if(b == c)
                found = true;
        }
        if(m%2 == 1)
            found = false;
        if(found)
            "YES".writeln;
        else
            "NO".writeln;
    }
}

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
/*******************************It's a Me, Mario!*******************************************/

void play(){
    int n, m;
    n = rd!int;
    m = rd!int;
    bool sym = 0, sym2 = 0;
    ll a, b, c, d;
    foreach(i; 0..n){
        a = rd;
        b = rd;
        c = rd;
        d = rd;
        if(b == c){ sym = 1; }
    }
    if(sym && m % 2 == 0){
            writeln("YES");
    }else{
        writeln("NO");
    }
}

int main(){
    long t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
/*******************************It's a Me, Mario!*******************************************/

void play(){
    int n, m;
    n = rd!int;
    m = rd!int;
    bool sym = 0, sym2 = 0;
    ll a, b, c, d;
    foreach(i; 0..n){
        a = rd;
        b = rd;
        c = rd;
        d = rd;
        if(b == c){ sym = 1; }
        if(a == d && b == c){ sym2 = 1; }
    }
    if(sym && m % 2 == 0){
        if(m == 2 && !sym2){
            writeln("NO");
        }else{
            writeln("YES");
        }
    }else{
        writeln("NO");
    }
}

int main(){
    long t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
/*******************************It's a Me, Mario!*******************************************/

void play(){
    int n, m;
    n = rd!int;
    m = rd!int;
    bool sym = 0, sym2 = 0;
    ll a, b, c, d;
    foreach(i; 0..n){
        a = rd;
        b = rd;
        c = rd;
        d = rd;
        if(a == d){ sym = 1; }
        if(a == d && b == c){ sym2 = 1; }
    }
    if(sym && m % 2 == 0){
        if(m == 2 && !sym2){
            writeln("NO");
        }else{
            writeln("YES");
        }
    }else{
        writeln("NO");
    }
}

int main(){
    long t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}


You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.

The first line of the input contains two integers n, k (1 ≤ k ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103), where ai is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task. It is guaranteed that n is divisible by k.

In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.

NoteExplanation of the first example.If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12. Explanation of the second example.In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3.

import std.stdio;

void main() {
    debug stdin = File("input.txt", "r");

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

    int[] a = new int[n];
    foreach (ref x; a) {
        readf(" %s", &x);
    }

    int[] sum = new int[k];
    foreach (i; 0 .. n) {
        sum[i % k] += a[i];
    }

    int best = 0;
    foreach(i; 1 .. k) {
        if (sum[i] < sum[best]) {
            best = i;
        }
    }

    writeln(best + 1);
}


AquaMoon has $$$n$$$ friends. They stand in a row from left to right, and the $$$i$$$-th friend from the left wears a T-shirt with a number $$$a_i$$$ written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.AquaMoon hopes that after some operations, the numbers written on the T-shirt of $$$n$$$ friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 50$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of Aquamoon's friends. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — the numbers, written on the T-shirts. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteThe possible list of operations in the first test case:  Swap $$$a_1$$$ and $$$a_2$$$. The resulting sequence is $$$3, 4, 2, 5$$$. The directions are: left, left, right, right.  Swap $$$a_2$$$ and $$$a_3$$$. The resulting sequence is $$$3, 2, 4, 5$$$. The directions are: left, left, right, right.  Swap $$$a_1$$$ and $$$a_2$$$. The resulting sequence is $$$2, 3, 4, 5$$$. The directions are: right, right, right, right.

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()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n, i, j, k;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!int).array;
    auto b = zip(a, iota(0, n)).array.sort!((x, y) => x[0] < y[0]).array;
    bool good = true;
    i = 0;
    while (i < n) {
      j = i;
      while (j < n && b[i][0] == b[j][0])
        j++;
      int[2] tmp = [0, 0];
      for (k = i; k < j; k++) {
        tmp[k % 2] += abs(b[k][1] - k) % 2;
      }
      if (tmp[0] != tmp[1]) {
        good = false;
        break;
      }
      i = j;
    }
    writeln(good ? "YES" : "NO");
  }
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
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 bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;

		long[][long] cnt;
		foreach (e; a)
			cnt[e] = [0, 0];

		auto index = a.MAKE_IDX;
		foreach (ii, i; index)
		{
			auto j = ii % 2;
			++cnt[a[i]][j];
		}

		ans[ti] = true;
		foreach (i; 0..n)
		{
			auto j = i % 2;
			if (cnt[a[i]][j] == 0)
			{
				ans[ti] = false;
				break;
			}
			else
				--cnt[a[i]][j];
		}
	}

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

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    immutable(int) Maxn = 10 ^^ 5 + 5;
    int n; readf!"%s\n"(n);
    auto a = readln.splitter.map!(to!int).array;
    auto b = a.dup.sort;
    int[Maxn][2] c;
    foreach(i; 0 .. n) {
      c[i % 2][b[i]]++;
    }
    bool ok = true;
    foreach(i; 0 .. n) {
      if (c[i % 2][a[i]] == 0) {
        ok = false;
        break;
      }
      c[i % 2][a[i]]--;
    }
    writefln!"%s"(ok ? "YES" : "NO");
  }

} // main

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a.stride (2));
		sort (a.drop (1).stride (2));
		writeln (a.isSorted ? "YES" : "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()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n, i, j, k;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!int).array;
    auto b = zip(a, iota(0, n)).array.sort!((x, y) => x[0] < y[0]).array;
    bool good = true;
    i = 0;
    while (i < n) {
      if (abs(b[i][1] - i) % 2 != 0) {
        if (i + 1 < n && b[i][0] == b[i + 1][0] && abs(b[i + 1][1] - (i + 1)) % 2 != 0) {
          // L L pattern (we can change it to R R)
          swap(b[i], b[i + 1]);
          continue;
        } else if (i + 2 < n && b[i][0] == b[i + 2][0] && abs(b[i + 2][1] - (i + 2)) % 2 == 0) {
          // L R R pattern (we can change it to L L L)
          swap(b[i + 1], b[i + 2]);
          continue;
        } else {
          good = false;
          break;
        }
      }
      i++;
    }
    writeln(good ? "YES" : "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()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n, i, j, k;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!int).array;
    auto b = zip(a, iota(0, n)).array.sort!((x, y) => x[0] < y[0]).array;
    bool good = true;
    i = 0;
    while (i < n) {
      if (abs(b[i][1] - i) % 2 != 0) {
        if (i + 1 < n && b[i][0] == b[i + 1][0] && abs(b[i + 1][1] - (i + 1)) % 2 != 0)
          i++;
        else
          good = false;
      }
      i++;
    }
    writeln(good ? "YES" : "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()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n, i, j, k;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!int).array;
    auto b = zip(a, iota(0, n)).array.sort!((x, y) => x[0] < y[0]).array;
    bool good = true;
    i = 0;
    while (i < n) {
      if (abs(b[i][1] - i) % 2 != 0) {
        if (i + 1 < n && b[i][0] == b[i + 1][0] && abs(b[i + 1][1] - (i + i)) % 2 != 0)
          i++;
        else
          good = false;
      }
      i++;
    }
    writeln(good ? "YES" : "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()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n, i, j, k;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!int).array;
    auto b = zip(a, iota(0, n)).array.sort!((x, y) => x[0] < y[0]).array;
    bool good = true;
    i = 0;
    while (i < n) {
      j = i;
      while (j < n && b[i][0] == b[j][0])
        j++;
      int tmp = 0;
      for (k = i; k < j; k++) {
        tmp += abs(b[k][1] - k) % 2;
      }
      if (tmp % 2 != 0) {
        good = false;
        break;
      }
      i = j;
    }
    writeln(good ? "YES" : "NO");
  }
}