You are given a positive integer $$$x$$$. Find any such $$$2$$$ positive integers $$$a$$$ and $$$b$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$.As a reminder, $$$GCD(a,b)$$$ is the greatest integer that divides both $$$a$$$ and $$$b$$$. Similarly, $$$LCM(a,b)$$$ is the smallest integer such that both $$$a$$$ and $$$b$$$ divide it.It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$  — the number of testcases. Each testcase consists of one line containing a single integer, $$$x$$$ $$$(2 \le x \le 10^9)$$$.

For each testcase, output a pair of positive integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9)$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$. It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.

NoteIn the first testcase of the sample, $$$GCD(1,1)+LCM(1,1)=1+1=2$$$.In the second testcase of the sample, $$$GCD(6,4)+LCM(6,4)=2+12=14$$$.

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

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

void solve(){
    foreach(_; 0 .. scan!int){
        long x = scan!long;
        print(1, x - 1);
    }
}

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		readf(" %d", &a);
		writeln(1);
		writeln(a-1);
	}
	return 0;
}


IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting.Today, when IA looked at the fridge, she noticed that the word formed by magnets is really messy. "It would look much better when I'll swap some of them!" — thought the girl — "but how to do it?". After a while, she got an idea. IA will look at all prefixes with lengths from $$$1$$$ to the length of the word and for each prefix she will either reverse this prefix or leave it as it is. She will consider the prefixes in the fixed order: from the shortest to the largest. She wants to get the lexicographically smallest possible word after she considers all prefixes. Can you help her, telling which prefixes should be chosen for reversing?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first and the only line contains a string $$$s$$$ ($$$1 \le |s| \le 1000$$$), describing the initial string formed by magnets. The string $$$s$$$ consists only of characters 'a' and 'b'.

Output exactly $$$|s|$$$ integers. If IA should reverse the $$$i$$$-th prefix (that is, the substring from $$$1$$$ to $$$i$$$), the $$$i$$$-th integer should be equal to $$$1$$$, and it should be equal to $$$0$$$ otherwise. If there are multiple possible sequences leading to the optimal answer, print any of them.

NoteIn the first example, IA can reverse the second and the third prefix and get a string "abbb". She cannot get better result, since it is also lexicographically smallest string obtainable by permuting characters of the initial string.In the second example, she can reverse any subset of prefixes — all letters are 'a'.

import std.range;
import std.stdio;
import std.string;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto n = s.length;
		int last = 'b';
		int [] ans;
		foreach_reverse (c; s)
		{
			if (c == last)
			{
				ans ~= 0;
			}
			else
			{
				ans ~= 1;
				last = 'a' + 'b' - last;
			}
		}
		writefln ("%(%s %)", ans.retro);
	}
}

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

int [] solve (bool [] s)
{
	if (s.length < 2)
	{
		return [];
	}
	auto res = solve (s[0..$ - 1]);
	if (s[$ - 2] == s[$ - 1])
	{
		return res ~ 0;
	}
	else
	{
		reverse (s[0..$ - 1]);
		return res ~ 1;
	}
}

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto t = s.map !(c => c == 'b').array ~ true;
		writefln ("%(%s %)", solve (t));
	}
}


You found a useless array $$$a$$$ of $$$2n$$$ positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of $$$a$$$.It could have been an easy task, but it turned out that you should follow some rules:   In the beginning, you select any positive integer $$$x$$$. Then you do the following operation $$$n$$$ times:   select two elements of array with sum equals $$$x$$$;  remove them from $$$a$$$ and replace $$$x$$$ with maximum of that two numbers.  For example, if initially $$$a = [3, 5, 1, 2]$$$, you can select $$$x = 6$$$. Then you can select the second and the third elements of $$$a$$$ with sum $$$5 + 1 = 6$$$ and throw them out. After this operation, $$$x$$$ equals $$$5$$$ and there are two elements in array: $$$3$$$ and $$$2$$$. You can throw them out on the next operation.Note, that you choose $$$x$$$ before the start and can't change it as you want between the operations.Determine how should you behave to throw out all elements of $$$a$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \leq n \leq 1000$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \leq a_i \leq 10^6$$$) — the initial array $$$a$$$. It is guaranteed that the total sum of $$$n$$$ over all test cases doesn't exceed $$$1000$$$.

For each test case in the first line print YES if it is possible to throw out all elements of the array and NO otherwise. If it is possible to throw out all elements, print the initial value of $$$x$$$ you've chosen. Print description of $$$n$$$ operations next. For each operation, print the pair of integers you remove.

NoteThe first test case was described in the statement.In the second and third test cases, we can show that it is impossible to throw out all elements of array $$$a$$$.

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()
{
    auto t = readln.chomp.to!int;

    while (t--) {
        auto n = readln.chomp.to!int;
        auto arr = readln.chomp.split.map!(to!int).array;

        arr.sort();

        bool found = false;
        foreach (start; 0 .. 2*n - 1) {
            int[int] cnt;
            foreach (e; arr) { ++cnt[e]; }
            Tuple!(int, int)[] result;

            int x = arr[2*n-1] + arr[start];
            int pos = 2*n-1;
            while (pos >= 0) {
                if (cnt[arr[pos]] == 0) {
                    --pos;
                    continue;
                }

                int now = arr[pos];
                --cnt[now];

                int need = x - now;
                debug { writeln("pos ", pos, " now: ", now, " need: ", need); }
                if (need !in cnt || cnt[need] == 0) {
                    break;
                }

                --cnt[need];
                result ~= tuple(need, now);

                x = now;

                --pos;
            }

            if (result.length == n) {
                writeln("YES");
                writeln(result[0][0] + result[0][1]);
                foreach (r; result) { writeln(r[0], ' ', r[1]); }
                found = true;
                break;
            }
        }

        if (!found) { writeln("NO"); }
    }
}

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int N; get(N);
        int[] AA; get(AA);
        sort(AA);
        foreach (i; 0..N*2-1) {
            int[][int] memo;
            foreach_reverse (j, a; AA[0..$-1]) if (i != j) memo[a] ~= j.to!int;
            auto aa = new int[](N);
            aa[0] = AA[$-1];
            auto bb = new int[](N);
            bb[0] = AA[i];
            auto j = N*2 - 1;
            if (i == j) --j;
            auto fs = new bool[](N * 2);
            fs[$-1] = fs[i] = true;
            foreach (k; 1..N) {
                auto x = aa[k-1];
                while (fs[j]) --j;
                auto a = AA[j];
                memo[a].popFront();
                fs[j] = true;
                --j;
                auto b = x - a;
                if (b !in memo || memo[b].empty) goto ng;
                fs[memo[b].front] = true;
                memo[b].popFront();
                aa[k] = a;
                bb[k] = b;
            }
            writeln("YES\n", aa[0] + bb[0]);
            foreach (k; 0..N) writeln(aa[k], " ", bb[k]);
            goto ok;
            ng:
        }
        writeln("NO");
        continue;
        ok:
    }
}

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

immutable int limit = 10 ^^ 6 + 1;

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);
		RedBlackTree !(int, q{a < b}, true) t;

		int [2] [] solve (int lo, int hi)
		{
			int [2] [] answer = [[lo, hi]];
			int cur = hi;
			foreach (j; 0..n - 1)
			{
				auto two = t.back;
				t.removeBack ();
				auto one = cur - two;
				if (one !in t)
				{
					return null;
				}
				t.removeKey (one);
				answer ~= [one, two];
				cur = two;
			}
			return answer;
		}

		auto hi = a.back;
		a.popBack ();
		auto t0 = redBlackTree !(true, int) (a);
		int [2] [] answer;
		foreach (ref b; a)
		{
			t = t0.dup;
			t.removeKey (b);
			answer = solve (b, hi);
			if (answer !is null)
			{
				break;
			}
		}

		if (answer !is null)
		{
			writeln ("YES");
			writeln (answer.front[].sum);
			writefln !("%(%(%s %)\n%)") (answer);
		}
		else
		{
			writeln ("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()
{
    immutable int MAXN = 10 ^^ 6;

    auto cnt = new int[] (MAXN + 23);

    auto t = readln.chomp.to!int;

    while (t--) {
        auto n = readln.chomp.to!int;
        auto arr = readln.chomp.split.map!(to!int).array;

        arr.sort();

        bool found = false;
        foreach (start; 0 .. 2*n - 1) {
            foreach (e; arr) { cnt[e] = 0; }
            foreach (e; arr) { ++cnt[e]; }
            Tuple!(int, int)[] result;

            int x = arr[2*n-1] + arr[start];
            int pos = 2*n-1;
            while (pos >= 0) {
                if (cnt[arr[pos]] == 0) {
                    --pos;
                    continue;
                }

                int now = arr[pos];
                cnt[now] -= 1;

                int need = x - now;
                debug { writeln("pos ", pos, " now: ", now, " need: ", need); }
                if (cnt[need] == 0) {
                    break;
                }

                --cnt[need];
                result ~= tuple(need, now);

                x = now;

                --pos;
            }

            if (result.length == n) {
                writeln("YES");
                writeln(result[0][0] + result[0][1]);
                foreach (r; result) { writeln(r[0], ' ', r[1]); }
                found = true;
                break;
            }
        }

        if (!found) { writeln("NO"); }
    }
}


Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web.  There are n main threads going from the center of the web. All main threads are located in one plane and divide it into n equal infinite sectors. The sectors are indexed from 1 to n in the clockwise direction. Sectors i and i + 1 are adjacent for every i, 1 ≤ i < n. In addition, sectors 1 and n are also adjacent.Some sectors have bridge threads. Each bridge connects the two main threads that make up this sector. The points at which the bridge is attached to the main threads will be called attachment points. Both attachment points of a bridge are at the same distance from the center of the web. At each attachment point exactly one bridge is attached. The bridges are adjacent if they are in the same sector, and there are no other bridges between them.A cell of the web is a trapezoid, which is located in one of the sectors and is bounded by two main threads and two adjacent bridges. You can see that the sides of the cell may have the attachment points of bridges from adjacent sectors. If the number of attachment points on one side of the cell is not equal to the number of attachment points on the other side, it creates an imbalance of pulling forces on this cell and this may eventually destroy the entire web. We'll call such a cell unstable. The perfect web does not contain unstable cells.Unstable cells are marked red in the figure. Stable cells are marked green.Paw the Spider isn't a skillful webmaker yet, he is only learning to make perfect webs. Help Paw to determine the number of unstable cells in the web he has just spun.

The first line contains integer n (3 ≤ n ≤ 1000) — the number of main threads. The i-th of following n lines describe the bridges located in the i-th sector: first it contains integer ki (1 ≤ ki ≤ 105) equal to the number of bridges in the given sector. Then follow ki different integers pij (1 ≤ pij ≤ 105; 1 ≤ j ≤ ki). Number pij equals the distance from the attachment points of the j-th bridge of the i-th sector to the center of the web. It is guaranteed that any two bridges between adjacent sectors are attached at a different distance from the center of the web. It is guaranteed that the total number of the bridges doesn't exceed 105.

Print a single integer — the number of unstable cells in Paw the Spider's web.

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

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

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

        arr[i] = readln.chomp.split.map!(to!int).array.sort().array;
    }

    debug { arr.each!writeln; }

    int ans = 0;
    foreach (i; 0 .. n) {
        int go(int c, ref int st, int e) {
            int ans = 0;
            while (st < arr[c].length && arr[c][st] < e) {
                ++st;
                ++ans;
            }

            return ans;
        }

        int prv = (i - 1 + n) % n;
        int nxt = (i + 1) % n;

        int cidx = 0, pidx = 0, nidx = 0;
        while (cidx < arr[i].length) {
            int cle = go(prv, pidx, arr[i][cidx]);
            int cr = go(nxt, nidx, arr[i][cidx]);

            if (cidx > 0 && cle != cr) {
                ++ans;

                debug { writeln(i, ' ', cidx, ' ', cle, ' ', cr); }
            }

            ++cidx;
        }
    }

    ans.writeln;
}

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

alias ll = long;
alias rbt = RedBlackTree;
alias sr = SortedRange;
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 solve(){
    int n;
    n = rd!int;
    SortedRange!(ll[])[] sectors;
    foreach(i; 0..n){
        sectors ~= sort(rdarr[1..$]);
    }
    // Check each cell in sector left & right
    ll cnt = 0;
    foreach(i; 0..n){
        int l = (i - 1 + n) % n;
        int r = (i + 1) % n;
        ll lold, rold;
        // writeln(sectors[i].length);
        foreach(k; 0..sectors[i].length){
            ll lnew = sectors[l].lowerBound(sectors[i][k]).length;
            ll rnew = sectors[r].lowerBound(sectors[i][k]).length;
            if(k != 0){
                ll lside = lnew - lold;
                ll rside = rnew - rold;
                if(lside != rside) ++cnt;
                /* debug writeln(lside, " | ", rside, " | ", i, " ", k); */
            }
            lold = lnew;
            rold = rnew;
        }
    }
    writeln(cnt);
}

void main(){
    long t = 1;
    /* t = rd; */
    while(t--) solve();
    stdout.flush;
}


Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.

The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000). After that, there are two strings s and t, consisting of n lowercase Latin letters each.

If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number  - 1. Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n;
	read(n);
	auto ss = readln.strip;
	auto tt = readln.strip;
	char[] s, t;
	foreach (c; ss)
	{
		s ~= c;
	}
	foreach (c; tt)
	{
		t ~= c;
	}
	int[] ans;
	foreach (i; 0 .. n)
	{
		char c = t[n - i - 1];
		debug writeln(c);
		int pos = -1;
		foreach (j; i .. n)
		{
			if (s[j] == c)
			{
				pos = j;
				break;
			}
		}
		if (pos == -1)
			return writeln(-1);
		ans ~= n;
		reverse(s);
		pos = n - pos - 1;
		ans ~= n - pos - 1;
		reverse(s[pos + 1 .. n]);
		s = s[pos .. n] ~ s[0 .. pos];
		ans ~= 1;
	}
	writeln(ans.length);
	foreach (x; ans)
	{
		write(x, ' ');
	}
}

import core.bitop;
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;

int [] solve (int n, string s, string t)
{
	auto lo = n / 2;
	auto hi = lo;
	int [] res;

	string op (string s, int x)
	in
	{
		debug {writeln ("op ", s, " ", x);}
	}
	out (ans)
	{
		debug {writeln (ans);}
	}
	body
	{
		res ~= x;
		return s[$ - x..$].retro.text ~ s[0..$ - x];
	}

	while (hi - lo < n)
	{
		debug {writeln (lo, " ", hi);}
		if ((hi - lo) & 1)
		{
			auto p = s.drop (hi - lo).countUntil (t[lo - 1]);
			debug {writeln (p);}
			if (p == -1)
			{
				return [];
			}
			s = op (s, n - hi + lo - p);
			s = op (s, p);
			s = op (s, n);
			lo -= 1;
		}
		else
		{
			auto p = s.drop (hi - lo).countUntil (t[hi]);
			debug {writeln (p);}
			if (p == -1)
			{
				return [];
			}
			s = op (s, n - hi + lo - p);
			s = op (s, p);
			s = op (s, n);
			hi += 1;
		}
	}
	if (s != t)
	{
		s = op (s, n);
	}
	return res;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.strip;
		auto t = readln.strip;
		auto res = solve (n, s, t);
		if (res.empty)
		{
			writeln (-1);
		}
		else
		{
			writeln (res.length);
			writefln ("%(%s %)", res);
		}
	}
}

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

int [] g (S) (int n, S s, S t) {
	auto x = n / 2, y = x, r = [0];

	void f (int x) {
		r ~= x;
		s = s[$ - x..$].retro.text ~ s[0..$ - x];
	}

	while (y - x < n) {
		auto z = (y ^ x) & 1, p = s[y - x..$].countUntil (z ? t[x - 1] : t[y]);
		if (p < 0) return [];
		f (n - y + x - p); f (p); f (n);
		if (z) x -= 1; else y += 1;
	}
	if (s != t) f (n);
	return r;
}

void main () {
	auto n = readln.strip.to!int, s = readln.strip, t = readln.strip, r = g (n, s, t);
	writefln ("%s\n%(%s %)", r.length.to!int - 1, r.drop (1));
}

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

int [] solve (int n, string s, string t) {
	int lo = n / 2, hi = lo;
	int [] res;

	string op (string s, int x) {
		res ~= x;
		return s[$ - x..$].retro.text ~ s[0..$ - x];
	}

	while (hi - lo < n) {
		auto x = (hi ^ lo) & 1;
		auto p = s.drop (hi - lo).countUntil (x ? t[lo - 1] : t[hi]);
		if (p == -1) return [];
		s = op (s, n - hi + lo - p);
		s = op (s, p);
		s = op (s, n);
		if (x) lo -= 1;
		else hi += 1;
	}
	if (s != t) s = op (s, n);
	return res;
}

void main () {
	auto n = readln.strip.to!int, s = readln.strip, t = readln.strip;
	auto res = solve (n, s, t);
	if (res.empty) writeln (-1);
	else writefln ("%s\n%(%s %)", res.length, res);
}


You are given a sequence $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, and an integer $$$x$$$. Your task is to make the sequence $$$a$$$ sorted (it is considered sorted if the condition $$$a_1 \le a_2 \le a_3 \le \dots \le a_n$$$ holds).To make the sequence sorted, you may perform the following operation any number of times you want (possibly zero): choose an integer $$$i$$$ such that $$$1 \le i \le n$$$ and $$$a_i > x$$$, and swap the values of $$$a_i$$$ and $$$x$$$.For example, if $$$a = [0, 2, 3, 5, 4]$$$, $$$x = 1$$$, the following sequence of operations is possible:  choose $$$i = 2$$$ (it is possible since $$$a_2 > x$$$), then $$$a = [0, 1, 3, 5, 4]$$$, $$$x = 2$$$;  choose $$$i = 3$$$ (it is possible since $$$a_3 > x$$$), then $$$a = [0, 1, 2, 5, 4]$$$, $$$x = 3$$$;  choose $$$i = 4$$$ (it is possible since $$$a_4 > x$$$), then $$$a = [0, 1, 2, 3, 4]$$$, $$$x = 5$$$. Calculate the minimum number of operations you have to perform so that $$$a$$$ becomes sorted, or report that it is impossible.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500$$$, $$$0 \le x \le 500$$$) — the number of elements in the sequence and the initial value of $$$x$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 500$$$). The sum of values of $$$n$$$ over all test cases in the input does not exceed $$$500$$$.

For each test case, print one integer — the minimum number of operations you have to perform to make $$$a$$$ sorted, or $$$-1$$$, if it is impossible.

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, x;
		readf !(" %s %s") (n, x);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		int pos = 0;
		int steps = 0;
		while (pos < n && !a.isSorted)
		{
			while (pos < n && a[pos] <= x)
			{
				pos += 1;
			}
			if (pos < n)
			{
				swap (x, a[pos]);
				steps += 1;
			}
		}
		writeln (a.isSorted ? steps : -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(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

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

		bool ok = true;
		foreach (i; 1..n)
		{
			if (a[i] < a[i-1])
			{
				ok = false;
			}
		}
		if (ok) continue;

		ok = true;
		foreach (i; 0..n)
		{
			if (a[i] > x)
			{
				swap(a[i], x);
				++ans[ti];
				bool done = true;
				foreach (j; i+1..n)
				{
					if (a[j] < a[j-1])
					{
						done = false;
						break;
					}
				}
				if (done) break;
			}
			else if (a[i] < a[i-1])
			{
				ok = false;
			}
		}
		if (!ok)
			ans[ti] = -1;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		bool ok = true;
		foreach (i; 1..n)
		{
			if (a[i] < a[i-1])
			{
				ok = false;
			}
		}
		if (ok) continue;

		ok = true;
		foreach (i; 0..n)
		{
			if (a[i] > x)
			{
				swap(a[i], x);
				++ans[ti];
			}
			else if (a[i] < a[i-1])
			{
				ok = false;
			}
		}
		if (!ok)
			ans[ti] = -1;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		bool ok = true;
		foreach (i; 1..n)
		{
			if (a[i] < a[i-1])
			{
				ok = false;
			}
		}
		if (ok) continue;

		ok = true;
		foreach (i; 0..n)
		{
			if (i == n-1 && a[i] >= a[i-1]) continue;
			if (a[i] > x)
			{
				swap(a[i], x);
				++ans[ti];
			}
			else if (a[i] < a[i-1])
			{
				ok = false;
			}
		}
		if (!ok)
			ans[ti] = -1;
	}

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


Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all $$$26$$$ lowercase Latin letters will be arranged in some order.Polycarp uses the same password $$$s$$$ on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in $$$s$$$, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in $$$s$$$, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Then $$$T$$$ lines follow, each containing one string $$$s$$$ ($$$1 \le |s| \le 200$$$) representing the test case. $$$s$$$ consists of lowercase Latin letters only. There are no two adjacent equal characters in $$$s$$$.

For each test case, do the following:   if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of $$$26$$$ lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them.

5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza

YES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

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

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

void solve(){
	A: foreach(_; 0 .. rint){
		string s = readln.chomp;
		int[] as = s.map!(c => (c - 'a').to!int).array;
		int n = s.length.to!int;

		if(n == 1){
			"YES".writeln;
			"abcdefghijklmnopqrstuvwxyz".writeln;
			continue A;
		}

		bool[][] xf = new bool[][](26, 26);
		foreach(i; 0 .. n - 1){
			int a = as[i], b = as[i + 1];
			xf[a][b] = 1, xf[b][a] = 1;
		}

		int start = -1, end = -1;
		int[] cnt = new int[](26);
		foreach(a; 0 .. 26){
			foreach(b; 0 .. 26){
				if(xf[a][b]) cnt[a] += 1;
			}
			if(cnt[a] > 2){
				"NO".writeln;
				continue A;
			}
			if(cnt[a] == 1){
				if(start < 0) start = a;
				else end = a;
			}
		}

		if(start < 0){
			"NO".writeln;
			continue A;
		}

		"YES".writeln;

		int x = start;
		int oldx = -1;
		write("abcdefghijklmnopqrstuvwxyz"[x]);
		while(x != end){
			foreach(b; 0 .. 26) if(xf[x][b] && b != oldx){
				oldx = x;
				x = b;
				break;
			}
			write("abcdefghijklmnopqrstuvwxyz"[x]);
		}

		foreach(a; 0 .. 26) if(cnt[a] == 0) write("abcdefghijklmnopqrstuvwxyz"[a]);
		writeln("");
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto T = RD!int;
	auto ans = new string[](T);
	foreach (ti; 0..T)
	{
		auto s = RD!string;
		auto edges = new bool[][](26, 26);
		if (s.length == 2)
		{
			auto l = s[0]-'a';
			auto r = s[1]-'a';
			edges[l][r] = true;
			edges[r][l] = true;
		}
		foreach (i; 1..s.length-1)
		{
			auto m = s[i]-'a';
			auto l = s[i-1]-'a';
			auto r = s[i+1]-'a';
			edges[m][l] = true;
			edges[m][r] = true;
			edges[l][m] = true;
			edges[r][m] = true;
		}
		bool ok = true;
		int[] list;
		foreach (i, e; edges)
		{
			int cnt;
			foreach (ee; e)
			{
				if (ee)
					++cnt;
			}
			if (cnt >= 3)
			{
				ok = false;
				break;
			}
			else if (cnt == 1)
			{
				list ~= cast(int)i;
			}
			else if (cnt == 0)
			{
				ans[ti] ~= cast(char)(i+'a');
			}
		}
		debug writeln(ans[ti]);
		if (!ok)
		{
			ans[ti] = [];
			continue;
		}

		auto used = new int[](26);
		void dfs(int i, int par)
		{
			used[i] = true;
			ans[ti] ~= cast(char)(i+'a');
			foreach (j; 0..26)
			{
				if (j == par) continue;
				if (edges[i][j])
				{
					dfs(j, i);
				}
			}
		}

		foreach (e; list)
		{
			if (used[e] == false)
				dfs(e, -1);
		}
		debug writeln(ans[ti]);
		if (ans[ti].length != 26)
			ans[ti] = [];
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			writeln(e);
		}
	}
	stdout.flush;
	debug readln;
}

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

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

void solve(){
	A: foreach(_; 0 .. rint){
		string s = readln.chomp;
		int[] as = s.map!(c => (c - 'a').to!int).array;
		int n = s.length.to!int;
		bool[][] xf = new bool[][](26, 26);
		foreach(i; 0 .. n - 1){
			int a = as[i], b = as[i + 1];
			xf[a][b] = 1, xf[b][a] = 1;
		}

		int start = -1, end = -1;
		int[] cnt = new int[](26);
		foreach(a; 0 .. 26){
			foreach(b; 0 .. 26){
				if(xf[a][b]) cnt[a] += 1;
			}
			if(cnt[a] > 2){
				"NO".writeln;
				continue A;
			}
			if(cnt[a] == 1){
				if(start < 0) start = a;
				else end = a;
			}
		}

		if(start < 0){
			"NO".writeln;
			continue A;
		}

		int x = start;
		int oldx = -1;
		write("abcdefghijklmnopqrstuvwxyz"[x]);
		while(x != end){
			foreach(b; 0 .. 26) if(xf[x][b] && b != oldx){
				oldx = x;
				x = b;
				break;
			}
			write("abcdefghijklmnopqrstuvwxyz"[x]);
		}

		foreach(a; 0 .. 26) if(cnt[a] == 0) write("abcdefghijklmnopqrstuvwxyz"[a]);
		writeln("");
	}
}

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

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

void solve(){
	A: foreach(_; 0 .. rint){
		string s = readln.chomp;
		int[] as = s.map!(c => (c - 'a').to!int).array;
		int n = s.length.to!int;
		bool[][] xf = new bool[][](26, 26);
		foreach(i; 0 .. n - 1){
			int a = as[i], b = as[i + 1];
			xf[a][b] = 1, xf[b][a] = 1;
		}

		int start = -1, end = -1;
		int[] cnt = new int[](26);
		foreach(a; 0 .. 26){
			foreach(b; 0 .. 26){
				if(xf[a][b]) cnt[a] += 1;
			}
			if(cnt[a] > 2){
				"NO".writeln;
				continue A;
			}
			if(cnt[a] == 1){
				if(start < 0) start = a;
				else end = a;
			}
		}

		if(start < 0){
			"NO".writeln;
			continue A;
		}

		"YES".writeln;

		int x = start;
		int oldx = -1;
		write("abcdefghijklmnopqrstuvwxyz"[x]);
		while(x != end){
			foreach(b; 0 .. 26) if(xf[x][b] && b != oldx){
				oldx = x;
				x = b;
				break;
			}
			write("abcdefghijklmnopqrstuvwxyz"[x]);
		}

		foreach(a; 0 .. 26) if(cnt[a] == 0) write("abcdefghijklmnopqrstuvwxyz"[a]);
		writeln("");
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto T = RD!int;
	auto ans = new string[](T);
	foreach (ti; 0..T)
	{
		auto s = RD!string;
		auto edges = new bool[][](26, 26);
		foreach (i; 1..s.length-1)
		{
			auto m = s[i]-'a';
			auto l = s[i-1]-'a';
			auto r = s[i+1]-'a';
			edges[m][l] = true;
			edges[m][r] = true;
			edges[l][m] = true;
			edges[r][m] = true;
		}
		bool ok = true;
		int[] list;
		foreach (i, e; edges)
		{
			int cnt;
			foreach (ee; e)
			{
				if (ee)
					++cnt;
			}
			if (cnt >= 3)
			{
				ok = false;
				break;
			}
			else if (cnt == 1)
			{
				list ~= cast(int)i;
			}
			else if (cnt == 0)
			{
				ans[ti] ~= cast(char)(i+'a');
			}
		}
		debug writeln(ans[ti]);
		if (!ok)
		{
			ans[ti] = [];
			continue;
		}

		auto used = new int[](26);
		void dfs(int i, int par)
		{
			used[i] = true;
			ans[ti] ~= cast(char)(i+'a');
			foreach (j; 0..26)
			{
				if (j == par) continue;
				if (edges[i][j])
				{
					dfs(j, i);
				}
			}
		}

		foreach (e; list)
		{
			if (used[e] == false)
				dfs(e, -1);
		}
		debug writeln(ans[ti]);
		if (ans[ti].length != 26)
			ans[ti] = [];
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			writeln(e);
		}
	}
	stdout.flush;
	debug readln;
}


Theofanis started playing the new online game called "Among them". However, he always plays with Cypriot players, and they all have the same name: "Andreas" (the most common name in Cyprus).In each game, Theofanis plays with $$$n$$$ other players. Since they all have the same name, they are numbered from $$$1$$$ to $$$n$$$.The players write $$$m$$$ comments in the chat. A comment has the structure of "$$$i$$$ $$$j$$$ $$$c$$$" where $$$i$$$ and $$$j$$$ are two distinct integers and $$$c$$$ is a string ($$$1 \le i, j \le n$$$; $$$i \neq j$$$; $$$c$$$ is either imposter or crewmate). The comment means that player $$$i$$$ said that player $$$j$$$ has the role $$$c$$$.An imposter always lies, and a crewmate always tells the truth. Help Theofanis find the maximum possible number of imposters among all the other Cypriot players, or determine that the comments contradict each other (see the notes for further explanation).Note that each player has exactly one role: either imposter or crewmate.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of each test case follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 5 \cdot 10^5$$$) — the number of players except Theofanis and the number of comments. Each of the next $$$m$$$ lines contains a comment made by the players of the structure "$$$i$$$ $$$j$$$ $$$c$$$" where $$$i$$$ and $$$j$$$ are two distinct integers and $$$c$$$ is a string ($$$1 \le i, j \le n$$$; $$$i \neq j$$$; $$$c$$$ is either imposter or crewmate). There can be multiple comments for the same pair of $$$(i, j)$$$. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ and the sum of all $$$m$$$ does not exceed $$$5 \cdot 10^5$$$.

For each test case, print one integer — the maximum possible number of imposters. If the comments contradict each other, print $$$-1$$$.

5
3 2
1 2 imposter
2 3 crewmate
5 4
1 3 crewmate
2 5 crewmate
2 4 imposter
3 4 imposter
2 2
1 2 imposter
2 1 crewmate
3 5
1 2 imposter
1 2 imposter
3 2 crewmate
3 2 crewmate
1 3 imposter
5 0

NoteIn the first test case, imposters can be Andreas $$$2$$$ and $$$3$$$.In the second test case, imposters can be Andreas $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$.In the third test case, comments contradict each other. This is because player $$$1$$$ says that player $$$2$$$ is an imposter, and player $$$2$$$ says that player $$$1$$$ is a crewmate. If player $$$1$$$ is a crewmate, then he must be telling the truth, so player $$$2$$$ must be an imposter. But if player $$$2$$$ is an imposter then he must be lying, so player $$$1$$$ can't be a crewmate. Contradiction.

// Cheese-Cracker: cheese-cracker.github.io

int find(int v, int[] dsu){
    if(dsu[v] == -1) return v;
    return (dsu[v] = find(dsu[v], dsu));
}

bool onion(int u, int v, int[] dsu){
    int uid = find(u, dsu);
    int vid = find(v, dsu);
    if(uid != vid) dsu[vid] = uid;
    return (uid != vid);
}

void solve(){
    int n = scan!int;
    int m = scan!int;
    auto dsu = new int[](2*n+2);
    dsu[] = -1;
    auto cnt = new int[](2*n + 2);
    int[] qr, uarr, varr;
    for(int i = 0; i < m; ++i){
        int u = scan!int;
        int v = scan!int;
        auto oper = scan!(dchar[]);
        uarr ~= u;
        varr ~= v;
        if(oper == to!(dchar[])("imposter")){
            qr ~= 1;
        }else{
            qr ~= 0;
        }
    }
    for(int i = 0; i < m; ++i){
        int u = uarr[i];
        int v = varr[i];
        if(qr[i]){
            int uid = find(u, dsu);
            if(uid == find(v, dsu)){
                writeln(-1);
                return;
            }
            onion(uid, n+v, dsu);
            onion(v, n+u, dsu);
        }else{
            int uinv = find(n+u, dsu);
            if(uinv == find(v, dsu)){
                writeln(-1);
                return;
            }
            onion(uinv, n+v, dsu);
            onion(v, u, dsu);
        }
    }
    auto rbt = redBlackTree!int;
    for(int i = 1; i <= n; ++i){
        int iid = find(i, dsu);
        cnt[iid] += 1;
        rbt.insert(iid);
    }
    ll res = 0;
    foreach(iid; rbt){
        int opp = (iid > n) ? iid - n : n + iid;
        int inv = find(opp, dsu);
        res += max(cnt[iid], cnt[inv]);
        cnt[iid] = 0;
        cnt[inv] = 0;
    }
    writeln(res);
}

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

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

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

alias Tuple!(int, "to", long, "cost") Edge;

void solve() {
    int N, M; readf("%d %d\n", &N, &M);
    auto G = new Edge[][N];
    foreach (m; 0 .. M) {
        int i, j; string c; readf("%d %d %s\n", &i, &j, &c);
        i--; j--;
        int ci;
        if (c == "imposter") {
            ci = 1;
        } else {
            assert(c == "crewmate");
            ci = 0;
        }
        G[i] ~= Edge(j, ci);
        G[j] ~= Edge(i, ci);
    }

    auto truth = new int[N];
    truth[] = -1;

    Tuple!(int,int) dfs(int v, int c, int p) {
        auto ans = tuple(c, 1); // number of imposters, number of members in this group
        foreach (e; G[v]) {
            if (e.to == p) continue;
            int nc_should = (c + e.cost) % 2;
            if (truth[e.to] >= 0) {
                if (truth[e.to] != nc_should) return tuple(-1, 0);
            } else {
                truth[e.to] = nc_should;
                auto r = dfs(e.to, nc_should, v);
                if (r[0] < 0) return tuple(-1, 0);
                ans[0] += r[0];
                ans[1] += r[1];
            }
        }
        return ans;
    }

    int ans = 0;
    for (int i = 0; i < N; i++) {
        if (truth[i] < 0) {
            truth[i] = 0;
            auto r = dfs(i, 0, -1);
            if (r[0] < 0) {
                ans = -1;
                break;
            } else {
                ans += max(r[0], r[1] - r[0]);
            }
        }
    }
    writeln(ans);
}

enum int INF = 1<<30;

// Cheese-Cracker: cheese-cracker.github.io

int find(int v, int[] dsu){
    if(dsu[v] == -1) return v;
    return (dsu[v] = find(dsu[v], dsu));
}

bool onion(int u, int v, int[] dsu){
    int uid = find(u, dsu);
    int vid = find(v, dsu);
    if(uid != vid) dsu[vid] = uid;
    return (uid != vid);
}

void solve(){
    int n = scan!int;
    int m = scan!int;
    auto dsu = new int[](2*n+2);
    dsu[] = -1;
    auto cnt = new int[](2*n + 2);
    int[] qr, uarr, varr;
    for(int i = 0; i < m; ++i){
        int u = scan!int;
        int v = scan!int;
        auto oper = scan!(dchar[]);
        uarr ~= u;
        varr ~= v;
        if(oper == to!(dchar[])("imposter")){
            qr ~= 1;
        }else{
            qr ~= 0;
        }
    }
    for(int i = 0; i < m; ++i){
        int u = uarr[i];
        int v = varr[i];
        if(qr[i]){
            int uid = find(u, dsu);
            if(uid == find(v, dsu)){
                writeln(-1);
                return;
            }
            onion(uid, n+v, dsu);
            onion(v, n+u, dsu);
        }else{
            int uinv = find(n+u, dsu);
            if(uinv == find(v, dsu)){
                writeln(-1);
                return;
            }
            onion(uinv, n+v, dsu);
            onion(v, u, dsu);
        }
    }
    auto rbt = redBlackTree!int;
    for(int i = 1; i <= n; ++i){
        int iid = find(i, dsu);
        cnt[iid] += 1;
        if(iid <= n){
            rbt.insert(iid);
        }else{
            rbt.insert(iid - n);
        }
    }
    ll res = 0;
    foreach(iid; rbt){
        int inv = find(n+iid, dsu);
        res += max(cnt[iid], cnt[inv]);
        cnt[iid] = 0;
        cnt[inv] = 0;
    }
    writeln(res);
}

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

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

// Cheese-Cracker: cheese-cracker.github.io

int find(int v, int[] dsu){
    if(dsu[v] == -1) return v;
    return (dsu[v] = find(dsu[v], dsu));
}

bool onion(int u, int v, int[] dsu){
    int uid = find(u, dsu);
    int vid = find(v, dsu);
    if(uid != vid) dsu[vid] = uid;
    return (uid != vid);
}

void solve(){
    int n = scan!int;
    int m = scan!int;
    auto dsu = new int[](2*n+2);
    dsu[] = -1;
    auto cnt = new int[](2*n + 2);
    int[] qr, uarr, varr;
    for(int i = 0; i < m; ++i){
        int u = scan!int;
        int v = scan!int;
        auto oper = scan!(dchar[]);
        uarr ~= u;
        varr ~= v;
        if(oper == to!(dchar[])("imposter")){
            qr ~= 1;
        }else{
            qr ~= 0;
        }
    }
    for(int i = 0; i < m; ++i){
        int u = uarr[i];
        int v = varr[i];
        if(qr[i]){
            int uid = find(u, dsu);
            if(uid == find(v, dsu)){
                writeln(-1);
                return;
            }
            onion(uid, n+v, dsu);
            onion(v, n+u, dsu);
        }else{
            int uinv = find(n+u, dsu);
            if(uinv == find(v, dsu)){
                writeln(-1);
                return;
            }
            onion(uinv, n+v, dsu);
            onion(v, u, dsu);
        }
    }
    auto rbt = redBlackTree!int;
    for(int i = 1; i <= n; ++i){
        int iid = find(i, dsu);
        cnt[iid] += 1;
        if(iid <= n){
            rbt.insert(iid);
        }
    }
    ll res = 0;
    foreach(iid; rbt){
        int inv = find(n+iid, dsu);
        res += max(cnt[iid], cnt[inv]);
        cnt[iid] = 0;
        cnt[inv] = 0;
    }
    writeln(res);
}

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

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

// Cheese-Cracker: cheese-cracker.github.io

int find(int v, int[] dsu){
    if(dsu[v] == -1) return v;
    return (dsu[v] = find(dsu[v], dsu));
}

bool onion(int u, int v, int[] dsu){
    int uid = find(u, dsu);
    int vid = find(v, dsu);
    if(uid != vid) dsu[vid] = uid;
    return (uid != vid);
}

void solve(){
    int n = scan!int;
    int m = scan!int;
    auto dsu = new int[](2*n+2);
    dsu[] = -1;
    auto cnt = new int[2*n+2];
    int[] qr, uarr, varr;
    for(int i = 0; i < m; ++i){
        int u = scan!int;
        int v = scan!int;
        auto oper = scan!(dchar[]);
        uarr ~= u;
        varr ~= v;
        if(oper == to!(dchar[])("imposter")){
            qr ~= 1;
        }else{
            qr ~= 0;
        }
    }
    for(int i = 0; i < m; ++i){
        int u = uarr[i];
        int v = varr[i];
        if(qr[i]){
            int uid = find(u, dsu);
            if(uid == find(v, dsu)){
                writeln(-1);
                return;
            }
            onion(uid, n+v, dsu);
            onion(v, n+u, dsu);
        }else{
            int uinv = find(n+u, dsu);
            if(uinv == find(v, dsu)){
                writeln(-1);
                return;
            }
            onion(uinv, n+v, dsu);
            onion(v, u, dsu);
        }
    }
    auto rbt = redBlackTree!int;
    for(int i = 1; i <= n; ++i){
        int iid = find(i, dsu);
        cnt[iid] += 1;
        if(iid <= n){
            rbt.insert(iid);
        }
    }
    ll res = 0;
    if(rbt.length){
        foreach(iid; rbt){
            int inv = find(n+iid, dsu);
            res += max(cnt[iid], cnt[inv]);
            cnt[iid] = 0;
            cnt[inv] = 0;
        }
    }
    writeln(res);
}

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

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

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

alias Tuple!(int, "to", long, "cost") Edge;

void solve() {
    int N, M; readf("%d %d\n", &N, &M);
    auto G = new Edge[][N];
    foreach (m; 0 .. M) {
        int i, j; string c; readf("%d %d %s\n", &i, &j, &c);
        i--; j--;
        int ci;
        if (c == "imposter") {
            ci = 1;
        } else {
            assert(c == "crewmate");
            ci = 0;
        }
        G[i] ~= Edge(j, ci);
        G[j] ~= Edge(i, ci);
    }

    auto truth = new int[N];
    truth[] = -1;

    Tuple!(int,int) dfs(int v, int c, int p) {
        auto ans = tuple(c, 1); // number of imposters, number of members in this group
        foreach (e; G[v]) {
            if (e.to == p) continue;
            int nc_should = (c + e.cost) % 2;
            if (truth[e.to] >= 0) {
                if (truth[e.to] != nc_should) return tuple(-1, 0);
            } else {
                truth[e.to] = nc_should;
                auto r = dfs(e.to, nc_should, v);
                if (r[0] < 0) return tuple(-1, 0);
                ans[0] += r[0];
                ans[1] += r[1];
            }
        }
        return ans;
    }

    int ans = 0;
    for (int i = 0; i < N; i++) {
        if (truth[i] < 0) {
            auto r = dfs(i, 0, -1);
            if (r[0] < 0) {
                ans = -1;
                break;
            } else {
                ans += max(r[0], r[1] - r[0]);
            }
        }
    }
    writeln(ans);
}

enum int INF = 1<<30;


You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".

The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.

Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.

NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".

module main;

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

int main()
{
    auto s = readln()
             .strip()
             .split(",")
             .map! (x => (x == "") ? [""] : x.split(";"))
             .join();

    // debug {writeln(s);};

    string a, b;

    foreach (i; 0..s.length) {
        BigInt temp;
        try {
            temp = BigInt(s[i]);
            if (s[i][0] == '0' && s[i].length > 1) {
                int zero = 0;
                temp = 1 / zero;
            }
            a ~= temp.to! (string) ~ ",";
        }
        catch {
            b ~= s[i] ~ ",";
        }
    }

    if (a.length)
        writeln('\"', a[0..$ - 1], '\"');
    else
        writeln('-');
    if (b.length)
        writeln('\"', b[0..$ - 1], '\"');
    else
        writeln('-');

	return 0;
}

module main;

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

int main()
{
    auto s = readln()
             .strip()
             .split(",")
             .map! (x => (x == "") ? [""] : x.split(";"))
             .join();

    // debug {writeln(s);};

    string a, b;

    foreach (i; 0..s.length) {
        BigInt temp;
        try {
            temp = BigInt(s[i]);
            if (s[i][0] == '0' && temp != 0) {
                int zero = 0;
                temp = 1 / zero;
            }
            a ~= temp.to! (string) ~ ",";
        }
        catch {
            b ~= s[i] ~ ",";
        }
    }

    if (a.length)
        writeln('\"', a[0..$ - 1], '\"');
    else
        writeln('-');
    if (b.length)
        writeln('\"', b[0..$ - 1], '\"');
    else
        writeln('-');

	return 0;
}

module main;

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

int main()
{
    auto cleanS = readln().strip();
    auto s = cleanS.split(",").map! (x => x.split(";")).join();

    // debug {writeln(s);};

    string a, b;

    foreach (i; 0..s.length) {
        int temp;
        try {
            temp = s[i].to! (int);
            if (s[i][0] == '0' && temp != 0) {
                int zero = 0;
                temp = 1 / zero;
            }
            a ~= temp.to! (string) ~ ",";
        }
        catch {
            b ~= s[i] ~ ",";
        }
    }

    if (a.length)
        writeln('\"', a[0..$ - 1], '\"');
    else
        writeln('-');
    if (b.length) {
        if (cleanS.back == ',' || cleanS.back == ';')
            b ~= ',';
        writeln('\"', b[0..$ - 1], '\"');
    } else
        writeln('-');

	return 0;
}

// 123,fgfg,32d,5;12d,a

module main;

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

int main()
{
    auto s = readln()
             .strip()
             .split(",")
             .map! (x => (x == "") ? [""] : x.split(";"))
             .join();

    // debug {writeln(s);};

    string a, b;

    foreach (i; 0..s.length) {
        int temp;
        try {
            temp = s[i].to! (int);
            if (s[i][0] == '0' && temp != 0) {
                int zero = 0;
                temp = 1 / zero;
            }
            a ~= temp.to! (string) ~ ",";
        }
        catch {
            b ~= s[i] ~ ",";
        }
    }

    if (a.length)
        writeln('\"', a[0..$ - 1], '\"');
    else
        writeln('-');
    if (b.length)
        writeln('\"', b[0..$ - 1], '\"');
    else
        writeln('-');

	return 0;
}


You are given a integer $$$n$$$ ($$$n > 0$$$). Find any integer $$$s$$$ which satisfies these conditions, or report that there are no such numbers:In the decimal representation of $$$s$$$:   $$$s > 0$$$,  $$$s$$$ consists of $$$n$$$ digits,  no digit in $$$s$$$ equals $$$0$$$,  $$$s$$$ is not divisible by any of it's digits.

The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 400$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case contains one positive integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, print an integer $$$s$$$ which satisfies the conditions described above, or "-1" (without quotes), if no such number exists. If there are multiple possible solutions for $$$s$$$, print any solution.

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		writeln (n == 1 ? "-1" : "2" ~ "3".cycle.take (n - 1).text);
	}
}

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

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

void solve(){
    foreach(_; 0 .. scan!int){
        int n = scan!int;
        if(n == 1) "-1".writeln;
        else{
            if(n % 9 == 1){
                foreach(i; 0 .. n - 2) "5".write;
                "99".writeln;
            }
            else{
                foreach(i; 0 .. n - 1) "5".write;
                "9".writeln;
            }
        }
    }
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        if (N == 1) {
          writeln(-1);
        } else {
          write(8);
          foreach (i; 1 .. N) {
            write(9);
          }
          writeln();
        }
      }
    }
  } catch (EOFException e) {
  }
}


Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of $$$n$$$ rows and $$$n$$$ columns of square cells. The rows are numbered from $$$1$$$ to $$$n$$$, from top to bottom, and the columns are numbered from $$$1$$$ to $$$n$$$, from left to right. The position of a cell at row $$$r$$$ and column $$$c$$$ is represented as $$$(r, c)$$$. There are only two colors for the cells in cfpaint — black and white.There is a tool named eraser in cfpaint. The eraser has an integer size $$$k$$$ ($$$1 \le k \le n$$$). To use the eraser, Gildong needs to click on a cell $$$(i, j)$$$ where $$$1 \le i, j \le n - k + 1$$$. When a cell $$$(i, j)$$$ is clicked, all of the cells $$$(i', j')$$$ where $$$i \le i' \le i + k - 1$$$ and $$$j \le j' \le j + k - 1$$$ become white. In other words, a square with side equal to $$$k$$$ cells and top left corner at $$$(i, j)$$$ is colored white.A white line is a row or a column without any black cells.Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the number of rows and columns, and the size of the eraser. The next $$$n$$$ lines contain $$$n$$$ characters each without spaces. The $$$j$$$-th character in the $$$i$$$-th line represents the cell at $$$(i,j)$$$. Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.

Print one integer: the maximum number of white lines after using the eraser exactly once.

NoteIn the first example, Gildong can click the cell $$$(2, 2)$$$, then the working screen becomes: BWWWWWWWWWWWWWWBThen there are four white lines — the $$$2$$$-nd and $$$3$$$-rd row, and the $$$2$$$-nd and $$$3$$$-rd column.In the second example, clicking the cell $$$(2, 3)$$$ makes the $$$2$$$-nd row a white line.In the third example, both the $$$2$$$-nd column and $$$5$$$-th row become white lines by clicking the cell $$$(3, 2)$$$.

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

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

    dchar[][] arr;
    foreach (_; 0 .. n) { arr ~= readln.chomp.to!(dchar[]); }

    auto badCount = ((dchar[][] arr) => arr.count!(r => r.canFind('B')).to!int);
    int allBad = badCount(arr) + badCount(arr.dup.transposed.map!array.array);

    debug { arr.each!writeln; }

    debug { allBad.writeln; }

    auto firstR = new int[] (n), firstC = new int[] (n);
    auto lastR = new int[] (n), lastC = new int[] (n);
    firstR[] = -1, lastR[] = -1, firstC[] = -1, lastC[] = -1;

    foreach (i; 0 .. n) {
        foreach (j; 0 .. n) {
            if (arr[i][j] == 'B') {
                if (firstR[i] == -1) { firstR[i] = j; }
                if (firstC[j] == -1) { firstC[j] = i; }

                lastR[i] = j;
                lastC[j] = i;
            }
        }
    }

    debug { writeln(firstR, ' ', lastR); writeln(firstC, ' ', lastC); }

    auto rows = new int[][] (n+1, n+1);
    auto cols = new int[][] (n+1, n+1);

    foreach (i; 0 .. n) {
        if (firstR[i] != -1 && firstR[i] + k - 1 >= lastR[i]) {
            foreach (j; max(i - k + 1, 0) .. min(i + 1, n - k + 1)) {
                rows[j][max(lastR[i] - k + 1, 0)] += 1;
                rows[j][firstR[i] + 1] -= 1;
            }
        }
        if (firstC[i] != -1 && firstC[i] + k - 1 >= lastC[i]) {
            foreach (j; max(i - k + 1, 0) .. min(i + 1, n - k + 1)) {
                cols[j][max(lastC[i] - k + 1, 0)] += 1;
                cols[j][firstC[i] + 1] -= 1;
            }
        }
    }

    foreach (i; 0 .. n) {
        foreach (j; 1 .. n) {
            rows[i][j] += rows[i][j-1];
            cols[i][j] += cols[i][j-1];
        }
    }

    debug { rows.each!writeln; writeln; cols.each!writeln; }

    int mx = 0;
    foreach (i; 0 .. n) {
        foreach (j; 0 .. n) {
            mx = max(mx, rows[i][j] + cols[j][i]);
        }
    }

    auto ans = n+n - allBad + mx;
    ans.writeln;
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int n = read.to!int;
	int k = read.to!int;
	log("n:", n, "k:", k);

	int z; // already done

	bool[][] af = new bool[][](n, n);
	foreach(i; 0 .. n){
		char[] l = readln.chomp.to!(char[]);
		foreach(j; 0 .. n){
			af[i][j] = (l[j] == 'B');
		}
	}
	log("af:", af.fz);

	bool[][] uf = new bool[][](n, n);
	foreach(i; 0 .. n){
		foreach(j; 0 .. n){
			uf[i][j] = 1;
			if(af[i][j]) break;
		}
		bool f;
		foreach_reverse(j; 0 .. n){
			if(j - k + 1 >= 0) if(f) uf[i][j - k + 1] = 0;
			if(af[i][j]) f = 1;
		}
		if(!f){
			foreach(j; 0 .. n) uf[i][j] = 0;
			z += 1;
		}
	}
	log("uf:", uf.fz);

	bool[][] vf = new bool[][](n, n);
	foreach(j; 0 .. n){
		foreach(i; 0 .. n){
			vf[i][j] = 1;
			if(af[i][j]) break;
		}
		bool f;
		foreach_reverse(i; 0 .. n){
			if(i - k + 1 >= 0) if(f) vf[i - k + 1][j] = 0;
			if(af[i][j]) f = 1;
		}
		if(!f){
			foreach(i; 0 .. n) vf[i][j] = 0;
			z += 1;
		}
	}
	log("vf:", vf.fz);

	int[][] pf = new int[][](n, n);
	foreach(i; 0 .. n){
		int sum = 0;
		foreach(j; 0 .. n){
			sum += (vf[i][j]? 1: 0);
			pf[i][j] = sum;
		}
	}
	log("pf:", pf.fz);

	int[][] qf = new int[][](n, n);
	foreach(j; 0 .. n){
		int sum = 0;
		foreach(i; 0 .. n){
			sum += (uf[i][j]? 1: 0);
			qf[i][j] = sum;
		}
	}
	log("qf:", qf.fz);

	int[][] anf = new int[][](n, n);
	foreach(i; 0 .. n) foreach(j; 0 .. n){
		if(i + k - 1 >= n || j + k - 1 >= n) continue;
		anf[i][j] = pf[i][j + k - 1] + qf[i + k - 1][j];
		if(j > 0) anf[i][j] -= pf[i][j - 1];
		if(i > 0) anf[i][j] -= qf[i - 1][j];
	}
	log("anf:", anf.fz);

	int an = 0;
	foreach(i; 0 .. n) foreach(j; 0 .. n){
		an = max(an, anf[i][j]);
	}

	(an + z).writeln;
}

string fz(bool[][] bf){
	string[] res;
	foreach(bs; bf) res ~= bs.map!(x => (x? '#': '_')).array;
	return "\n" ~ res.join("\n");
}
string fz(int[][] nf){
	string[] res;
	foreach(ns; nf) res ~= ns.map!(to!string).array.join(" ");
	return "\n" ~ res.join("\n");
}


There is a field divided into $$$n$$$ rows and $$$m$$$ columns. Some cells are empty (denoted as E), other cells contain robots (denoted as R).You can send a command to all robots at the same time. The command can be of one of the four types:  move up;  move right;  move down;  move left. When you send a command, all robots at the same time attempt to take one step in the direction you picked. If a robot tries to move outside the field, it explodes; otherwise, every robot moves to an adjacent cell in the chosen direction.You can send as many commands as you want (possibly, zero), in any order. Your goal is to make at least one robot reach the upper left corner of the field. Can you do this without forcing any of the robots to explode?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case starts with a line containing two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5$$$) — the number of rows and the number of columns, respectively. Then $$$n$$$ lines follow; each of them contains a string of $$$m$$$ characters. Each character is either E (empty cell} or R (robot). Additional constraint on the input: in each test case, there is at least one robot on the field.

If it is possible to make at least one robot reach the upper left corner of the field so that no robot explodes, print YES. Otherwise, print NO.

6

1 3

ERR

2 2

ER

RE

2 2

ER

ER

1 1

R

4 3

EEE

EEE

ERR

EER

3 3

EEE

EER

REE

NoteExplanations for test cases of the example:  in the first test case, it is enough to send a command to move left.  in the second test case, if you try to send any command, at least one robot explodes.  in the third test case, it is enough to send a command to move left.  in the fourth test case, there is already a robot in the upper left corner.  in the fifth test case, the sequence "move up, move left, move up" leads one robot to the upper left corner;  in the sixth test case, if you try to move any robot to the upper left corner, at least one other robot explodes.

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto M = scan!int;
      auto G = scan!string(N);

      int mx = 100, my = 100;
      foreach(y; 0..N) foreach(x; 0..M) {
        if (G[y][x] == 'R') {
          mx = min(mx, x);
          my = min(my, y);
        }
      }

      bool ans;
      foreach(y; 0..N) foreach(x; 0..M) {
        if (G[y][x] == 'R' && x <= mx && y <= my) {
          ans = true;
          break;
        }
      }
      return ans ? "YES" : "NO";
    }

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

  outputForAtCoder(&solve);
}

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

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

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

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

immutable int NA = -1;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		string [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip;
		}
		int lo = NA;
		bool ok = true;
		foreach (row; 0..rows)
		{
			auto cur = board[row].countUntil ('R');
			if (cur >= 0)
			{
				if (lo == NA)
				{
					lo = cur;
				}
				else if (lo > cur)
				{
					ok = false;
				}
			}
		}
		writeln (ok ? "YES" : "NO");
	}
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).

For each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.

import std.stdio;
import std.string : split, strip;
import std.algorithm : count, map;
import std.conv : to;

void main()
{
    int t;
    readf!"%d\n"(t);

    foreach (i; 0..t) {
        int n;
        readf!"%d\n"(n);

        auto a = readln.strip.split.map!(to!int);
        auto even = a.count!"(a & 1) == 0";
        auto odd = n - even;

        if ((odd > 0 && even > 0) || (odd & 1) == 1) {
            writeln("YES");
        } else {
            writeln("NO");
        }
    }
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
import std.algorithm.mutation;
import std.container.array;

string[] tokens;

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

int readInt()
{
    return readToken.to!int;
}

bool solve()
{
    int n = readInt;
    auto cnt = [0, 0];
    for (int i = 0; i < n; ++i)
        cnt[readInt % 2] = 1;
    if (cnt[1])
    {
        if (cnt[0])
        {
            return true;
        }
        return n % 2 == 1;
    }
    else
    {
        return false;
    }
}

void main()
{
    int T = readInt;
    while (T--)
    {
        writeln(solve ? "YES" : "NO");
    }
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value = E.init)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

void main()
{
  auto t = next!int;
  foreach(tc; 0 .. t)
    {
      auto n = next!int;
      auto a = new int[n.ind];
      read(a);
      auto pa = a.map!(ai => ai % 2);
      auto c0 = pa.canFind(0);
      auto c1 = pa.canFind(1);
      if (c0 && c1)
        {
          writeln("YES");
        }
      else if (c0)
        {
          writeln("NO");
        }
      else
        {
          writeln(pa.sum % 2 == 1? "YES" : "NO");
        }
    }
}

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int n=0;
		readf(" %d", &n);
		int sum=0;
		int count=0;
		for (int j=0; j<n; j++)
		{
			int a=0;
			readf(" %d", &a);
			sum=sum+a;
			if (a%2==0)
			{
				count=count+1;
			}
		}
		if (count==n)
		{
			writeln("NO");
		}
		else
		{
			if (count==0 && n%2==0)
			{
				writeln("NO");
			}
			else
			{
				writeln("YES");
			}
		}
	}
	return 0;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		long cnt;
		foreach (e; a)
		{
			if (e % 2 == 1)
				++cnt;
		}
		if (cnt == 0) continue;
		if (cnt % 2 == 0 && cnt == n) continue;
		ans[ti] = true;
	}

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