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() {
    int N = read!int;
    auto A = readarray!int;
    int[int] last;
    for (int i = 0; i < N; i++) {
        last[A[i]] = i;
    }
    int ans = -1;
    foreach (v, i; last) {
        foreach (u, j; last) {
            if (gcd(v, u) == 1) {
                ans = max(ans, i + j + 2);
            }
        }
    }
    writeln(ans);
}

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

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

void main()
{
  auto coprimes = new byte[1001][1001];
  foreach (i ; 1 .. 1001) {
    foreach (j ; i .. 1001) {
      if (gcd(i, j) == 1) {
        coprimes[i][j] = 1;
        coprimes[j][i] = 1;
      }
    }
  }
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    auto b = zip(iota(1, a.length + 1), a).array.sort!((x, y) => x[1] == y[1] ? x[0] > y[0] : x[1] > y[1]);
    auto c = b.uniq!((x, y) => x[1] == y[1]).array;
    long ans = -1;
    foreach (i ; 0 .. c.length) {
      foreach (j ; 0 .. c.length) {
        if (coprimes[c[i][1]][c[j][1]])
          ans = max(ans, c[i][0] + c[j][0]);
      }
    }
    writeln(ans);
  }
}


module _;
void main() {
	import std.stdio;
	int n;
	readf("%s ", &n);
	string vowels = "aeiou";
	int x = 0, y;
	for(int i = 5; i * i <= n; i++){
		if (n % i == 0) {
			x = i;
			y = n/i;
		}
	}
	if (!x) {
		writeln("-1");
		return;
	}
	foreach(i; 0..5) {
		string pat = vowels[i..5] ~ vowels[0..i];
		foreach(j; 0..y/5) {
			write(pat);
		}
		write(pat[0..y%5]);
	}
	foreach(i; 5..x) {
		write(vowels);
		foreach(j; 5..y) {
			write("x");
		}
	}
	writeln;
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int u, v;
		for (int i = 1; i * i <= n; i++)
		{
			if (n % i == 0 && i >= 5 && n / i >= 5)
			{
				u = i;
				v = n / i;
				break;
			}
		}
		if (u == 0 && v == 0)
		{
			writeln (-1);
			continue;
		}
		string res;
		foreach (i; 0..u)
		{
			foreach (j; 0..v)
			{
				res ~= "aeiou"[(i + j) % 5];
			}
		}
		writeln (res);
	}
}

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

enum string vowels = "aeiou";

void main() {
  int k = readln.strip.to!int;
  char[] z;
  z.reserve (k);
  for (int h = 5; h * h <= k; ++h) {
    if (k % h == 0) {
      int w = k / h;
      foreach (i; 0 .. h) {
        foreach (j; 0 .. w) {
          z ~= vowels[(i + j) % 5];
        }
      }
      writeln (z);
      return;
    }
  }
  writeln (-1);
}

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

string FMT_F = "%.10f";

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; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
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; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * y / gcd(x, y); }

//long mod = 10^^9 + 7;
long mod = 998244353;
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 main()
{
	auto K = RD!int;

	int a, b;
	for (int i = 5; i*i <= K; ++i)
	{
		if (K % i == 0)
		{
			if (K / i >= 5)
			{
				a = i;
				b = K / i;
				break;
			}
		}
	}
	if (a == 0)
		writeln(-1);
	else
	{
		auto str = "aiueo";
		foreach (i; 0..a)
		{
			foreach (j; 0..b)
			{
				write(str[((i%5)+j)%5]);
			}
		}
		writeln();
	}
	stdout.flush();
	debug readln();
}


import std.stdio;
import std.string;
import std.uni;
import std.array;
import std.algorithm;

string[] flag;

char[] get(int x0, int y0, int x1, int y1) {
	auto app = appender!(char[])();
	bool R = false, G = false, B = false;
	for (int i = x0; i < x1; i++) for (int j = y0; j < y1; j++) {
		if (flag[i][j] == 'R') {
			if (!R) {
				R = true;
				app.put('R');
			}
		} else if (flag[i][j] == 'G') {
			if (!G) {
				G = true;
				app.put('G');
			}
		} else {
			if (!B) {
				B = true;
				app.put('B');
			}
		}
	}
	return app.data;
}

void main() {
	int n, m;
	readf("%d %d\n", &n, &m);
	flag = new string[n];
	for (int i = 0; i < n; i++) flag[i] = readln();
	bool ans = false;
	if (n % 3 == 0) {
		auto app = appender!(char[])();
		int d = n / 3;
		app.put(get(0, 0, d, m));
		app.put(get(d, 0, 2 * d, m));
		app.put(get(2 * d, 0, n, m));
		char[] data = app.data;
		sort(data.representation);
		if (data == "BGR") ans = true;
	}
	if (m % 3 == 0) {
		auto app = appender!(char[])();
		int d = m / 3;
		app.put(get(0, 0, n, d));
		app.put(get(0, d, n, 2 * d));
		app.put(get(0, 2 * d, n, m));
		char[] data = app.data;
		sort(data.representation);
		if (data == "BGR") ans = true;
	}
	writeln(ans ? "YES" : "NO");
}

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;
import std.datetime, std.bigint;

int n, m;
char[][] flag;

void main() {
    scan(n, m);

    if (n % 3 && m % 3) {
        writeln("NO");
        return;
    }

    flag = new char[][](n, m);
    iota(n).each!(i => flag[i][] = readln.chomp);

    debug {
        writefln("%(%(%s %)\n%)", flag);
    }

    int r, c;

    if (n % 3 == 0) {
        r = n / 3;

        auto rgb = new int[](3);

        bool ok = true;

        foreach (k ; 0 .. 3) {
            char ch = flag[k * r][0];

            if (ch == 'R') rgb[0]++;
            else if (ch == 'G') rgb[1]++;
            else rgb[2]++;

            foreach (i ; k * r .. k * r + r) {
                foreach (j ; 0 .. m) {
                    if (flag[i][j] != ch) ok = false;
                }
            }
        }

        if (rgb == [1, 1, 1] && ok) {
            writeln("YES");
            return;
        }
    }

    if (m % 3 == 0) {
        c = m / 3;

        auto rgb = new int[](3);

        bool ok = true;

        foreach (k ; 0 .. 3) {
            char ch = flag[0][k * c];

            if (ch == 'R') rgb[0]++;
            else if (ch == 'G') rgb[1]++;
            else rgb[2]++;

            foreach (j ; k * c .. k * c + c) {
                foreach (i ; 0 .. n) {
                    if (flag[i][j] != ch) ok = false;
                }
            }

            if (rgb == [1, 1, 1] && ok) {
                writeln("YES");
                return;
            }
        }
    }

    writeln("NO");
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto H = s[0];
    auto W = s[1];
    auto B = H.iota.map!(_ => readln.chomp).array;

    if (H % 3 == 0) {
        dchar[] used;
        bool ok = true;
        foreach (k; 0..3) {
            char c = B[H / 3 * k][0];
            used ~= c;
            foreach (i; H/3*k..H/3*(k+1)) foreach (j; 0..W) if (B[i][j] != c) ok = false;
        }
        used.sort();
        if (ok && used == ['B', 'G', 'R'].to!(dchar[])) {
            "YES".writeln;
            return;
        }
    }

    if (W % 3 == 0) {
        dchar[] used;
        bool ok = true;
        foreach (k; 0..3) {
            char c = B[0][W / 3 * k];
            used ~= c;
            foreach (j; W/3*k..W/3*(k+1)) foreach (i; 0..H) if (B[i][j] != c) ok = false;
        }
        used.sort();
        if (ok && used == ['B', 'G', 'R'].to!(dchar[])) {
            "YES".writeln;
            return;
        }
    }

    "NO".writeln;
}

// Try Codeforces
// author: Leonardone @ NEETSDKASU
import std.stdio, std.string, std.array, std.algorithm, std.conv;

void main() {
    auto nm = to!(int[])(split(chomp(readln())));
    int n = nm[0], m = nm[1];
    auto xss = appender!(string[])();
    for (int i = 0; i < n; i++) {
        xss.put(chomp(readln()));
        if (!xss.data[i].count!( (a) => a == 'R' || a == 'G' || a == 'B' )) {
            writeln("NO");
            return;
        }
    }
    auto ans = false;
    if (n % 3 == 0) {
        int u = n / 3;
        bool flag = true;
        for (int x = 0; x < m; x++) {
            for (int y = 0; y < n; y++) {
                auto p = xss.data[y][x];
                auto a = xss.data[y/u*u][x];
                auto b = xss.data[(y/u+1)%3*u][x];
                auto c = xss.data[(y/u+2)%3*u][x];
                flag = flag && (p == a && p != b && p != c) && (x == 0 || p == xss.data[y][x-1]);
            }
        }
        ans = ans || flag;
    }
    if (m % 3 == 0) {
        int u = m / 3;
        bool flag = true;
        for (int y = 0; y < n; y++) {
            for (int x = 0; x < m; x++) {
                auto p = xss.data[y][x];
                auto a = xss.data[y][x/u*u];
                auto b = xss.data[y][(x/u+1)%3*u];
                auto c = xss.data[y][(x/u+2)%3*u];
                flag = flag && (p == a && p != b && p != c) && (y == 0 || p == xss.data[y-1][x]);
            }
        }
        ans = ans || flag;
    }
    writeln(ans ? "YES" : "NO");
}

// Try Codeforces
// author: Leonardone @ NEETSDKASU
import std.stdio, std.string, std.array, std.algorithm, std.conv;

void main() {
    auto nm = to!(int[])(split(chomp(readln())));
    int n = nm[0], m = nm[1];
    auto xss = appender!(string[])();
    for (int i = 0; i < n; i++) {
        xss.put(chomp(readln()));
        if (!xss.data[i].count!( (a) => a == 'R' || a == 'G' || a == 'B' )) {
            writeln("NO");
            return;
        }
    }
    auto ans = false;
    if (n % 3 == 0) {
        int u = n / 3;
        bool flag = true;
        for (int x = 0; x < m; x++) {
            for (int y = 0; y < n; y++) {
                auto p = xss.data[y][x];
                auto a = xss.data[y/u*u][x];
                auto b = xss.data[(y/u+1)%3*u][x];
                auto c = xss.data[(y/u+2)%3*u][x];
                flag = flag && (p == a && p != b && p != c);
            }
        }
        ans = ans || flag;
    }
    if (m % 3 == 0) {
        int u = m / 3;
        bool flag = true;
        for (int y = 0; y < n; y++) {
            for (int x = 0; x < m; x++) {
                auto p = xss.data[y][x];
                auto a = xss.data[y][x/u*u];
                auto b = xss.data[y][(x/u+1)%3*u];
                auto c = xss.data[y][(x/u+2)%3*u];
                flag = flag && (p == a && p != b && p != c);
            }
        }
        ans = ans || flag;
    }
    writeln(ans ? "YES" : "NO");
}

// Try Codeforces
// author: Leonardone @ NEETSDKASU
import std.stdio, std.string, std.array, std.algorithm, std.conv;

void main() {
    auto nm = to!(int[])(split(chomp(readln())));
    int n = nm[0], m = nm[1];
    auto xss = appender!(string[])();
    for (int i = 0; i < n; i++) {
        xss.put(chomp(readln()));
    }
    auto ans = false;
    if (n % 3 == 0) {
        int u = n / 3;
        bool flag = true;
        for (int x = 0; x < m; x++) {
            for (int y = 0; y < n; y++) {
                auto p = xss.data[y][x];
                auto a = xss.data[y/u*u][x];
                auto b = xss.data[(y/u+1)%3*u][x];
                auto c = xss.data[(y/u+2)%3*u][x];
                flag = flag && (p == a && p != b && p != c);
            }
        }
        ans = ans || flag;
    }
    if (m % 3 == 0) {
        int u = m / 3;
        bool flag = true;
        for (int y = 0; y < n; y++) {
            for (int x = 0; x < m; x++) {
                auto p = xss.data[y][x];
                auto a = xss.data[y][x/u*u];
                auto b = xss.data[y][(x/u+1)%3*u];
                auto c = xss.data[y][(x/u+2)%3*u];
                flag = flag && (p == a && p != b && p != c);
            }
        }
        ans = ans || flag;
    }
    writeln(ans ? "YES" : "NO");
}


import std;

int t,n,m;
long[] answers;

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d", &n);
        getchar();
        auto a = readln.split.to!(int[]);

        auto rbt = redBlackTree!true(0);
        rbt.removeKey(0);

        for (int i = 0; i < n; i++){
            while (a[i] % 2 == 0){
                a[i] /= 2;
            }

            rbt.stableInsert(a[i]);
        }

        //writefln("%(%d %)", rbt[]);

        bool good = true;
        auto b = readln.split.to!(int[]);
        for (int i = 0; i < n; i++){
            while (b[i] != 0){
                if (b[i] in rbt){
                    rbt.removeKey(b[i]);
                    break;
                }

                b[i] /= 2;
            }

            if (b[i] == 0){
                good = false;
                break;
            }
        }

        if (good != false){
            writefln("YES");
        } else {
            writefln("NO");
        }
    }
    //writefln("%(%s \n%)", answers);
}

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

void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!int).array;
    auto B = readln.chomp.split(" ").map!(to!int).array;

    bool C() {
        int[int] aps;
        foreach (a; A) {
            while (a % 2 == 0) a /= 2;
            aps[a] = aps.get(a, 0) + 1;
        }
        foreach (b; B) {
            while (b % 2 == 0) b /= 2;
            while (b > 0) {
                if (aps.get(b, 0) > 0) {
                    aps[b] -= 1;
                    break;
                } else {
                    b /= 2;
                }
            }
        }
        return aps.values.all!((x) => x == 0);
    }
    writeln(C() ? "YES" : "NO");
}

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


import std.stdio : readln, writeln;

struct IO {
  import std.conv : to;
  import std.range : empty, front, popFront, split;

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

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

  string[] tokens;
}

void main() {
  import core.stdc.limits : INT_MAX;
  import std.algorithm : max, min, fill;

  IO io;
  int T = io.readInt;
  while (T--) {
    int n = io.readInt;
    int m = io.readInt;
    int[] a = new int[n];
    for (int i = 0; i < n; ++i) {
      a[i] = io.readInt;
    }
    bool[] gap = new bool[n - 1];
    fill(gap, true);
    for (int i = 0; i < m; ++i) {
      gap[io.readInt - 1] = false;
    }
    int[] suffixMin = new int[n + 1];
    suffixMin[n] = INT_MAX;
    for (int i = n; i--;) {
      suffixMin[i] = min(a[i], suffixMin[i + 1]);
    }
    int prefixMax = 0;
    bool ok = true;
    for (int i = 0; i + 1 < n; ++i) {
      prefixMax = max(prefixMax, a[i]);
      ok &= !gap[i] || prefixMax <= suffixMin[i + 1];
    }
    writeln(ok ? "YES" : "NO");
  }
}

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

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

void solve(){
    A: foreach(_; 0 .. rint){
        int n = rint, m = rint;
        int[] as = rint(n), ps = rint(m);

        bool[] xs = new bool[](n);
        foreach(p; ps) xs[p - 1] = 1;

        int mina = 999, maxa = -1;
        int oldmaxa = -1;
        foreach(int i, a; as){
            mina.chmin(a), maxa.chmax(a);
            if(! xs[i]){
                if(mina < oldmaxa){
                    "NO".writeln;
                    continue A;
                }
                oldmaxa = maxa;
                mina = 999, maxa = -1;
            }
        }
        "YES".writeln;

    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto a = RDA;
		auto p = RDA!int(-1);
		p.sort();
		int[][] lr;
		int last = p[0], l = p[0];
		foreach (i; 1..m)
		{
			if (p[i] != last+1)
			{
				lr ~= [l, last+1];
				l = p[i];
			}
			last = p[i];
		}
		lr ~= [l, last+1];
		foreach (e; lr)
		{
			a[e[0]..e[1]+1].sort();
		}
		bool ok = true;
		foreach (i; 1..n)
		{
			if (a[i-1] > a[i])
				ok = false;
		}
		ans[ti] = ok;
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	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 = 998244353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto a = RDA;
		auto p = RDA!int(-1);
		int[][] lr;
		int last = p[0], l = p[0];
		foreach (i; 1..m)
		{
			if (p[i] != last+1)
			{
				lr ~= [l, last+1];
				l = p[i];
			}
			last = p[i];
		}
		lr ~= [l, last+1];
		foreach (e; lr)
		{
			a[e[0]..e[1]+1].sort();
		}
		bool ok = true;
		foreach (i; 1..n)
		{
			if (a[i-1] > a[i])
				ok = false;
		}
		ans[ti] = ok;
	}

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


immutable multi = true;

void solve(int tc)
{
	int n = readInt!int;
	auto s = readString;
	int[][2] types;
	foreach(i, si; s) types[int(si == '2')] ~= cast(int)i;
	auto matches = new char[][](n, n);
	foreach(ref row; matches) row[] = '=';
	foreach(i; 0 .. n) matches[i][i] = 'X';
	if (types[1].length >= 1 && types[1].length <= 2)
	{
		writeln("NO");
		writeln;
		return;
	}
	writeln("YES");
	void setWin(int i, int j)
	{
		matches[i][j] = '+';
		matches[j][i] = '-';
	}
	foreach(i; 0 .. types[1].length) setWin(types[1][i], types[1][(i+1)%(types[1].length)]);
	foreach(row; matches) writeln(row);
	writeln;
}

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

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

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

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

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

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

void main()
{
    int t;
    scanf("%d", &t);
    foreach(_; 0..t)
    {
        int str_len;
        scanf("%d", &str_len);
        getchar();
        // auto str = readln.strip();
        // writeln(str);
        int[] players = new int[str_len];
        int[] first_players, second_players;
        for (int i = 0; i < str_len; i++)
        {
            char tmp;
            scanf("%c", &tmp);
            if (tmp == '1')
            {
                players[i] = 1;
                first_players ~= i;
            }
            else
            {
                players[i] = 2;
                second_players ~= i;
            }
        }
        getchar();
        if (second_players.length == 1 || second_players.length == 2)
        {
            writeln("NO");
            continue;
        }
        else
        {
            writeln("YES");
            if (!second_players.empty)
            {
                second_players ~= second_players.front();
                second_players.popFront();
            }
            int last_win = -1;
            int last_loss = -1;
            for(int i = 0; i < str_len; i++)
            {
                string line;
                if (!second_players.empty)
                {
                    last_win = second_players.front();
                }
                debug{
                    writeln("cur:", i);
                    writeln("win:", last_win);
                    writeln("loss:", last_loss);
                }
                for(int j = 0; j < str_len; j++)
                {
                    if (i == j)
                        line ~= 'X';
                    else if (players[i] == 1)
                        line ~= '=';
                    else if (players[i] == 2 && players[j] == 1)
                        line ~= '=';
                    else if (players[i] == 2 && players[j] == 2)
                    {
                        if (j == last_loss)
                        {
                            // writeln("last loss=", last_loss);
                            line ~= '-';
                        }
                        else if (j == last_win)
                        {
                            line ~= '+';
                            if (second_players.length > 1)
                                last_loss = i;
                        }
                        else if (i > j && j != last_loss)
                            line ~= '+';
                        else
                            line ~= '-';
                    }
                }
                if (!second_players.empty && players[i] == 2)
                {
                    // writeln("before pop:", second_players);
                    second_players.popFront();
                }
                writeln(line);
            }
        }
    }
}

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

void main()
{
    int t;
    scanf("%d", &t);
    foreach(_; 0..t)
    {
        int str_len;
        scanf("%d", &str_len);
        getchar();
        // auto str = readln.strip();
        // writeln(str);
        int[] players = new int[str_len];
        int[] first_players, second_players;
        for (int i = 0; i < str_len; i++)
        {
            char tmp;
            scanf("%c", &tmp);
            if (tmp == '1')
            {
                players[i] = 1;
                first_players ~= i;
            }
            else
            {
                players[i] = 2;
                second_players ~= i;
            }
        }
        getchar();
        if (second_players.length == 1 || second_players.length == 2)
        {
            writeln("NO");
            continue;
        }
        else
        {
            writeln("YES");
            if (!second_players.empty)
            {
                second_players ~= second_players.front();
                second_players.popFront();
            }
            int cur_second_player = -1;
            for(int i = 0; i < str_len; i++)
            {
                string line;
                if (!second_players.empty)
                {
                    cur_second_player = second_players.front();

                }
                debug{
                    writeln("cur:", i);
                    writeln("cur_2:", cur_second_player);
                    writeln("2pl:", second_players);
                }
                for(int j = 0; j < str_len; j++)
                {
                    if (i == j)
                        line ~= 'X';
                    else if (players[i] == 1)
                        line ~= '=';
                    else if (players[i] == 2 && players[j] == 1)
                        line ~= '=';
                    else if (players[i] == 2 && players[j] == 2)
                    {
                        if (j == cur_second_player)
                            line ~= '+';
                        else
                            line ~= '-';
                    }
                }
                if (!second_players.empty && players[i] == 2)
                {
                    // writeln("before pop:", second_players);
                    second_players.popFront();
                }
                writeln(line);
            }
        }
    }
}


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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto s = readln.strip;
    int best1 = -1;
    int eq1 = -1;

    foreach (i ; 0 .. cast(int)s.length - 1) {
      int digit1 = s[i] - '0';
      int digit2 = s[i + 1] - '0';
      if (digit1 + digit2 < 10 && digit1 + digit2 > digit1) {
        best1 = i;
        break;
      }
      if (digit1 + digit2 < 10 && digit1 + digit2 == digit1) {
        if (i + 2 >= s.length) {
          best1 = i;
          break;
        }
        int digit3 = s[i + 2] - '0';
        if (digit3 > digit2) {
          best1 = i;
          break;
        } else if (digit3 == digit2) {
          eq1 = i;
        }
      }
    }
    if (best1 == -1) {
      if (eq1 != -1)
        best1 = eq1;
      else
        best1 = cast(int)s.length - 2;
    }

    bool have_best2 = false;
    int default_best2;
    foreach_reverse (i ; 0 .. cast(int)s.length - 1) {
      if ((s[i] - '0') + (s[i + 1] - '0') >= 10) {
        have_best2 = true;
        default_best2 = i;
        break;
      }
    }
    int ans = best1;
    int best2 = -1;
    int eq2 = -1;
    if (have_best2) {
      foreach (i ; 0 .. cast(int)s.length - 1) {
        int digit1 = s[i] - '0';
        int digit2 = s[i + 1] - '0';
        if (digit1 + digit2 < 10)
          continue;
        if ((digit1 + digit2) / 10 > digit1) {
          best2 = i;
          break;
        }
        if ((digit1 + digit2) / 10 == digit1) {
          if ((digit1 + digit2) % 10 > digit2) {
            best2 = i;
            break;
          } else if ((digit1 + digit2) % 10 == digit2) {
            eq2 = i;
          }
        }
      }
      if (best2 == -1) {
        if (eq2 != -1)
          best2 = eq2;
        else
          best2 = default_best2;
      }
      ans = best2;
    }
    auto s1 = s[0 .. ans];
    auto s2 = ((s[ans] - '0') + (s[ans + 1] - '0')).to!string;
    auto s3 = s[ans + 2 .. $];
    writefln("%s%s%s", s1, s2, s3);
  }
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;

      auto candidates = new int[][](0, 2);
      foreach(i; 0..cast(int)S.length - 1) {
        int sum = (S[i] - '0') + (S[i + 1] - '0');
        candidates ~= [i, sum];
      }

      auto twos = candidates.filter!"a[1] > 9";
      if (twos.empty) {
        return candidates[0][1].to!string ~ S[2..$];
      } else {
        auto c = candidates.filter!"a[1] > 9".array[$ - 1];
        return S[0..c[0]] ~ c[1].to!string ~ S[c[0] + 2..$];
      }
    }

    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;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		auto n = s.length.to !(int);
		int p = 1;
		foreach (i; 1..n)
		{
			if (s[i - 1] + s[i] > '0' + '9')
			{
				p = i;
			}
		}
		writeln (s[0..p - 1], s[p - 1] + s[p] - '0' - '0',
		    s[p + 1..$]);
	}
}

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

bool better1(int a, int b, int c)
{
  int x1 = (a + b) * 10 + c;
  int x2 = (b + c) < 10 ? a * 10 + (b + c) : a * 100 + (b + c);
  return x2 >= x1;
}

bool better2(int a, int b, int c)
{
  int x1 = (a + b) * 10 + c;
  int x2 = (b + c) < 10 ? a * 10 + (b + c) : a * 100 + (b + c);
  return (b + c) >= 10 && x2 >= x1;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto s = readln.strip;
    int best1 = 0;
    foreach (i ; 0 .. cast(int)s.length - 2) {
      if (!better1(s[i] - '0', s[i + 1] - '0', s[i + 2] - '0'))
        break;
      best1 = i + 1;
    }
    bool have_best2 = false;
    int best2;
    foreach (i ; 0 .. cast(int)s.length - 1) {
      if ((s[i] - '0') + (s[i + 1] - '0') >= 10) {
        have_best2 = true;
        best2 = i;
        break;
      }
    }
    int ans = best1;
    if (have_best2) {
      foreach (i ; best2 .. cast(int)s.length - 2) {
        if (!better2(s[i] - '0', s[i + 1] - '0', s[i + 2] - '0'))
          break;
        best2 = i + 1;
      }
      ans = best2;
    }
    auto s1 = s[0 .. ans];
    auto s2 = ((s[ans] - '0') + (s[ans + 1] - '0')).to!string;
    auto s3 = s[ans + 2 .. $];
    writefln("%s%s%s", s1, s2, s3);
  }
}

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 s = readln.strip;
		auto n = s.length.to !(int);
		int p = n - 1;
		foreach (i; 1..n)
		{
			if (s[i - 1] + s[i] > '0' + '9')
			{
				p = i;
			}
		}
		writeln (s[0..p - 1], s[p - 1] + s[p] - '0' - '0',
		    s[p + 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)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto s = RD!string;
		auto ss = RD!string;

		if (s.length < ss.length) continue;
		if ((ss.length - s.length) % 2)
			s.popFront;

		int i, j;
		while (i < s.length && j < ss.length)
		{
			if (s[i] == ss[j])
			{
				++i;
				++j;
			}
			else
			{
				i += 2;
			}
		}
		debug writeln("i:", i, " j:", j);
		if (j == ss.length)
			ans[ti] = true;
	}

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

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

void main()
{
	int q = readInt!int;
	while (q--)
	{
		char[] s = cast(char[])readString;
		s.reverse;
		int ns = cast(int)s.length;
		char[] t = cast(char[])readString;
		t.reverse;
		int ei = -1;
		foreach(i, si; s)
		{
			if (si == t[0] && (i&1) == 0)
			{
				if (ei == -1) ei = cast(int)i;
			}
		}
		bool can(int i, char[] t)
		{
			while (i < ns && t.length > 0)
			{
				if (s[i] == t[0])
				{
					i++;
					t = t[1 .. $];
					continue;
				}
				else
				{
					i += 2;
				}
			}
			return t.length == 0;
		}
		bool cane = ei != -1 && can(ei, t.dup);
		if (cane) writeln("yes"); else writeln("no");
	}
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

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

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

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

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

string s, t;
int sn, tn;

bool solve(int si, int ti)
{
  if (ti == tn)
    return true;

  if (si == sn)
    return false;

  if (s[si] != t[ti] && si + 2 > sn)
    return false;

  if (s[si] == t[ti]) {
    bool ans1, ans2;
//    if (si + 2 <= sn)
//      ans1 = solve(si + 2, ti);
    if (si + 1 <= sn && ti + 1 <= tn)
      ans2 = solve(si + 1, ti + 1);
    return ans1 || ans2;
  } else {
    bool ans1, ans2;
    if (si + 2 <= sn)
      ans1 = solve(si + 2, ti);
    return ans1 || ans2;
  }
}

void main()
{
  long q;
  readf!" %d "(q);
  while (q--) {
    s = readln.strip.retro.text;
    t = readln.strip.retro.text;
    sn = cast(int)s.length;
    tn = cast(int)t.length;
//    writeln(s);
//    writeln(t);
    writeln(solve(0, 0) ? "YES" : "NO");
  }
}

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

bool solve (string s, string t)
{
	if ((s.length % 2) != (t.length % 2))
	{
		s = s[1..$];
	}
	int pos = 0;
	bool skip = false;
	foreach (ref c; s)
	{
		if (skip)
		{
			skip = false;
			continue;
		}
		if (t[pos] == c)
		{
			pos += 1;
		}
		else
		{
			skip = true;
		}
		if (pos == t.length)
		{
			return true;
		}
	}
	return false;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		auto t = readln.strip;
		writeln (solve (s, t) ? "YES" : "NO");
	}
}

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

void main()
{
	int q = readInt!int;
	while (q--)
	{
		char[] s = cast(char[])readString;
		int ns = cast(int)s.length;
		char[] t = cast(char[])readString;
		int ei = -1;
		int oi = -1;
		foreach(i, si; s)
		{
			if (si == t[0])
			{
				if (i & 1)
				{
					if (oi == -1) oi = cast(int)i;
				}
				else if (ei == -1) ei = cast(int)i;
			}
		}
		bool can(int i, char[] t)
		{
			while (i < ns && t.length > 0)
			{
				if (s[i] == t[0])
				{
					i++;
					t = t[1 .. $];
					continue;
				}
				else
				{
					i += 2;
				}
			}
			return t.length == 0;
		}
		bool cane = ei != -1 && can(ei, t.dup);
		bool cano = oi != -1 && can(oi, t.dup);
		if (cane || cano) writeln("yes"); else writeln("no");
	}
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

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

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

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


import std.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) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new long[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto used = new bool[](n);
		foreach (i; 0..n)
		{
			auto k = RD;
			bool ok;
			foreach (j; 0..k)
			{
				auto e = RD!int-1;
				if (ok) continue;
				if (!used[e])
				{
					used[e] = true;
					ok = true;
				}
			}
			if (!ok)
			{
				ans[ti] = [i+1];
			}
		}
		if (!ans[ti].empty)
		{
			foreach (i; 0..n)
			{
				if (!used[i])
				{
					ans[ti] ~= i+1;
					break;
				}
			}
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
		{
			writeln("OPTIMAL");
		}
		else
		{
			writeln("IMPROVE");
			writeln(e[0], " ", e[1]);
		}
	}
	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(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    A: foreach(_; 0 .. scan!int){
        int n = scan!int;
        bool[] isMarried = new bool[](n);
        bool[] isSold = new bool[](n);
        foreach(i; 0 .. n){
            int k = scan!int;
            int[] gs = scan!int(k).map!(x => x - 1).array;
            foreach(g; gs){
                if(! isSold[g]){
                    isSold[g] = 1;
                    isMarried[i] = 1;
                    break;
                }
            }
        }
        auto gq = new Queue!int;
        foreach(g; 0 .. n) if(! isSold[g]) gq.enq(g);

        if(gq.isEmpty){
            "OPTIMAL".print;
            continue A;
        }
        else{
            "IMPROVE".print;
            foreach(i; 0 .. n) if(! isMarried[i]){
                print(i + 1, gq.deq + 1);
                break;
            }
        }

    }
}

// ----- キュー -----
class Queue(T){
	private T[] xs;
	private uint i, j; // i : 次に読み出す位置　j: 次に書き込む位置
	this(){	}
	this(T[] xs){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){
		while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1;
		xs[j ++] = x;
	}
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(){ return new Queue!T; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}

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

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

void solve(){
    A: foreach(_; 0 .. scan!int){
        int n = scan!int;
        bool[] isMarried = new bool[](n);
        bool[] isSold = new bool[](n);
        foreach(i; 0 .. n){
            int k = scan!int;
            int[] gs = scan!int(k).map!(x => x - 1).array;
            foreach(g; gs){
                if(! isSold[g]){
                    isSold[i] = 1;
                    isMarried[i] = 1;
                    break;
                }
            }
        }
        auto gq = new Queue!int;
        foreach(g; 0 .. n) if(! isSold[g]) gq.enq(g);

        if(gq.isEmpty){
            "OPTIMAL".print;
            continue A;
        }
        else{
            "IMPROVE".print;
            foreach(i; 0 .. n) if(! isMarried[i]){
                print(i + 1, gq.deq + 1);
                break;
            }
        }

    }
}

// ----- キュー -----
class Queue(T){
	private T[] xs;
	private uint i, j; // i : 次に読み出す位置　j: 次に書き込む位置
	this(){	}
	this(T[] xs){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){
		while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1;
		xs[j ++] = x;
	}
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(){ return new Queue!T; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}


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

long solve_max(long[] pfa, long n)
{
  long total = cast(long)pfa.length + n;
  long accounted = total - total / 4;
  long score = min(accounted, n) * 100;
  long remaining = accounted - min(accounted, n);
  return score + (remaining > 0 ? pfa[cast(int)remaining - 1] : 0L);
}

long solve_min(long[] pfb, long n)
{
  long total = cast(long)pfb.length + n;
  long remaining = min(cast(long)pfb.length, total - total / 4);
  return (remaining > 0 ? pfb[cast(int)remaining - 1] : 0L);
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array.sort!((x, y) => x > y);
    auto b = readln.strip.split.map!(to!long).array.sort!((x, y) => x > y);

    long[] pfa;
    long[] pfb;

    long sum = 0;
    foreach (x ; a) {
      sum += x;
      pfa ~= sum;
    }
    sum = 0;
    foreach (x ; b) {
      sum += x;
      pfb ~= sum;
    }
    writeln(iota(0L, 1000000L).map!(x => solve_max(pfa, x) >= solve_min(pfb, x)).assumeSorted.lowerBound(true).length);
  }
}

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

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

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

int[] a, b, A, B;

int solve(int m) {
  int n = a.length.to!int;

  int q = n + m;
  q -= q / 4;

  int pointB = B[min(q, B.length) - 1];

  int pointA = m * 100;
  if (q > m) {
    pointA += A[q - m - 1];
  }

  return pointA >= pointB;
}

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

  while (t--) {
    int n;
    read(n);
    a = list!int;
    b = list!int;

    sort(a);
    reverse(a);
    sort(b);
    reverse(b);

    A = a.dup;
    B = b.dup;
    foreach (i; 1 .. n) A[i] = A[i - 1] + A[i];
    foreach (i; 1 .. n) B[i] = B[i - 1] + B[i];

    if (solve(0)) {
      writeln(0);
      continue;
    } else {
      auto low = 0;
      auto high = 300000;

      while (high > low + 1) {
        int mid = high + low;
        mid /= 2;

        if (solve(mid)) {
          high = mid;
        } else {
          low = mid;
        }
      }

      writeln(high);
    }
  }
}

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

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
auto sp(R)(R r, size_t i, size_t j)
{
	if (j < i) return 0;
	if (i == 0) return r[j];
	return r[j] - r[i - 1];
}
void solve()
{
	int n = readInt!int;
	auto a = new int[](n);
	auto b = new int[](n);
	foreach(ref ai; a) ai = readInt!int;
	foreach(ref bi; b) bi = readInt!int;
	sort(a); sort(b);
	a.reverse, b.reverse;
	auto pa = a.cumulativeFold!((a, b)=> cast(long)a + b).array;
	auto pb = b.cumulativeFold!((a, b)=> cast(long)a + b).array;
	int used = n - (n/4);
	int hi = 5 * 1_000_00;
	int lo = 0;
	int ans = -1;
	while (lo <= hi)
	{
		int mi = (lo + hi) / 2;
		int nn = mi + n;
		int usedmi = nn - nn / 4;
		int usedorig = max(0, usedmi - mi);
		int usednew = usedmi - usedorig;
		long sa = usednew * 100;
		if (usedorig) sa += pa[usedorig - 1];
		long sb = pb[min(n, usedmi) - 1];
		if (sa >= sb)
		{
			ans = mi;
			hi = mi - 1;
		}
		else
		{
			lo = mi + 1;
		}
	}
	ans.writeln;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

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

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

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

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    int n; readf!"%s\n"(n);
    auto a = readln.splitter.map!(to!int).array.sort.reverse;
    auto b = readln.splitter.map!(to!int).array.sort.reverse;
    int low = -1, high = 3 * n + 1;
    while (low + 1 < high) {
      int mid = (low + high) / 2;
      int k = n + mid;
      int r = k - k / 4;
      long A, B;
      foreach(i; 0 .. r) {
        A += (i < mid) ? 100 : a[i - mid];
        B += (i < n) ? b[i] : 0;
      }
      ((A >= B) ? high : low) = mid;
    }
    high.writeln;
  }

} // main

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

string FMT_F = "%.10f";

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

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

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

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

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

		a.sort();
		b.sort();

		auto aa = new long[](n+1);
		auto bb = new long[](n+1);
		foreach (i; 0..n)
		{
			aa[i+1] = aa[i] + a[i];
			bb[i+1] = bb[i] + b[i];
		}
		auto tot = a.sum - b.sum;

		auto i = n;
		while (true)
		{
			if (tot + (i-n) * 100 - aa[i/4] + bb[max(i/4-(i-n), 0)] >= 0)
				break;
			++i;
		}
		ans[ti] = i - n;
	}

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

		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		reverse (a);

		auto b = readln.splitter.map !(to !(int)).array;
		sort (b);
		reverse (b);

		auto sa = [0];
		foreach (ref c; a)
		{
			sa ~= sa.back + c;
		}

		auto sb = [0];
		foreach (ref c; b)
		{
			sb ~= sb.back + c;
		}

		bool ok (int add)
		{
			auto num = n + add;
			auto part = num - num / 4;

			int resA = 0;
			int numA = part;
			int fullA = min (add, numA);
			numA -= fullA;
			resA += fullA * 100;
			resA += sa[numA];

			int resB = 0;
			int numB = part;
			int someB = min (n, numB);
			numB -= someB;
			resB += sb[someB];

			debug {writeln (n, " ", add, ": ", resA, " ", resB);}
			return resA >= resB;
		}

		auto lo = 0;
		auto hi = 2 * 10 ^^ 7;
		while (lo < hi)
		{
			auto me = (lo + hi) >> 1;
			if (ok (me))
			{
				hi = me;
			}
			else
			{
				lo = me + 1;
			}
		}
		writeln (lo);
	}
}

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

enum L = 100;

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        auto A = new int[N];
        auto B = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt();
        }
        foreach (i; 0 .. N) {
          B[i] = readInt();
        }
        A.sort.reverse;
        B.sort.reverse;

        int lo = -1, hi = 3 * N + 1;
        for (; lo + 1 < hi; ) {
          const mid = (lo + hi) / 2;
          const k = N + mid;
          const num = k - k / 4;
          long scoreA, scoreB;
          foreach (i; 0 .. num) {
            scoreA += (i < mid) ? L : A[i - mid];
            scoreB += (i < N) ? B[i] : 0;
          }
          ((scoreA >= scoreB) ? hi : lo) = mid;
        }
        writeln(hi);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
auto sp(R)(R r, size_t i, size_t j)
{
	if (j < i) return 0;
	if (i == 0) return r[j];
	return r[j] - r[i - 1];
}
void solve()
{
	int n = readInt!int;
	auto a = new int[](n);
	auto b = new int[](n);
	foreach(ref ai; a) ai = readInt!int;
	foreach(ref bi; b) bi = readInt!int;
	sort(a); sort(b);
	a.reverse, b.reverse;
	auto pa = a.cumulativeFold!((a, b)=> cast(long)a + b).array;
	auto pb = b.cumulativeFold!((a, b)=> cast(long)a + b).array;
	int used = n - (n/4);
	int hi = 5 * 1_000_00;
	int lo = 0;
	int ans = -1;
	while (lo <= hi)
	{
		int mi = (lo + hi) / 2;
		int nn = mi + n;
		int usedmi = nn - nn / 4;
		int usedorig = max(0, usedmi - mi);
		int usednew = usedmi - usedorig;
		long sa = usednew * 100;
		if (usedorig) sa += pa[usedorig - 1];
		long sb = pb[$ - 1];
		if (sa >= sb)
		{
			ans = mi;
			hi = mi - 1;
		}
		else
		{
			lo = mi + 1;
		}
	}
	ans.writeln;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

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

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

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


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

void main () {
	auto n = readln.strip.to !(int);
	auto a = readln.splitter.map !(to !(long)).array;
	auto b = readln.splitter.map !(to !(int)).array;

	auto g = new int [] [n];
	foreach (i; 0..n) if (b[i] > 0) g[b[i] - 1] ~= i;

	auto used = new bool [n];
	auto h = new int [] [n];

	void recur (int v) {
		if (used[v]) return;
		used[v] = true;
		foreach (u; g[v]) {
			recur (u);
			if (a[u] > 0) {h[v] ~= u; a[v] += a[u];}
			else h[u] ~= v;
		}
	}

	foreach (v; 0..n) recur (v);
	writeln (a.sum);

	int cur = 0;
	used[] = false;
	int [] p;

	void topSort (int v) {
		if (used[v]) return;
		used[v] = true;
		foreach (u; h[v]) topSort (u);
		p ~= v + 1;
	}

	foreach (v; 0..n) topSort (v);
	writefln !("%(%s %)") (p);
}

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

DList!string _words;
void read(T)(out T t)
{
  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;
  t = to!T(word);
}

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

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 log =
  q{
    debug
    {
     _loglevel++;
     mixin(`_log!(__FUNCTION__, `, [ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back))].joiner(", ").array, `);`);
     scope(exit) _loglevel--;
    }
};

void main()
{
  long n;
  read(n);

  auto a = Array!long(); a.length = n.ind;
  auto b = Array!long(); b.length = n.ind;
  auto children = Array!(Appender!(long[]))(); children.length = n.ind;

  foreach(i; 0 .. n)
    read(a.at(i));
  foreach(ref childrenArray; children)
    childrenArray = appender!(long[])();
  foreach(i; 0 .. n)
    {
      read(b.at(i));
      if (b.at(i) == -1)
        continue;
      b.at(i)--;
      children.at(b.at(i)).put(i);
    }
  auto roots = iota(0, n).filter!(i => b.at(i) == -1).array;

  auto operations = appender!(long[])();
  auto done = new bool[n.ind];
  auto ans = long(0);

  void doOperation(long node)
  {
    assert(!done.at(node));
    if (b.at(node) != -1)
      a.at(b.at(node)) += a.at(node);
    operations.put(node);
    ans += a.at(node);
    done.at(node) = true;
  }

  void solveTree(long node)
  {
    mixin(log);
    foreach(child; children.at(node))
      {
        solveTree(child);
        if (a.at(child) >= 0)
          doOperation(child);
      }
  }
  foreach(root; roots)
    {
      solveTree(root);
    }

  void solveRemaining(long node)
  {
    if (!done.at(node))
      doOperation(node);
    foreach(child; children.at(node))
        solveRemaining(child);
  }

  foreach(root; roots)
    solveRemaining(root);

  writeln(ans);
  foreach(operation; operations)
    write(operation + 1, " ");
  writeln;
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		b[] -= 1;

		auto g = new int [] [n];
		foreach (i; 0..n)
		{
			if (b[i] >= 0)
			{
				g[b[i]] ~= i;
			}
		}

		auto used = new bool [n];
		auto h = new int [] [n];

		void recur (int v, int w)
		{
			if (used[v])
			{
				return;
			}
			used[v] = true;
			foreach (u; g[v])
			{
				if (u != w)
				{
					recur (u, v);
					if (a[u] > 0)
					{
						h[v] ~= u;
						a[v] += a[u];
					}
					else
					{
						h[u] ~= v;
					}
				}
			}
		}

		foreach (v; 0..n)
		{
			recur (v, -1);
		}

		writeln (a.sum);

		int cur = 0;
		used[] = false;
		auto p = new int [n];

		void topologicalSort (int v)
		{
			if (used[v])
			{
				return;
			}
			used[v] = true;
			foreach (u; h[v])
			{
				topologicalSort (u);
			}
			p[cur] = v + 1;
			cur += 1;
		}

		foreach (v; 0..n)
		{
			topologicalSort (v);
		}
		writefln !("%(%s %)") (p);
	}
}


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

struct Cmb
{
	void init(size_t n)
	{
		long powmod(long a, long p)
		{
			long ans = 1;
			long mul = a;
			while (p > 0)
			{
				if ((p & 1) == 1)
					ans.modm(mul);
				p >>= 1;
				mul.modm(mul);
			}
			return ans;
		}

		++n;
		fact = new long[2][](n);
		fact[0][0] = 1;
		foreach (i; 1..n)
		{
			fact[i][0] = fact[i-1][0];
			fact[i][0].modm(i);
		}
		fact[n-1][1] = powmod(fact[n-1][0], mod - 2);
		foreach_reverse (i; 0..n-1)
		{
			fact[i][1] = fact[i+1][1];
			fact[i][1].modm(i+1);
		}
	}

	long get(size_t n, size_t r)
	{
		long res = fact[n][0];
		res.modm(fact[r][1]);
		res.modm(fact[n-r][1]);
		return res;
	}

	long[2][] fact;
}

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

		auto cnt = new int[](n+1);
		foreach (i; 0..n)
		{
			++cnt[a[i]];
		}

		foreach_reverse (i; 0..n+1)
		{
			if (cnt[i] < k)
				k -= cnt[i];
			else
			{
				ans[ti] = cmb.get(cnt[i], k);
				break;
			}
		}
	}

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

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

immutable int mod = 10 ^^ 9 + 7;

int powMod (int a, int p)
{
	int res = 1;
	for ( ; p > 0; p >>= 1)
	{
		if (p & 1)
		{
			res = (res * 1L * a) % mod;
		}
		a = (a * 1L * a) % mod;
	}
	return res;
}

alias inv = a => powMod (a, mod - 2);

int fact (int n)
{
	int res = 1;
	for (int i = 1; i <= n; i++)
	{
		res = (res * 1L * i) % mod;
	}
	return res;
}

int c (int n, int k)
{
	return fact (n) * 1L * inv (fact (n - k)) % mod * 1L *
	    inv (fact (k)) % mod;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort !(q{a > b}) (a);

		int lo = k - 1;
		int hi = k;
		if (a[lo] != a[hi])
		{
			writeln (1);
			continue;
		}

		while (lo > 0 && a[lo - 1] == a[lo])
		{
			lo -= 1;
		}
		while (hi + 1 < n && a[hi + 1] == a[hi])
		{
			hi += 1;
		}

		writeln (c (hi + 1 - lo, k - lo));
	}
}

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

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

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

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

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

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

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

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

enum P = 10L^^9 + 7;

void main()
{
    int T; get(T);
    while (T--) {
        int N, K; get(N, K);
        int[] aa; get(aa);
        auto MAX = new int[](K + 1);
        auto DP = new long[](K + 1);
        DP[0] = 1;
        foreach (a; aa) {
            foreach_reverse (i; 0..K) {
                if (MAX[i] + a > MAX[i+1]) {
                    MAX[i+1] = MAX[i] + a;
                    DP[i+1] = DP[i];
                } else if (MAX[i] + a == MAX[i+1]) {
                    (DP[i+1] += DP[i]) %= P;
                }
            }
        }
        writeln(DP[K]);
    }
}

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

immutable int mod = 10 ^^ 9 + 7;

int powMod (int a, int p)
{
	int res = 1;
	for ( ; p > 0; p >>= 1)
	{
		if (p & 1)
		{
			res = (res * 1L * a) % mod;
		}
		a = (a * 1L * a) % mod;
	}
	return res;
}

alias inv = a => powMod (a, mod - 2);

int fact (int n)
{
	int res = 1;
	for (int i = 1; i <= n; i++)
	{
		res = (res * 1L * i) % mod;
	}
	return res;
}

int c (int n, int k)
{
	return fact (n) * 1L * inv (fact (n - k)) % mod * 1L *
	    inv (fact (k)) % mod;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort !(q{a > b}) (a);

		int lo = k - 1;
		int hi = k;
		if (a[lo] != a[hi])
		{
			writeln (1);
			continue;
		}

		while (lo > 0 && a[lo - 1] == a[lo])
		{
			lo -= 1;
		}
		while (hi + 1 < n && a[hi + 1] == a[hi])
		{
			hi += 1;
		}

		writeln (c (hi - lo, k - lo));
	}
}


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

void main ()
{
	auto tests = readln.strip.to !(int);
multitest_loop:
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip;
		auto t = readln.strip;
		if (n.iota.any !(i => s[i] > t[i]))
		{
			writeln (-1);
			continue multitest_loop;
		}
		auto r = s.dup;
		int res = 0;
		auto b = new bool [n];
		foreach (c; 'a'..'u')
		{
			foreach (i; 0..n)
			{
				b[i] = (r[i] == c && r[i] < t[i]);
			}
			if (any (b))
			{
				auto d = n.iota.filter !(i => b[i])
				    .map !(i => t[i]).minElement;
				foreach (i; 0..n)
				{
					if (r[i] == c)
					{
						r[i] = d;
					}
				}
				res += 1;
			}
		}
		writeln (res);
	}
}

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

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

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

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

enum V = 20;

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const A = readToken();
        const B = readToken();

        bool ok = true;
        foreach (i; 0 .. N) {
          ok = ok && (A[i] <= B[i]);
        }
        if (ok) {
          auto needs = new int[V];
          foreach (i; 0 .. N) {
            needs[A[i] - 'a'] |= 1 << (B[i] - 'a');
          }
          int ans;
          foreach (u; 0 .. V) {
            needs[u] &= ~(1 << u);
            if (needs[u]) {
              const v = bsf(needs[u]);
              needs[v] |= needs[u];
              ++ans;
            }
          }
          writeln(ans);
        } else {
          writeln(-1);
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

struct UnionFind(T)
{
	void init(T n) { par = new T[](n); foreach (i; 0..n) par[i] = i; cnt = new T[](n); fill(cnt, 1); }
	T root(T i) { return par[i] == i ? i : (par[i] = root(par[i])); }
	bool same(T i, T j) { return root(i) == root(j); }
	void unite(T i, T j) { i = root(i); j = root(j); if (i == j) return; par[i] = j; cnt[j] += cnt[i]; }
	T size(T i) { return cnt[root(i)]; }
	T[] par, cnt;
}

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto A = RD!string;
		auto B = RD!string;

		UnionFind!int uf;
		uf.init(20);
		bool ok = true;
		foreach (i; 0..n)
		{
			auto a = A[i] - 'a';
			auto b = B[i] - 'a';
			if (a > b)
			{
				ok = false;
				break;
			}
			else if (a == b) continue;
			uf.unite(a, b);
		}
		if (!ok)
		{
			ans[ti] = -1;
			continue;
		}
		debug writeln(uf.par);
		debug writeln(uf.cnt);

		auto root = new bool[](20);
		foreach (i; 0..20)
		{
			auto r = uf.root(i);
			root[r] = true;
		}
		foreach (i; 0..20)
		{
			if (root[i])
			{
				ans[ti] += uf.size(i) - 1;
			}
		}
	}

	foreach (e; ans)
	{
		writeln(e);
	}
	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;

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

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

        auto vals = new RedBlackTree!int[] (25);
        foreach (i; (25).iota) { vals[i] = redBlackTree!int(); }

        foreach (ca, cb; lockstep(a, b)) {
            if (ca > cb) {
                writeln(-1);
                continue test;
            }

            if (ca == cb) { continue; }

            vals[ca - 'a'].insert(cb - 'a');
        }

        auto trans = new bool[][] (25, 25);
        foreach (i; (25).iota) { trans[i][] = false; }

        int ans = 0;

        foreach (let; (25).iota) {
            if (vals[let].empty()) { continue; }

            ans += 1;
            int nxt = vals[let].front;
            vals[let].removeFront();

            foreach (el; vals[let]) { vals[nxt].insert(el); }
        }

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

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

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

        auto vals = new RedBlackTree!int[] (25);
        foreach (i; (25).iota) { vals[i] = redBlackTree!int(); }

        foreach (ca, cb; lockstep(a, b)) {
            if (ca > cb) {
                writeln(-1);
                continue test;
            }

            if (ca == cb) { continue; }

            vals[ca - 'a'].insert(cb - 'a');
        }

        auto trans = new bool[][] (25, 25);
        foreach (i; (25).iota) { trans[i][] = false; }

        foreach (let; (25).iota) {
            if (vals[let].empty()) { continue; }

            auto arr = [let].chain(vals[let][]);

            foreach (prev, nxt; lockstep(arr, arr.dropOne())) { trans[prev][nxt] = true; }
        }

        int ans = 0;

        foreach (i; (25).iota) { ans += trans[i].count!(x => x); }

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

enum V = 20;

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const A = readToken();
        const B = readToken();

        bool ok = true;
        foreach (i; 0 .. N) {
          ok = ok && (A[i] <= B[i]);
        }
        if (ok) {
          auto needs = new int[V];
          foreach (i; 0 .. N) {
            needs[A[i] - 'a'] |= 1 << (B[i] - 'a');
          }
          int ans;
          foreach (u; 0 .. V) {
            needs[u] &= ~(1 << u);
            if (needs[u]) {
              const v = bsf(u);
              needs[v] |= needs[u];
              ++ans;
            }
          }
          writeln(ans);
        } else {
          writeln(-1);
        }
      }
    }
  } catch (EOFException e) {
  }
}