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

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


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


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

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


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

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


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


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

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.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		readln;
		auto n = readln.strip.to !(int);
		auto s = new int [n];
		foreach (i; 0..n)
		{
			auto t = readln.strip.map !(q{a - '0'}).array;
			foreach (j; 0..n)
			{
				s[(i + n - j) % n] += t[j];
			}
		}
		auto total = s.sum;
		auto res = s.map !(c => total - c + n - c).minElement;
		writeln (res);
	}
}

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 solve() {
    readln;
    int N = read!int;
    auto F = iota(N).map!(_ => readln.chomp).array;
    int no = 0;
    for (int y = 0; y < N; y++) {
        for (int x = 0; x < N; x++) {
            no += (F[y][x] == '1');
        }
    }
    int ans = N*N;
    for (int y = 0; y < N; y++) {
        int dno = 0;
        for (int k = 0; k < N; k++) {
            int i = (y + k) % N, j = k;
            dno += (F[i][j] == '1');
        }
        ans = min(ans, no - dno + N - dno);
    }
    writeln(ans);
}

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


/+ dub.sdl:
    name "D"
    dependency "dcomp" version=">=0.9.0"
+/

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

import std.typecons;

int main() {
    Scanner sc = new Scanner(stdin);
    int n, m;
    long[] c;
    sc.read(n, m, c);
    alias E = Tuple!(int, "to", int, "id");
    E[][] g = new E[][](n);
    foreach (i; 0..m) {
        int a, b;
        sc.read(a, b); a--; b--;
        g[a] ~= E(b, i);
        g[b] ~= E(a, i);
    }
    long[] res = new long[m];
    int[] dps = new int[n];
    int[] par = new int[n];
    int[] pid = new int[n]; pid[0] = -1;
    bool[] vis = new bool[n];

    int eid = -1, edown = -1, eup = -1, edps = -1;
    long dfs(int p, int b, int ndp = 0) {
        dps[p] = ndp;
        par[p] = b;
        vis[p] = true;
        long sm = c[p];
        foreach (e; g[p]) {
            int d = e.to;
            if (d == b) continue;
            if (!vis[d]) {
                pid[d] = e.id;
                long u = dfs(d, p, ndp+1);
                res[e.id] = u;
                sm -= u;
                continue;
            }
            if (dps[p] < dps[d]) continue;
            // back edge
            if ((dps[p] - dps[d]) % 2) continue;
            // odd cycle
            eid = e.id;
            edown = p; eup = d; edps = dps[p];
        }
        return sm;
    }

    long u = dfs(0, -1);
    if (edps % 2) u *= -1;
    if (u) {
        if (eid == -1) {
            writeln("NO");
            return 0;
        }
        u /= 2;
        res[eid] += u; u *= -1;
        int s = edown;
        while (s != eup) {
            res[pid[s]] += u; u *= -1;
            s = par[s];
        }
        u *= 2;
        while (s) {
            res[pid[s]] += u; u *= -1;
            s = par[s];
        }
    }

    writeln("YES");
    writeln(res.map!(to!string).join("\n"));
    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/container/stackpayload.d */
// module dcomp.container.stackpayload;

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

    private T* _data;
    private uint len, cap;

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

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

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

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

    void clear() {
        len = 0;
    }

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

/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/foundation.d */

// module dcomp.foundation;

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

}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

// import dcomp.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

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

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

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

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

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

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

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

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

int[][] G;
int[] par, pari;
int[] dep;
long[] ans;
int odI, odU, odV;

long dfs(int u, int p, int pi) {
  par[u] = p;
  pari[u] = pi;
  dep[u] = (p == -1) ? 0 : (dep[p] + 1);
  long ret = C[u];
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      if (dep[v] == -1) {
        ans[i] = dfs(v, u, i);
        ret -= ans[i];
      } else if (dep[u] > dep[v]) {
        if ((dep[u] - dep[v]) % 2 == 0) {
          odI = i;
          odU = u;
          odV = v;
        }
      }
    }
  }
  return ret;
}

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

      G = new int[][N];
      foreach (i; 0 .. M) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      par = new int[N];
      pari = new int[N];
      dep = new int[N];
      dep[] = -1;
      ans = new long[M];
      odI = odU = odV = -1;
      const rt = 0;
      const res = dfs(rt, -1, -1);
      debug {
        writeln("ans = ", ans);
        writefln("od = %s: %s %s", odI, odU, odV);
        writeln("res = ", res);
      }
      if (res != 0) {
        if (odI != -1 && res % 2 == 0) {
          long d = (-1)^^(dep[odV] % 2) * (res / 2);
          ans[odI] += d;
          for (int w = odU; w != odV; w = par[w]) {
            d *= -1;
            ans[pari[w]] += d;
          }
          d *= 2;
          for (int w = odV; w != rt; w = par[w]) {
            d *= -1;
            ans[pari[w]] += d;
          }
        } else {
          ans = null;
        }
      }

      if (!ans.empty) {
        auto cs = new long[N];
        foreach (i; 0 .. M) {
          cs[A[i]] += ans[i];
          cs[B[i]] += ans[i];
        }
        if (C != cs) {
          ans = null;
        }
      }

      if (!ans.empty) {
        writeln("YES");
        foreach (i; 0 .. M) {
          writeln(ans[i]);
        }
      } else {
        writeln("NO");
      }
    }
  } catch (EOFException e) {
  }
}

/+ dub.sdl:
    name "C"
    dependency "dcomp" version=">=0.9.0"
+/

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

import std.typecons;

// import dcomp.segtree.lazyseg;

int main() {
    Scanner sc = new Scanner(stdin);

    int n, m;
    sc.read(n, m);
    int[][] g = new int[][n];
    foreach (i; 0..m) {
        int a, b;
        sc.read(a, b); a--; b--;
        g[a] ~= b; g[b] ~= a;
    }

    int[] par = new int[n];
    int[] dps = new int[n];
    bool[] vis = new bool[n];

    int[] ri = new int[n+1]; ri[] = n;

    void add(int s, int t) {
        int mi = t, ma = t;
        while (s != t) {
            mi = min(mi, s);
            ma = max(ma, s);
            s = par[s];
        }
        ri[mi] = min(ri[mi], ma);
    }

    void dfs(int p, int b = -1, int ndp = 0) {
        par[p] = b;
        dps[p] = ndp;
        vis[p] = true;
        foreach (d; g[p]) {
            if (d == b) continue;
            if (!vis[d]) {
                dfs(d, p, ndp+1);
                continue;
            }
            if (dps[p] < dps[d]) continue;
            add(p, d);
        }
    }
    foreach (i; 0..n) {
        if (vis[i]) continue;
        dfs(i);
    }
    foreach_reverse (i; 0..n-1) {
        ri[i] = min(ri[i], ri[i+1]);
    }
//    writeln(ri);

    int q;
    sc.read(q);
    long[] res = new long[q];

    alias E = Tuple!(int, "left", int, "id", bool, "pos");
    E[][] ev = new E[][](n+1);

    foreach (i; 0..q) {
        int a, b;
        sc.read(a, b); a--;
        res[i] = long(b-a) * long(b-a + 1) / 2;
        ev[b] ~= E(a, i, false);
        ev[b] ~= E(b, i, true);
        ev[a] ~= E(a, i, true);
        ev[a] ~= E(b, i, false);
    }

    alias N = Tuple!(long, int);
    auto seg = LazySeg!(N, long,
        (a, b) => N(a[0]+b[0], a[1]+b[1]),
        (a, b) => N(a[0]+a[1]*b, a[1]),
        "a+b",
        N(0, 0), 0)(N(0, 1).repeat.take(n).array);
    foreach (r; 0..n+1) {
        foreach (e; ev[r]) {
            long u = seg[e.left..$].sum[0];
            if (e.pos) {
                res[e.id] += u;
            } else {
                res[e.id] -= u;
            }
        }
        seg[ri[r]..$] += 1;
    }
    writeln(res.map!(to!string).join("\n"));

    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/foundation.d */

// module dcomp.foundation;

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

}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/segtree/lazyseg.d */
// module dcomp.segtree.lazyseg;

// import dcomp.segtree.primitive;

import std.functional : binaryFun;

alias LazySeg(T, L, alias opTT, alias opTL, alias opLL, T eT, L eL, alias Engine = LazySegEngine) =
    SegTree!(Engine, T, L , binaryFun!opTT, binaryFun!opTL, binaryFun!opLL, eT, eL);

struct LazySegEngine(T, L, alias opTT, alias opTL, alias opLL, T eT, L eL) {
    import std.typecons : Tuple;
    alias DataType = T;
    alias LazyType = L;
    alias BinSearch = binSearchLazy;
    alias S = Tuple!(T, "d", L, "lz");
    uint n, sz, lg;
    S[] s;
    this(uint n) {
        import std.conv : to;
        import std.algorithm : each;
        this.n = n;
        uint lg = 0;
        while ((2^^lg) < n) lg++;
        this.lg = lg;
        sz = 2^^lg;
        s = new S[](2*sz);
        s.each!((ref x) => x = S(eT, eL));
    }
    this(T[] first) {
        import std.conv : to;
        import std.algorithm : each;
        n = first.length.to!uint;
        uint lg = 0;
        while ((2^^lg) < n) lg++;
        this.lg = lg;
        sz = 2^^lg;

        s = new S[](2*sz);
        s.each!((ref x) => x = S(eT, eL));
        foreach (i; 0..n) {
            s[sz+i].d = first[i];
        }
        foreach_reverse (i; 1..sz) {
            update(i);
        }
    }
    @property uint length() const { return n; }
    pragma(inline):
    private void lzAdd(uint k, in L x) {
        s[k].lz = opLL(s[k].lz, x);
        s[k].d = opTL(s[k].d, x);
    }
    public void push(uint k) {
        if (s[k].lz == eL) return;
        lzAdd(2*k, s[k].lz);
        lzAdd(2*k+1, s[k].lz);
        s[k].lz = eL;
    }
    private void update(uint k) {
        s[k].d = opTT(s[2*k].d, s[2*k+1].d);
    }
    T single(uint k) {
        k += sz;
        foreach_reverse (uint i; 1..lg+1) {
            push(k>>i);
        }
        return s[k].d;
    }
    void singleSet(uint k, T x) {
        k += sz;
        foreach_reverse (uint i; 1..lg+1) {
            push(k>>i);
        }
        s[k].d = x;
        foreach (uint i; 1..lg+1) {
            update(k>>i);
        }
    }
    T sum(uint a, uint b) {
        assert(0 <= a && a <= b && b <= n);
        if (a == b) return eT;
        a += sz; b--; b += sz;
        uint tlg = lg;
        while (true) {
            uint k = a >> tlg;
            if (a >> tlg != b >> tlg) {
                tlg++;
                break;
            }
            if (((a-1) >> tlg) + 2 == (b+1) >> tlg) return s[k].d;
            push(k);
            tlg--;
        }
        T sm = eT;
        foreach_reverse (l; 0..tlg) {
            uint k = a >> l;
            if ((a-1)>>l != a>>l) {
                sm = opTT(s[k].d, sm);
                break;
            }
            push(k);
            if (!((a >> (l-1)) & 1)) sm = opTT(s[2*k+1].d, sm);
        }
        foreach_reverse (l; 0..tlg) {
            uint k = b >> l;
            if (b>>l != (b+1)>>l) {
                sm = opTT(sm, s[k].d);
                break;
            }
            push(k);
            if ((b >> (l-1)) & 1) sm = opTT(sm, s[2*k].d);
        }
        return sm;
    }
    void add(uint a, uint b, L x) {
        assert(0 <= a && a <= b && b <= n);
        if (a == b) return;
        a += sz; b--; b += sz;
        uint tlg = lg;
        while (true) {
            uint k = a >> tlg;
            if (a >> tlg != b >> tlg) {
                tlg++;
                break;
            }
            if (((a-1) >> tlg) + 2 == (b+1) >> tlg) {
                lzAdd(k, x);
                foreach (l; tlg+1..lg+1) {
                    update(a >> l);
                }
                return;
            }
            push(k);
            tlg--;
        }
        foreach_reverse (l; 0..tlg) {
            uint k = a >> l;
            if ((a-1)>>l != a>>l) {
                lzAdd(k, x);
                foreach (h; l+1..tlg) {
                    update(a >> h);
                }
                break;
            }
            push(k);
            if (!((a >> (l-1)) & 1)) lzAdd(2*k+1, x);
        }
        foreach_reverse (l; 0..tlg) {
            uint k = b >> l;
            if (b>>l != (b+1)>>l) {
                lzAdd(k, x);
                foreach (h; l+1..tlg) {
                    update(b >> h);
                }
                break;
            }
            push(k);
            if ((b >> (l-1)) & 1) lzAdd(2*k, x);
        }
        foreach (l; tlg..lg+1) {
            update(a >> l);
        }
    }
}

int binSearchLazy(bool rev, alias pred, TR)(TR t, int a, int b) {
    import std.traits : TemplateArgsOf;
    alias args = TemplateArgsOf!TR;
    alias opTT = args[2];
    auto x = args[5];
    with (t) {
        static if (!rev) {

            if (pred(x)) return a-1;
            int pos = a;
            void f(int a, int b, int l, int r, int k) {
                if (b <= l || r <= a) return;
                if (a <= l && r <= b && !pred(opTT(x, s[k].d))) {
                    x = opTT(x, s[k].d);
                    pos = r;
                    return;
                }
                if (l+1 == r) return;
                push(k);
                int md = (l+r)/2;
                f(a, b, l, md, 2*k);
                if (pos >= md) f(a, b, md, r, 2*k+1);
            }
            f(a, b, 0, sz, 1);
            return pos;
        } else {

            if (pred(x)) return b;
            int pos = b-1;
            void f(int a, int b, int l, int r, int k) {
                if (b <= l || r <= a) return;
                if (a <= l && r <= b && !pred(opTT(x, s[k].d))) {
                    x = opTT(s[k].d, x);
                    pos = l-1;
                    return;
                }
                if (l+1 == r) return;
                push(k);
                int md = (l+r)/2;
                f(a, b, md, r, 2*k+1);
                if (pos < md) f(a, b, l, md, 2*k);
            }
            f(a, b, 0, sz, 1);
            return pos;
        }
    }
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

// import dcomp.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

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

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/segtree/primitive.d */
// module dcomp.segtree.primitive;

import std.conv : to;

struct SegTree(alias E, Args...) {
    import std.traits : ReturnType;
    alias Engine = E!Args;
    alias T = Engine.DataType;
    alias L = Engine.LazyType;

    Engine eng;

    this(size_t n) { eng = Engine(n.to!uint); }
    this(T[] first) { eng = Engine(first); }

    @property size_t length() const { return eng.length(); }
    @property size_t opDollar() const { return eng.length(); }

    struct Range {
        Engine* eng;
        size_t start, end;
        @property const(T) sum() {
            return eng.sum(start.to!uint, end.to!uint);
        }
    }
    const(T) opIndex(size_t k) {
        assert(0 <= k && k < eng.length());
        return eng.single(k.to!uint);
    }
    void opIndexAssign(T x, size_t k) {
        assert(0 <= k && k < eng.length());
        eng.singleSet(k.to!uint, x);
    }
    size_t[2] opSlice(size_t dim : 0)(size_t start, size_t end) {
        assert(0 <= start && start <= end && end <= eng.length());
        return [start, end];
    }
    Range opIndex(size_t[2] rng) {
        return Range(&eng, rng[0].to!uint, rng[1].to!uint);
    }
    static if (!is(L == void)) {
        void opIndexOpAssign(string op : "+")(L x, size_t[2] rng) {
            eng.add(rng[0].to!uint, rng[1].to!uint, x);
        }
    }
}

import std.traits : isInstanceOf;

ptrdiff_t binSearchLeft(alias pred, TR)(TR t, ptrdiff_t a, ptrdiff_t b)
if (isInstanceOf!(SegTree, TR)) {
    return TR.Engine.BinSearch!(false, pred)(t.eng, a.to!int, b.to!int);
}

ptrdiff_t binSearchRight(alias pred, TR)(TR t, ptrdiff_t a, ptrdiff_t b)
if (isInstanceOf!(SegTree, TR)) {
    return TR.Engine.BinSearch!(true, pred)(t.eng, a.to!int, b.to!int);
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/container/stackpayload.d */
// module dcomp.container.stackpayload;

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

    private T* _data;
    private uint len, cap;

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

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

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

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

    void clear() {
        len = 0;
    }

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

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


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

void theCode(){
    ll l = scan;
    ll r = scan;
    if(l == r){
        writeln(0);
        return;
    }
    ll d = r/2 + 1;
    d = max(l, d);
    writeln(r % d);
}

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

/*********  That's All Folks!  *********/
import std.stdio, std.random, std.functional, std.container, std.algorithm;
import std.numeric, std.range, std.typecons, std.string, std.math, std.conv;
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, std.conv, std.string, std.array, std.algorithm;

long maximalModulus(long left, long right) {
    if (right / 2 + 1 >= left) {
        return right % (right / 2 + 1);
    }
    else {
        long max = -1;
        long i = 1;
        long x = 1;
        while (x > max + 1) {
            x = ((right - 1) / i) + 1;
            debug{writeln("x=", x, "right&x=", right%x, "max=", max);}
            if (right%x > max) {
                max = right%x;
            }
            if (x < left) {
                return right % left;
            }
            ++i;
        }
        return max;
    }
}

// void find_mod(long left, long right)
// {
//     long max_current = 0;
//     long max_delimeter = 0;
//     for (long a = right; a >= left; a--)
//     {
//         for (long b = max(a - 1, a / 2 + 1); b >= left ; b--)
//         {
//             auto current = a % b;
//             max_current = max(max_current, current);
//             if (max_current == b - 1)
//             {
//                 writeln(max_current);
//                 debug{writeln("A",a," B",b);}
//                 return;
//             }
//         }
//     }
//     writeln(max_current);
//     return;
// }

void main()
{
    int n;
    long l, r;
    scanf("%d", &n);
    getchar();

    for (int k = 0; k < n; k++){
	    scanf("%ld %ld", &l, &r);
        getchar();
        // find_mod(l, r);
        writeln(maximalModulus(l, r));
    }
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long l, r;
    readln.formattedRead!" %d %d "(l, r);
    long max_b = max(l, (r + 1) / 2);
    long max_a = min(max_b * 2, r);
    long maxrem = 0;
    foreach (i ; -5L .. 5L) {
      foreach (j ; -5L .. 5L) {
        long a = max(min(max_a + i, r), l);
        long b = max(min(max_b + j, r), l);
        if (b > a)
          continue;
        maxrem = max(maxrem, a % b);
      }
    }
    writeln(maxrem);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = r % max(r / 2 + 1, l);
	}

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


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

        int[] ansA, ansB;
        for (int i = 0, j; i < N; i = j) {
          for (j = i; j < N && A[i] == A[j]; ++j) {}
          if (!(j == N && A[N - 1] == '0')) {
            ansA ~= j;
          }
        }
        for (int i = 0, j; i < N; i = j) {
          for (j = i; j < N && B[i] == B[j]; ++j) {}
          if (!(j == N && B[N - 1] == '0')) {
            ansB ~= j;
          }
        }

        int[] ans;
        foreach (j; ansA) {
          ans ~= j;
        }
        foreach_reverse (j; ansB) {
          ans ~= j;
        }

        write(ans.length);
        foreach (j; ans) {
          write(" ", j);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip.map !(q{a == '1'}).array;
		auto t = readln.strip.map !(q{a == '1'}).array;

		int [] answer;
		int lo = 0;
		int hi = n - 1;
		int p = 0;
		foreach_reverse (i; 0..n)
		{
			auto cur = (p ? !s[hi] : s[lo]);
			if (cur == t[i])
			{
				answer ~= 1;
			}
			answer ~= i + 1;
			if (p)
			{
				hi -= 1;
			}
			else
			{
				lo += 1;
			}
			p ^= 1;
		}
		writefln !("%s\n%(%s %)") (answer.length, answer);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int l, r = n-1;
		bool inv;
		foreach_reverse (i; 0..n)
		{
			int ll = inv ? r : l;
			int rr = inv ? l : r;
			debug writeln("ll:", ll, " rr:", rr);
			if ((a[rr] == b[i]) != inv)
			{
				if (inv)
					++l;
				else
					--r;
				continue;
			}
			if ((a[ll] == b[i]) != inv)
			{
				ans[ti] ~= 1;
			}
			ans[ti] ~= i+1;
			if (inv)
				--r;
			else
				++l;
			inv = !inv;
			continue;
		}
	}

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

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

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

    while (t--) {
        int n;
        readf("%s", &n);
        readln;

        auto a = readln.chomp;
        auto b = readln.chomp;

        int[] ans;
        int p = 0;
        foreach (op; 0 .. n) {
            int cur = (a[p] - '0') ^ (op & 1);

            debug { writeln(p, ' ', op, ' ', cur); }

            if (cur == (b[n - op - 1] - '0')) {
                ans ~= 1;
            }

            ans ~= n - op;
            p = n - p - 1 + (op & 1);
        }

        ans.length.write;
        write(" ");
        ans.map!(to!string).join(" ").writeln;
    }
}

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

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

    while (t--) {
        int n;
        readf("%s", &n);
        readln;

        auto a = readln.chomp;
        auto b = readln.chomp;

        int[] ans;
        int p = 0;
        foreach (op; 0 .. n) {
            int cur = (a[p] - '0') ^ op;
            if (cur == (b[n - op - 1] - '0')) {
                ans ~= 1;
            }

            ans ~= n - op;
            p = n - p - 1;
        }

        ans.length.write;
        write(" ");
        ans.map!(to!string).join(" ").writeln;
    }
}