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);
		long cur = 0;
		long res = 0;
		foreach_reverse (i; 0..n - 1)
		{
			cur += (a[i + 1] - a[i]) * (n - i - 1L);
			res += cur;
		}
		writeln (a.back - res);
	}
}

// Vicfred
// https://codeforces.com/contest/1541/problem/C
//
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int t = readln.chomp.to!int;

while(t--) {
    int n = readln.chomp.to!int;
    long[] d = readln.split.map!(to!long).array;
    d.sort;
    long ans = d[n - 1];
    long node = 0L;
    for(int i = 0; i < n; ++i) {
        ans -= d[i] * i - node;
        node += d[i];
    }
    ans.writeln;
}
}

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

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

  while (t--) {
    int n;
    read(n);
    auto arr = list!long;

    long answer = 0;
    long current = 0;

    sort(arr);
    foreach (i; 1 .. n) {
      auto w = arr[i] - arr[i - 1];
      answer += w;
      answer -= i * w + current;
      current += i * w;
    }

    writeln(answer);
  }
}

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

void theCode(){
    int n = scan!int;
    auto arr = scanArray;
    arr.sort;
    ll[] pref = [0];
    for(int i = 1; i < n; ++i){
        pref ~= pref.back + arr[i];
    }
    ll cost = 0;
    for(int i = 1; i < n; ++i){
        cost += (i - 1) * 1L * arr[i];
        if(i > 1) cost -= pref[i-2];
    }
    writeln(- cost);
}

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.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);
		long cur = 0;
		long res = 0;
		foreach_reverse (i; 0..n - 1)
		{
			cur += (a[i + 1] - a[i]) * (n - i - 1);
			res += cur;
		}
		writeln (a.back - res);
	}
}


import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;
import std.math;

alias Tree = RBT!int;
alias ll = long;

ll[1000] nn;

void main() {
  GC.disable();

  int q;
  readf(" %s", q);

  foreach(i;0 ..q) {
    ll n;
    readf(" %s", n);
    ll c5=0;
    ll c3=0;
    ll c2=0;
    while(n % 5==0) {c5++; n /=5;}
    while(n % 3==0) {c3++; n /=3;}
    while(n % 2==0) {c2++; n /=2;}

    if (n != 1) writeln(-1);
    else writeln(c5 + c3 + 2*c5 + c3 + c2);
  }

}

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;
//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 main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (i; 0..q)
	{
		auto n = RD;
		long cnt;
		while (n != 1)
		{
			if (n % 2 == 0)
			{
				n /= 2;
			}
			else if ((n * 2) % 3 == 0)
			{
				n = (n * 2) / 3;
			}
			else if ((n * 4) % 5 == 0)
			{
				n = (n * 4) /5;
			}
			else
			{
				cnt = -1;
				break;
			}
			++cnt;
		}
		ans[i] = cnt;
	}

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

import std.stdio;

void main() {
  int nt;
  readf!" %d" (nt);
  while (--nt >= 0) {
    long x;
    int res;
    readf!" %d" (x);
    while (x > 1) {
      if (!(x % 2)) {
        x /= 2;
        ++res;
      } else if (!(x % 3)) {
        x /= 3;
        res += 2;
      } else if (!(x % 5)) {
        x /= 5;
        res += 3;
      } else {
        res = -1;
        break;
      }
    }
    writeln (res);
  }
}


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 long[][](t, 2);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto c = RD;

		if (a < c)
			ans[ti][0] = 1;
		else
			ans[ti][0] = -1;

		if (a*b > c)
			ans[ti][1] = b;
		else
			ans[ti][1] = -1;
	}

	foreach (e; ans)
	{
		writeln(e[0], " ", e[1]);
	}
	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)
	{
		long a, b, c;
		readf !(" %s %s %s") (a, b, c);
		auto res1 = (a < c) ? 1 : -1;
		auto res2 = (c < a * b) ? b : -1;
		writeln (res1, " ", res2);
	}
}


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

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

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

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

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

bool isPrime(long n) {
	if (n < 2) {
		return false;
	}
	for (long d = 2; d * d <= n; ++d) {
		if (n % d == 0) {
			return false;
		}
	}
	return true;
}

long[] gs;

bool isPrimitive(long p, long g) {
	gs = new long[0];
	gs ~= 1;
	foreach (i; 1 .. p - 1) {
		gs ~= (gs[$ - 1] * g) % p;
	}
	foreach (i; 1 .. p - 1) {
		if (gs[cast(size_t)(i)] == 1) {
			return false;
		}
	}
	return true;
}

long N;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readLong;

		if (N == 1) {
			writeln("YES");
			writeln(1);
		} else if (N == 2) {
			writeln("YES");
			writeln(1);
			writeln(2);
		} else if (N == 4) {
			writeln("YES");
			writeln(1);
			writeln(3);
			writeln(2);
			writeln(4);
		} else if (isPrime(N)) {
			for (long g = 2; ; ++g) {
				if (isPrimitive(N, g)) {
debug{
writeln("gs = ",gs);
}
					writeln("YES");
					writeln(1);
					foreach (i; 0 .. (N - 3) / 2) {
debug{
// writeln("g^",1+2*i);
// writeln("g^",N-3-2*i);
}
						writeln(gs[cast(size_t)(1 + 2 * i)]);
						writeln(gs[cast(size_t)(N - 3 - 2 * i)]);
					}
debug{
// writeln("g^",N-2);
}
					writeln(gs[cast(size_t)(N - 2)]);
					writeln(N);
					break;
				}
			}
		} else {
			writeln("NO");
		}
	}
	} catch (EOFException) {}
}

/* submitted, so what? */
import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import core.bitop;

long powmod (int a, int b, int c)
{
	long cur = a % c;
	long res = 1 % c;
	while (b)
	{
		if (b & 1)
		{
			res = (res * cur) % c;
		}
		cur = (cur * cur) % c;
		b >>= 1;
	}
	return res;
}

void main ()
{
	int n;
main_loop:
	while (readf (" %s", &n) > 0)
	{
		if (n == 4)
		{
			write ("YES\n1\n3\n2\n4\n");
			continue main_loop;
		}

		for (int i = 2; i * i <= n; i++)
		{
			if (n % i == 0)
			{
				writeln ("NO");
				continue main_loop;
			}
		}

		writeln ("YES");
		if (n > 1)
		{
			writeln (1);
		}
		foreach (i; 2..n)
		{
			writeln ((i * powmod (i - 1, n - 2, n)) % n);
		}
		writeln (n);
	}
}


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

void main ()
{
	int n, m, p;
	while (readf (" %s %s %s", &n, &m, &p) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		auto b = new int [m];
		foreach (j; 0..m)
		{
			readf (" %s", &b[j]);
		}

		int [] ans;
		if ((m - 1) * cast (long) p < n)
		{
			foreach (k; 0..p)
			{
				int [int] e;
				int d = m;
				foreach (j; 0..m)
				{
					e[b[j]]++;
				}

				for (int i = k, j = i - p * m; i < n;
				     i += p, j += p)
				{
					e[a[i]]--;
					int cur = e[a[i]];
					if (cur >= 0)
					{
						d--;
					}
					else
					{
						d++;
					}

					if (j >= 0)
					{
						e[a[j]]++;
						int prev = e[a[j]];
						if (prev <= 0)
						{
							d--;
						}
						else
						{
							d++;
						}
					}

					debug {writeln (k, " ", i, " ",
					                j, " ", d);}
					if (d == 0)
					{
						ans ~= j + p + 1;
					}
				}
			}
		}

		ans.sort !("a < b", SwapStrategy.stable);
		writefln ("%s\n%(%s %)", ans.length, ans);
	}
}

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

void solve(int[] a, int[] b, int n, int m, int p)
{
    int[int] cntb;
    foreach (v; b)
    {
        if (v !in cntb) cntb[v] = 1;
        else ++ cntb[v];
    }
    int[] res;
    foreach (i; 0 .. min(n, p))
    {
        auto d = m;
        int[int] cnta;
        int j;
        for (j = i; j < n && (j - i) / p < m; j += p)
        {
            if (a[j] !in cnta) cnta[a[j]] = 1;
            else ++ cnta[a[j]];
            if (a[j] !in cntb)
            {
                ++ d;
            }
            else
            {
                if (cnta[a[j]] <= cntb[a[j]]) -- d;
                else ++ d;
            }
        }
        if ((j - i) / p < m) continue;
        if (d == 0) res ~= i;
        for (int left = i, right = j; right < n; left += p, right += p)
        {
            if (a[left] != a[right])
            {
                -- cnta[a[left]];
                if (a[left] !in cntb)
                {
                    -- d;
                }
                else
                {
                    if (cnta[a[left]] < cntb[a[left]]) ++ d;
                    else -- d;
                }
                ++ cnta[a[right]];
                if (a[right] !in cntb)
                {
                    ++ d;
                }
                else
                {
                    if (cnta[a[right]] <= cntb[a[right]]) -- d;
                    else ++ d;
                }
            }
            if (d == 0) res ~= left + p;
        }
    }
    writeln(res.length);
    if (res.length > 0)
    {
        res.sort();
        foreach (v; res) write(v + 1, " ");
        writeln();
    }
}

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

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

void solve(int[] a, int[] b, int n, int m, int p)
{
    int[int] cntb;
    foreach (v; b)
    {
        if (v !in cntb) cntb[v] = 1;
        else ++ cntb[v];
    }
    int[] res;
    foreach (i; 0 .. min(n, p))
    {
        auto d = m;
        int[int] cnta;
        int j;
        for (j = i; j < n && (j - i) / p < m; j += p)
        {
            if (a[j] !in cnta) cnta[a[j]] = 1;
            else ++ cnta[a[j]];
            if (a[j] !in cntb)
            {
                ++ d;
            }
            else
            {
                if (cnta[a[j]] <= cntb[a[j]]) -- d;
                else ++ d;
            }
        }
        if ((j - i) / p < m) continue;
        if (d == 0) res ~= i;
        for (int left = i, right = j; right < n; left += p, right += p)
        {
            if (a[left] != a[right])
            {
                -- cnta[a[left]];
                if (a[left] !in cntb)
                {
                    -- d;
                }
                else
                {
                    if (cnta[a[left]] < cntb[a[left]]) ++ d;
                    else -- d;
                }
                ++ cnta[a[right]];
                if (a[right] !in cntb)
                {
                    ++ d;
                }
                else
                {
                    if (cnta[a[right]] <= cntb[a[right]]) -- d;
                    else ++ d;
                }
            }
            if (d == 0) res ~= left + p;
        }
    }
    writeln(res.length);
    if (res.length > 0)
    {
        foreach (v; res) write(v + 1, " ");
        writeln();
    }
}

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


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;

int[3][6] perm =
[
  [0, 1, 2],
  [0, 2, 1],
  [1, 0, 2],
  [1, 2, 0],
  [2, 0, 1],
  [2, 1, 0],
];

void main()
{
    int n, m;
    readf!" %d %d "(n, m);
    auto s = readln.strip;
    int[][6] pf = [[0], [0], [0], [0], [0], [0]];
    int[6] sum;
    foreach (i ; 0 .. n) {
      int x = s[i] - 'a';
      foreach (j ; 0 .. 6) {
        sum[j] += (x != perm[j][i % 3]);
        pf[j] ~= sum[j];
      }
    }
    while (m--) {
      int l, r;
      readf!" %d %d "(l, r);
      int ans = int.max;
      foreach (j ; 0 .. 6) {
        ans = min(ans, pf[j][r] - pf[j][l - 1]);
      }
      writeln(ans);
    }
}

import std;

void main () {
    immutable q = readln.chomp.splitter(' ').dropOne.front.to!uint;
    immutable s = readln.chomp;

    auto costs = (){
        scope result = appender!(uint[]);
        result.reserve(6 * (s.length + 1));

        [
            "abc",
            "acb",
            "bac",
            "bca",
            "cab",
            "cba"
        ].map!(patt => patt.makePrefix(s))
            .each!(v => v.each!(a => result.put(a)));

        assert(result[].length == 6 * (s.length + 1));
        return result[].assumeUnique.chunks(s.length + 1);
    }();

    stdin
        .byLine
        .map!((char[] line) {
                uint[2] query = line
                    .splitter(' ')
                    .map!(to!uint)
                    .staticArray!2;

                return tuple(query[0], query[1]);
        })
        .map!(query =>
              costs
                .map!(v => v[query[1]] - v[query[0] - 1])
                .minElement
        )
        .each!writeln;
}

auto makePrefix (in string patt, in string s) {
    return chain(
        [0u],
        zip(s.byCodeUnit, patt.byCodeUnit.cycle)
            .cumulativeFold!"a + (b[0] != b[1])"(0u)
    );
}
// ""

import std;

void main () {
    immutable q = readln.chomp.splitter(' ').dropOne.front.to!uint;
    immutable s = readln.chomp;

    auto costs = (){
        scope result = appender!(uint[]);
        [
            "abc",
            "acb",
            "bac",
            "bca",
            "cab",
            "cba"
        ].map!(patt => patt.makePrefix(s))
            .each!(v => v.each!(a => result.put(a)));

        assert(result[].length == 6 * (s.length + 1));
        return result[].assumeUnique.chunks(s.length + 1);
    }();

    stdin
        .byLine
        .map!((char[] line) {
                uint[2] query = line
                    .splitter(' ')
                    .map!(to!uint)
                    .staticArray!2;

                return tuple(query[0], query[1]);
        })
        .map!(query =>
              costs
                .map!(v => v[query[1]] - v[query[0] - 1])
                .minElement
        )
        .each!writeln;
}

auto makePrefix (in string patt, in string s) {
    return chain(
        [0u],
        zip(s.byCodeUnit, patt.byCodeUnit.cycle)
            .cumulativeFold!"a + (b[0] != b[1])"(0u)
    );
}
// ""

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

auto sum(R)(R r, size_t i, size_t j)
{
	if (i > j) return 0;
	if (i == 0) return r[j];
	return r[j] - r[i-1];
}

void main()
{
	int n = readInt!int;
	int m = readInt!int;
	auto s = readString.map!(c => cast(int)c - 'a').array;
	int[][] perm = new int[][](6, 3);
	int[] currp = [0, 1, 2];
	{
	size_t i = 0;
	do
	{
		perm[i++][] = currp;
	} while (nextPermutation(currp));
	}
	int[][] dist = new int[][](6, n);
	foreach(p; 0 .. 6)
	{
		foreach(i; 0 .. n)
		{
			dist[p][i] = s[i] != perm[p][i%3];
		}
	}
	auto prefSum = new int[][](6);
	foreach(p; 0 .. 6)
	{
		prefSum[p] = dist[p].cumulativeFold!((a, b)=>a + b).array;
	}
	foreach(i; 0 .. m)
	{
		auto l = readInt!int - 1;
		auto r = readInt!int - 1;
		iota(0, 6).map!(p => sum(prefSum[p], l, r)).fold!min.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.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;

immutable long MOD = 10^^6 + 3;

long powmod(long a, long x, long m) {
    long ret = 1;
    while (x) {
        if (x % 2) ret = ret * a % m;
        a = a * a % m;
        x /= 2;
    }
    return ret;
}

int gaussianElimination(ref long[][] org_mat, ref long[] ret) {
    int N = org_mat.length.to!int;

    auto mat = new long[][](N, N+1);
    foreach (i; 0..N)
        foreach (j; 0..N+1)
            mat[i][j] = org_mat[i][j];

    foreach (i; 0..N) {
        long maxval = 0;
        int maxrow = -1;
        foreach (j; i..N)
            if (abs(mat[j][i]) > maxval)
                maxval = abs(mat[j][i]), maxrow = j;
        if (maxval == 0)
            return -1;
        swap(mat[i], mat[maxrow]);

        foreach (j; i+1..N+1)
            mat[i][j] = mat[i][j] * powmod(mat[i][i], MOD-2, MOD) % MOD;
        mat[i][i] = 1;

        foreach (j; 0..N) {
            if (j == i) continue;
            long mul = mat[j][i];
            foreach (k; i..N+1) {
                (mat[j][k] -= mul * mat[i][k] % MOD) %= MOD;
                mat[j][k] = (mat[j][k] + MOD) % MOD;
            }
        }
    }

    foreach (i; 0..N)
        ret[i] = mat[i][N];

    return 0;
}

long[] B;

long ask(long x) {
    writeln("? ", x);
    debug {
        long res = 0;
        foreach (i; 0..11) (res += B[i] * powmod(x, i, MOD) % MOD) %= MOD;
        return res;
    }
    stdout.flush;
    return readln.chomp.to!long;
}

void ans(long x) {
    writeln("! ", x);
    return;
}

void main() {
    debug {
        B = new long[](11);
        B[0] = 1000002;
        B[2] = 1;
    }

    int N = 11;
    auto mat = new long[][](N, N+1);

    foreach (i; 0..N) {
        foreach (j; 0..N) mat[i][j] = powmod(i, j, MOD);
        mat[i][N] = ask(i);
    }

    auto A = new long[](N);
    gaussianElimination(mat, A);

    foreach (i; 0..MOD) {
        long res = 0;
        foreach (j; 0..N) (res += A[j] * powmod(i, j, MOD) % MOD) %= MOD;
        if (res == 0) {
            ans(i);
            return;
        }
    }

    ans(-1);
}

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

T gcd(T) (T a, T b) pure nothrow @nogc {
  if (a < b) {
    swap (a, b);
  }
  while (b) {
    T c = a % b; a = b; b = c;
  }
  return a;
}

T gcdext(T) (T a, T b, ref T x, ref T y) pure nothrow @nogc {
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  }
  T res = gcdext (b, a % b, y, x);
  y -= x * (a / b);
  return res;
}

struct IntM {
  enum q = 1_000_003;
  int v;
  this (int m) pure nothrow @nogc {
    v = m % q;
    if (v < 0) {
      v += q;
    }
  }
  IntM opAssign (int m) pure nothrow @nogc {
    v = m % q;
    if (v < 0) {
      v += q;
    }
    return this;
  }
  IntM opUnary (string op : "-")() const pure nothrow @nogc {
    return IntM ((q - v) % q);
  }
  ref IntM opUnary (string op : "++")() pure nothrow @nogc {
    if (++v >= q) {
      v -= q;
    }
    return this;
  }
  ref IntM opUnary (string op : "--")() pure nothrow @nogc {
    if (--v < 0) {
      v += q;
    }
    return this;
  }
  ref IntM opOpAssign (string op : "+")(in IntM rhs) pure nothrow @nogc {
    v += rhs.v;
    v %= q;
    return this;
  }
  ref IntM opOpAssign (string op : "-")(in IntM rhs) pure nothrow @nogc {
    v -= rhs.v;
    v %= q;
    return this;
  }
  ref IntM opOpAssign (string op : "*")(in IntM rhs) pure nothrow @nogc {
    v = ((v.to!(long)) * rhs.v.to!(long)) % q;
    return this;
  }
  IntM opBinary (string op : "+")(in IntM rhs) const pure nothrow @nogc {
    return IntM ( (v + rhs.v) % q);
  }
  IntM opBinary (string op : "-")(in IntM rhs) const pure nothrow @nogc {
    return IntM ( (v - rhs.v) % q);
  }
  IntM opBinary (string op : "*")(in IntM rhs) const pure nothrow @nogc {
    return IntM (((v.to!(long)) * rhs.v.to!(long)) % q);
  }
  IntM opBinary (string op : "^^")(in int rhs) const pure nothrow @nogc {
    IntM a = 1, b = this;
    int p = rhs;
    while (p > 0) {
      //a * (b ^ p) == x ^ rhs
      if (p & 1) {
        a *= b;
      }
      b *= b;
      p >>>= 1;
    }
    return a;
  }
  IntM opBinary (string op)(in int v) const pure nothrow @nogc if (op == "+" || op == "-" || op == "*") {
    mixin ("return this " ~ op ~ " IntM(v);");
  }
  int opCast(T : int)() const pure nothrow @nogc { return v; }
  int opCmp (const IntM rhs) const pure nothrow @nogc {
    if (v < rhs.v) {
      return -1;
    }
    if (v > rhs.v) {
      return 1;
    }
    return 0;
  }
  bool opEquals (const IntM rhs) const pure nothrow @nogc { return v == rhs.v; }
  string toString() const pure nothrow { return ((v < 0) ? v + q : v).text; }
}

void main() {
  IntM[][] a = new IntM[][] (11, 11);
  IntM[11] b;
  foreach (i; 0 .. 11) {
    IntM ii = i;
    writeln ("? ", i); stdout.flush ();
    a[i][0] = 1;
    foreach (j; 1 .. 11) {
      a[i][j] = a[i][j-1] * ii;
    }
    int bi = readln.strip.to!int;
    b[i] = bi;
  }
  immutable IntM z = 0;
  foreach (i; 0 .. 11) {
    enforce (a[i][i] != z);
    foreach (j; i + 1 .. 11) {
      IntM aji = a[j][i];
      foreach (k; i .. 11) {
        a[j][k] *= a[i][i];
        a[j][k] -= a[i][k] * aji;
      }
      b[j] *= a[i][i];
      b[j] -= b[i] * aji;
    }
  }
  IntM[11] x;
  foreach_reverse (i; 0 .. 11) {
    x[i] = b[i];
    foreach (j; i + 1 .. 11) {
      x[i] -= a[i][j] * x[j];
    }
    x[i] *= a[i][i] ^^ (IntM.q - 2);
  }
  debug stderr.writeln (a);
  debug stderr.writeln (b);
  debug stderr.writeln (x);
  foreach (i; 0 .. IntM.q) {
    IntM r;
    IntM ii = i;
    foreach_reverse (j; 0 .. 11) {
      r *= ii;
      r += x[j];
    }
    if (r == z) {
      writeln ("! ", i);
      return;
    }
  }
  writeln ("! ", -1);
}

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;

immutable long MOD = 10^^6 + 3;

long powmod(long a, long x, long m) {
    long ret = 1;
    while (x) {
        if (x % 2) ret = ret * a % m;
        a = a * a % m;
        x /= 2;
    }
    return ret;
}

int gaussianElimination(ref long[][] org_mat, ref long[] ret) {
    int N = org_mat.length.to!int;

    auto mat = new long[][](N, N+1);
    foreach (i; 0..N)
        foreach (j; 0..N+1)
            mat[i][j] = org_mat[i][j];

    foreach (i; 0..N) {
        long maxval = 0;
        int maxrow = -1;
        foreach (j; i..N)
            if (abs(mat[j][i]) > maxval)
                maxval = abs(mat[j][i]), maxrow = j;
        if (maxval == 0)
            return -1;
        swap(mat[i], mat[maxrow]);

        foreach (j; i+1..N+1)
            mat[i][j] = mat[i][j] * powmod(mat[i][i], MOD-2, MOD) % MOD;
        mat[i][i] = 1;

        foreach (j; 0..N) {
            if (j == i) continue;
            long mul = mat[j][i];
            foreach (k; i..N+1) {
                (mat[j][k] -= mul * mat[i][k] % MOD) %= MOD;
                mat[j][k] = (mat[j][k] + MOD) % MOD;
            }
        }
    }

    foreach (i; 0..N)
        ret[i] = mat[i][N];

    return 0;
}

long[] B;

long ask(long x) {
    writeln("? ", x);
    debug {
        long res = 0;
        foreach (i; 0..10) (res += B[i] * powmod(x, i, MOD) % MOD) %= MOD;
        return res;
    }
    stdout.flush;
    return readln.chomp.to!long;
}

void ans(long x) {
    writeln("! ", x);
    return;
}

void main() {
    debug {
        B = new long[](10);
        B[0] = 1000002;
        B[2] = 1;
    }

    int N = 10;
    auto mat = new long[][](N, N+1);

    foreach (i; 0..10) {
        foreach (j; 0..N) mat[i][j] = powmod(i, j, MOD);
        mat[i][N] = ask(i);
    }

    auto A = new long[](N);
    gaussianElimination(mat, A);

    foreach (i; 0..MOD) {
        long res = 0;
        foreach (j; 0..10) (res += A[j] * powmod(i, j, MOD) % MOD) %= MOD;
        if (res == 0) {
            ans(i);
            return;
        }
    }

    ans(-1);
}

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;

immutable long MOD = 10^^6 + 3;

long powmod(long a, long x, long m) {
    long ret = 1;
    while (x) {
        if (x % 2) ret = ret * a % m;
        a = a * a % m;
        x /= 2;
    }
    return ret;
}

int gaussianElimination(ref long[][] org_mat, ref long[] ret) {
    int N = org_mat.length.to!int;

    auto mat = new long[][](N, N+1);
    foreach (i; 0..N)
        foreach (j; 0..N+1)
            mat[i][j] = org_mat[i][j];

    foreach (i; 0..N) {
        long maxval = 0;
        int maxrow = -1;
        foreach (j; i..N)
            if (abs(mat[j][i]) > maxval)
                maxval = abs(mat[j][i]), maxrow = j;
        if (maxval == 0)
            return -1;
        swap(mat[i], mat[maxrow]);

        foreach (j; i+1..N+1)
            mat[i][j] = mat[i][j] * powmod(mat[i][i], MOD-2, MOD);
        mat[i][i] = 1;

        foreach (j; 0..N) {
            if (j == i) continue;
            long mul = mat[j][i];
            foreach (k; i..N+1) {
                (mat[j][k] -= mul * mat[i][k] % MOD) %= MOD;
                mat[j][k] = (mat[j][k] + MOD) % MOD;
            }
        }
    }

    foreach (i; 0..N)
        ret[i] = mat[i][N];

    return 0;
}

long[] B;

long ask(long x) {
    writeln("? ", x);
    debug {
        long res = 0;
        foreach (i; 0..10) (res += B[i] * powmod(x, i, MOD) % MOD) %= MOD;
        return res;
    }
    stdout.flush;
    return readln.chomp.to!long;
}

void ans(long x) {
    writeln("! ", x);
    return;
}

void main() {
    debug {
        B = new long[](10);
        B[0] = 1000002;
        B[2] = 1;
    }

    int N = 10;
    auto mat = new long[][](N, N+1);

    foreach (i; 0..10) {
        foreach (j; 0..N) mat[i][j] = powmod(i, j, MOD);
        mat[i][N] = ask(i);
    }

    auto A = new long[](N);
    gaussianElimination(mat, A);

    foreach (i; 0..MOD) {
        long res = 0;
        foreach (j; 0..10) (res += A[j] * powmod(i, j, MOD) % MOD) %= MOD;
        if (res == 0) {
            ans(i);
            return;
        }
    }

    ans(-1);
}

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

T gcd(T) (T a, T b) pure nothrow @nogc {
  if (a < b) {
    swap (a, b);
  }
  while (b) {
    T c = a % b; a = b; b = c;
  }
  return a;
}

T gcdext(T) (T a, T b, ref T x, ref T y) pure nothrow @nogc {
  if (b == 0) {
    x = 1;
    y = 0;
    return a;
  }
  T res = gcdext (b, a % b, y, x);
  y -= x * (a / b);
  return res;
}

struct IntM {
  enum q = 1_000_003;
  int v;
  this (int m) pure nothrow @nogc {
    v = m % q;
    if (v < 0) {
      v += q;
    }
  }
  IntM opAssign (int m) pure nothrow @nogc {
    v = m % q;
    if (v < 0) {
      v += q;
    }
    return this;
  }
  IntM opUnary (string op : "-")() const pure nothrow @nogc {
    return IntM ((q - v) % q);
  }
  ref IntM opUnary (string op : "++")() pure nothrow @nogc {
    if (++v >= q) {
      v -= q;
    }
    return this;
  }
  ref IntM opUnary (string op : "--")() pure nothrow @nogc {
    if (--v < 0) {
      v += q;
    }
    return this;
  }
  ref IntM opOpAssign (string op : "+")(in IntM rhs) pure nothrow @nogc {
    v += rhs.v;
    v %= q;
    return this;
  }
  ref IntM opOpAssign (string op : "-")(in IntM rhs) pure nothrow @nogc {
    v -= rhs.v;
    v %= q;
    return this;
  }
  ref IntM opOpAssign (string op : "*")(in IntM rhs) pure nothrow @nogc {
    v = ((v.to!(long)) * rhs.v.to!(long)) % q;
    return this;
  }
  IntM opBinary (string op : "+")(in IntM rhs) const pure nothrow @nogc {
    return IntM ( (v + rhs.v) % q);
  }
  IntM opBinary (string op : "-")(in IntM rhs) const pure nothrow @nogc {
    return IntM ( (v - rhs.v) % q);
  }
  IntM opBinary (string op : "*")(in IntM rhs) const pure nothrow @nogc {
    return IntM (((v.to!(long)) * rhs.v.to!(long)) % q);
  }
  IntM opBinary (string op : "^^")(in int rhs) const pure nothrow @nogc {
    IntM a = 1, b = this;
    int p = rhs;
    while (p > 0) {
      //a * (b ^ p) == x ^ rhs
      if (p & 1) {
        a *= b;
      }
      b *= b;
      p >>>= 1;
    }
    return a;
  }
  IntM opBinary (string op)(in int v) const pure nothrow @nogc if (op == "+" || op == "-" || op == "*") {
    mixin ("return this " ~ op ~ " IntM(v);");
  }
  int opCast(T : int)() const pure nothrow @nogc { return v; }
  int opCmp (const IntM rhs) const pure nothrow @nogc {
    if (v < rhs.v) {
      return -1;
    }
    if (v > rhs.v) {
      return 1;
    }
    return 0;
  }
  bool opEquals (const IntM rhs) const pure nothrow @nogc { return v == rhs.v; }
  string toString() const pure nothrow { return ((v < 0) ? v + q : v).text; }
}

void main() {
  IntM[][] a = new IntM[][] (11, 11);
  IntM[11] b;
  foreach (i; 0 .. 11) {
    IntM ii = i;
    writeln ("? ", i); stdout.flush ();
    a[i][0] = 1;
    foreach (j; 1 .. 11) {
      a[i][j] = a[i][j-1] * ii;
    }
    int bi = readln.strip.to!int;
    b[i] = bi;
  }
  immutable IntM z = 0;
  foreach (i; 0 .. 11) {
    enforce (a[i][i] != z);
    foreach (j; i + 1 .. 11) {
      IntM aji = a[j][i];
      foreach (k; j .. 11) {
        a[j][k] *= a[i][i];
        a[j][k] -= a[i][k] * aji;
      }
      b[j] *= a[i][i];
      b[j] -= b[i] * aji;
    }
  }
  IntM[11] x;
  foreach_reverse (i; 0 .. 11) {
    x[i] = b[i];
    foreach (j; i + 1 .. 11) {
      x[i] -= a[i][j] * x[j];
    }
    x[i] *= a[i][i] ^^ (IntM.q - 2);
  }
  foreach (i; 0 .. IntM.q) {
    IntM r;
    IntM ii = i;
    foreach_reverse (j; 0 .. 11) {
      r *= ii;
      r += x[j];
    }
    if (r == z) {
      writeln ("! ", i);
      return;
    }
  }
  writeln ("! ", -1);
}


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) {
        int N = readInt;
        int M = readInt;
        auto A = new int[M];
        auto B = new int[M];
        foreach (i; 0 .. M) {
          A[i] = readInt;
          B[i] = readInt;
        }
        M += 2 * N;
        foreach (u; 1 .. N + 1) {
          A ~= 0;
          B ~= u;
          A ~= u;
          B ~= N + 1;
        }

        auto G = new int[][N + 2];
        auto H = new int[][N + 2];
        foreach (i; 0 .. M) {
          G[A[i]] ~= i;
          H[B[i]] ~= i;
        }

        auto fs = new int[N + 1];
        foreach (i; 0 .. M) {
          if (A[i] + 1 == B[i]) {
            fs[A[i]] = 1;
          }
        }
        auto fsSum = new int[N + 2];
        foreach (u; 0 .. N + 1) {
          fsSum[u + 1] = fsSum[u] + fs[u];
        }

        long ans;
        if (fsSum[N + 1] == N + 1) {
          ans = 1L * N * (N - 1) / 2;
        } else {
          int l = N + 1, r = 0;
          foreach (u; 0 .. N + 1) {
            if (!fs[u]) {
              chmin(l, u);
              chmax(r, u + 1);
            }
          }
          debug {
            writeln("fs = ", fs);
            writeln("l = ", l, ", r = ", r);
          }
          bool isGood(int u, int v) {
            return (u <= v && fsSum[v] - fsSum[u] == v - u);
          }

          // (u, u + 1) to (l, l + 1),  parity of # of steps
          auto visL = new bool[2][N + 1];
          visL[l][0] = true;
          foreach_reverse (u; 0 .. l + 1) {
            foreach (i; H[u + 1]) {
              // v -> u + 1,  v + 1 -> u
              const v = A[i];
              if (isGood(v + 1, u)) {
                if (visL[u][0]) visL[v][1] = true;
                if (visL[u][1]) visL[v][0] = true;
              }
            }
          }
          long[4] cntL;
          foreach (u; 0 .. l + 1) {
            int p;
            if (visL[u][0]) p |= 1 << 0;
            if (visL[u][1]) p |= 1 << 1;
            ++cntL[p];
          }

          // (l, l + 1) to (u, u + 1),  parity of # of steps
          auto visR = new bool[2][N + 1];
          visR[l][0] = true;
          foreach (u; l .. N + 1) {
            foreach (i; G[u]) {
              // u -> v,  u + 1 -> v - 1
              const v = B[i];
              if (isGood(u + 1, v - 1)) {
                if (visR[u][0]) visR[v - 1][1] = true;
                if (visR[u][1]) visR[v - 1][0] = true;
              }
            }
          }
          long[4] cntR;
          foreach (u; /*!!!*/r - 1 .. N + 1) {
            int p;
            if (visR[u][0]) p |= 1 << 0;
            if (visR[u][1]) p |= 1 << 1;
            ++cntR[p];
          }

          debug {
            writeln("visL = ", visL);
            writeln("cntL = ", cntL);
            writeln("visR = ", visR);
            writeln("cntR = ", cntR);
          }

          foreach (p; 0 .. 4) foreach (q; 0 .. 4) {
            if (p & q) {
              ans += cntL[p] * cntR[q];
            }
          }
          if (l + 1 == r) {
            ans -= 1;
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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) {
        int N = readInt;
        int M = readInt;
        auto A = new int[M];
        auto B = new int[M];
        foreach (i; 0 .. M) {
          A[i] = readInt;
          B[i] = readInt;
        }
        M += 2 * N;
        foreach (u; 1 .. N + 1) {
          A ~= 0;
          B ~= u;
          A ~= u;
          B ~= N + 1;
        }

        auto graph = new int[][N + 2];
        auto graphRev = new int[][N + 2];
        foreach (i; 0 .. M) {
          graph[A[i]] ~= B[i];
          graphRev[B[i]] ~= A[i];
        }

        auto fs = new int[N + 1];
        foreach (i; 0 .. M) {
          if (A[i] + 1 == B[i]) {
            fs[A[i]] = 1;
          }
        }
        auto fsSum = new int[N + 2];
        foreach (u; 0 .. N + 1) {
          fsSum[u + 1] = fsSum[u] + fs[u];
        }

        long ans;
        if (fsSum[N + 1] == N + 1) {
          ans = 1L * N * (N - 1) / 2;
        } else {
          int l = N + 1, r = 0;
          foreach (u; 0 .. N + 1) {
            if (!fs[u]) {
              chmin(l, u);
              chmax(r, u + 1);
            }
          }
          debug {
            writeln("fs = ", fs);
            writeln("l = ", l, ", r = ", r);
          }
          bool isGood(int u, int v) {
            return (u <= v && fsSum[v] - fsSum[u] == v - u);
          }

          // (u, u + 1) to (l, l + 1),  parity of # of steps
          auto visL = new bool[2][N + 1];
          visL[l][0] = true;
          foreach_reverse (u; 0 .. l + 1) {
            foreach (v; graphRev[u + 1]) {
              // v -> u + 1,  v + 1 -> u
              if (isGood(v + 1, u)) {
                if (visL[u][0]) visL[v][1] = true;
                if (visL[u][1]) visL[v][0] = true;
              }
            }
          }
          long[4] cntL;
          foreach (u; 0 .. l + 1) {
            int p;
            if (visL[u][0]) p |= 1 << 0;
            if (visL[u][1]) p |= 1 << 1;
            ++cntL[p];
          }

          // (l, l + 1) to (u, u + 1),  parity of # of steps
          auto visR = new bool[2][N + 1];
          visR[l][0] = true;
          foreach (u; l .. N + 1) {
            foreach (v; graph[u]) {
              // u -> v,  u + 1 -> v - 1
              if (isGood(u + 1, v - 1)) {
                if (visR[u][0]) visR[v - 1][1] = true;
                if (visR[u][1]) visR[v - 1][0] = true;
              }
            }
          }
          long[4] cntR;
          foreach (u; /*!!!*/r - 1 .. N + 1) {
            int p;
            if (visR[u][0]) p |= 1 << 0;
            if (visR[u][1]) p |= 1 << 1;
            ++cntR[p];
          }

          debug {
            writeln("visL = ", visL);
            writeln("cntL = ", cntL);
            writeln("visR = ", visR);
            writeln("cntR = ", cntR);
          }

          foreach (p; 0 .. 4) foreach (q; 0 .. 4) {
            if (p & q) {
              ans += cntL[p] * cntR[q];
            }
          }
          if (l + 1 == r) {
            ans -= 1;
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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) {
        int N = readInt;
        int M = readInt;
        auto A = new int[M];
        auto B = new int[M];
        foreach (i; 0 .. M) {
          A[i] = readInt;
          B[i] = readInt;
        }
        M += 2 * N;
        foreach (u; 1 .. N + 1) {
          A ~= 0;
          B ~= u;
          A ~= u;
          B ~= N + 1;
        }

        auto G = new int[][N + 2];
        auto H = new int[][N + 2];
        foreach (i; 0 .. M) {
          G[A[i]] ~= i;
          H[B[i]] ~= i;
        }

        auto fs = new int[N + 1];
        foreach (i; 0 .. M) {
          if (A[i] + 1 == B[i]) {
            fs[A[i]] = 1;
          }
        }
        auto fsSum = new int[N + 2];
        foreach (u; 0 .. N + 1) {
          fsSum[u + 1] = fsSum[u] + fs[u];
        }

        long ans;
        if (fsSum[N + 1] == N + 1) {
          ans = 1L * N * (N - 1) / 2;
        } else {
          int l = N + 1, r = 0;
          foreach (u; 0 .. N + 1) {
            if (!fs[u]) {
              chmin(l, u);
              chmax(r, u + 1);
            }
          }
          debug {
            writeln("fs = ", fs);
            writeln("l = ", l, ", r = ", r);
          }
          bool isGood(int u, int v) {
            return (u <= v && fsSum[v] - fsSum[u] == v - u);
          }

          // (u, u + 1) to (l, l + 1),  parity of # of steps
          auto visL = new bool[2][N + 1];
          visL[l][0] = true;
          foreach_reverse (u; 0 .. l + 1) {
            foreach (i; H[u + 1]) {
              // v -> u + 1,  v + 1 -> u
              const v = A[i];
              if (isGood(v + 1, u)) {
                static foreach (s; 0 .. 2) {
                  if (visL[u][s]) {
                    visL[v][s ^ 1] = true;
                  }
                }
              }
            }
          }
          long[4] cntL;
          foreach (u; 0 .. l + 1) {
            int p;
            foreach (s; 0 .. 2) {
              if (visL[u][s]) {
                p |= 1 << s;
              }
            }
            ++cntL[p];
          }

          // (l, l + 1) to (u, u + 1),  parity of # of steps
          auto visR = new bool[2][N + 1];
          visR[l][0] = true;
          foreach (u; l .. N + 1) {
            foreach (i; G[u]) {
              // u -> v,  u + 1 -> v - 1
              const v = B[i];
              if (isGood(u + 1, v - 1)) {
                static foreach (s; 0 .. 2) {
                  if (visR[u][s]) {
                    visR[v - 1][s ^ 1] = true;
                  }
                }
              }
            }
          }
          long[4] cntR;
          foreach (u; /*!!!*/r - 1 .. N + 1) {
            int p;
            foreach (s; 0 .. 2) {
              if (visR[u][s]) {
                p |= 1 << s;
              }
            }
            ++cntR[p];
          }

          debug {
            writeln("visL = ", visL);
            writeln("cntL = ", cntL);
            writeln("visR = ", visR);
            writeln("cntR = ", cntR);
          }

          foreach (p; 0 .. 4) foreach (q; 0 .. 4) {
            if (p & q) {
              ans += cntL[p] * cntR[q];
            }
          }
          if (l + 1 == r) {
            ans -= 1;
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


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

void solve() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1].to!long;
    auto A = readln.split.map!(to!long).array;
    long mx = -1;
    int mxi = -1;
    long sm = 0;
    bool erased = false;
    int skipped = -1;
    foreach (i, a; A) {
        if (sm + a <= M) {
            sm += a;
            if (a >= mx) {
                mx = a;
                mxi = i.to!int;
            }
        } else if (!erased) {
            if (a >= mx) {
                mx = a;
                mxi = i.to!int;
            }
            if (sm + a - mx <= M) {
                sm += a - mx;
                erased = true;
                skipped = mxi;
            } else {
                break;
            }
        } else {
            break;
        }
    }
    writeln(skipped + 1);
}

void main() {
    auto T = readln.chomp.to!int;
    while (T--) solve;
}

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

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

alias Ans = Tuple!(int, int);

void main() {
  auto r = new InputReader;
  auto nt = r.next!uint;
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint.to!int;
    immutable s = r.next!uint;
    auto a = r.nextA!ulong(n);
    auto b = chain (only (0UL), a.cumulativeFold!((acc, x) => acc + x)).array;
    auto ans = Ans (0, 0);
    foreach (i; 1 .. n + 1) {
      if (b[i] <= s) ans = Ans (i, 0);
    }
    debug stderr.writeln (ans);
    auto e = assumeSorted (b);
    foreach (i; 0 .. n) {
      ulong x = s + a[i];
      auto rng = e.lowerBound (s + a[i] + 1);
      auto k = rng.length - 1;
      if (k >= (i + 1)) {
        auto cur = Ans ((k-1).to!int, (i + 1));
        if (ans[0] < cur[0]) ans = cur;
      }
      debug stderr.writeln (i, ' ', ans);
    }
    debug stderr.writeln (ans);
    writeln (ans[1]);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
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(){
	foreach(_; 0 .. rint){
		int n = rint;
		long s = rlong;
		long[] as = rlong(n);

		long[] sums  = [0];
		foreach(a; as) sums ~= sums[$ - 1] + a;
		long[] maxs = [0];
		foreach(a; as) maxs ~= max(maxs[$ - 1], a);

		if(sums[n] <= s) 0.writeln;
		else{
			int right = 1;
			long best = 0;
			foreach(i; 0 .. n + 1){
				long tmp = sums[i] - maxs[i];
				if(tmp <= s && best < i - 1){
					best = i - 1;
					right = i;
				}
			}
			int ans = 0;
			foreach(i; 0 .. right) if(as[i] == maxs[right]) ans = i + 1;
			ans.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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//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 main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!int;
		auto a = RDA;
		auto b = new long[](n+1);
		auto c = new long[][](n+1, 2);
		foreach (i; 0..n)
		{
			b[i+1] = b[i] + a[i];
			c[i+1] = c[i].dup;
			if (a[i] > c[i+1][0])
				c[i+1] = [a[i], i+1];
		}
		long best;
		int pos;
		foreach (i; 0..n)
		{
			if (b[i+1] <= s)
			{
				best = i+1;
				pos = 0;
			}
			else if (b[i+1] - c[i+1][0] <= s)
			{
				best = i;
				pos = cast(int)c[i+1][1];
			}
		}
		ans[ti] = pos;
	}

	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(){
	foreach(_; 0 .. rint){
		int n = rint;
		A[] as;
		B[] bs;
		foreach(i; 0 .. n){
			long l = rlong * 2, r = rlong * 2 + 1;
			as ~= A(l, r);
			bs ~= B(l, 1);
			bs ~= B(r, 2);
		}
		bs.sort!((a, b) => a.x < b.x)();
		log("as:", as);
		log("bs:", bs);

		int[long] za;
		int zt = -1, f = 0;
		foreach(b; bs){
			if(f == b.f) za[b.x] = zt;
			else f = b.f, za[b.x] = (++ zt);
		}
		log("za:", za);

		int zmax = zt + 1;

		long[] us = new long[](zmax);
		foreach(b; bs) us[za[b.x]] += [0, 1, -1][b.f];
		log("us:", us);

		long[] vs = [0];
		foreach(u; us) vs ~= vs[$ - 1] + u;
		log("vs:", vs);

		int vcnt = 0;
		long oldv = 0;
		foreach(v; vs){
			if(oldv == 0 && v > 0) vcnt += 1;
			oldv = v;
		}
		log("vcnt:", vcnt);

		long[] ws = [0];
		long[] ws2 = [0];
		foreach(i; 1 .. zmax){
			if(vs[i - 1] > 1 && vs[i] == 1 && vs[i + 1] > 1) ws ~= ws[$ - 1] + 1;
			else ws ~= ws[$ - 1];
			if(vs[i - 1] == 0 && vs[i] == 1 && vs[i + 1] == 0) ws2 ~= ws2[$ - 1] + 1;
			else ws2 ~= ws2[$ - 1];
		}
		ws ~= ws[$ - 1];
		ws2 ~= ws2[$ - 1];
		log("ws:", ws);
		log("ws2:", ws2);

		long ans;
		foreach(a; as){
			log("a:", a);
			long tmp = vcnt + (ws[za[a.r]] - ws[za[a.l]]) - (ws2[za[a.r]] - ws2[za[a.l]]);
			log("a:", a, "tmp:", tmp);
			ans.chmax(tmp);
		}

		ans.writeln;

	}
}

struct A{
	long l, r;
}
struct B{
	long x;
	int f; // 1 = opening, 2 = closing
}

import std.algorithm : maxElement, sort, swap;
import std.conv : to;
import std.range;
import std.stdio;
import std.typecons : Tuple, tuple;
import std.algorithm.mutation;

// import std.container.array;

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

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

void main()
{
    int T = readInt;
    while (T--)
    {
        int n = readInt;
        auto a = new Tuple!(int, int)[n];
        for (int i = 0; i < n; ++i)
        {
            a[i][0] = readInt;
            a[i][1] = readInt;
        }
        sort(a);
        int result = 0, mx0 = -1, mx1 = -1;
        int[] delta = new int[n];
        for (int i = 0; i < n; ++i)
        {
            if (mx0 == -1 || a[mx0][1] < a[i][0])
                result++, delta[i] = -1;
            else
            {
                delta[i] = 0;
                if (mx1 == -1 || a[mx1][1] < a[i][0])
                    delta[mx0]++;
            }
            int x = i;
            if (mx0 == -1 || a[x][1] > a[mx0][1])
                swap(mx0, x);
            if (~x && (mx1 == -1 || a[x][1] > a[mx1][1]))
                mx1 = x;
        }
        writeln(result + delta.maxElement);
    }
}

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(){
	foreach(_; 0 .. rint){
		int n = rint;
		A[] as;
		B[] bs;
		foreach(i; 0 .. n){
			long l = rlong * 2, r = rlong * 2 + 1;
			as ~= A(l, r);
			bs ~= B(l, 1);
			bs ~= B(r, 2);
		}
		bs.sort!((a, b) => a.x < b.x)();
		log("as:", as);
		log("bs:", bs);

		int[long] za;
		int zt = -1, f = 0;
		foreach(b; bs){
			if(f == b.f) za[b.x] = zt;
			else f = b.f, za[b.x] = (++ zt);
		}
		log("za:", za);

		int zmax = zt + 1;

		long[] us = new long[](zmax);
		foreach(b; bs) us[za[b.x]] += [0, 1, -1][b.f];
		log("us:", us);

		long[] vs = [0];
		foreach(u; us) vs ~= vs[$ - 1] + u;
		log("vs:", vs);

		int vcnt = 0;
		long oldv = 0;
		foreach(v; vs){
			if(oldv == 0 && v > 0) vcnt += 1;
			oldv = v;
		}
		log("vcnt:", vcnt);

		long[] ws = [0];
		foreach(i; 1 .. zmax - 1){
			if(vs[i - 1] > 1 && vs[i] == 1 && vs[i + 1] > 1) ws ~= ws[$ - 1] + 1;
			else ws ~= ws[$ - 1];
		}
		ws ~= ws[$ - 1];
		log("ws:", ws);

		long ans;
		foreach(a; as){
			log("a:", a);
			long tmp = vcnt + ws[za[a.r]] - ws[za[a.l]];
			log("a:", a, "tmp:", tmp);
			ans.chmax(tmp);
		}

		ans.writeln;

	}
}

struct A{
	long l, r;
}
struct B{
	long x;
	int f; // 1 = opening, 2 = closing
}


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 long[](t);
	foreach (ti; 0..t)
	{
		auto x = RD-1L;
		auto y = RD;
		auto k = RD;

		auto a = k*y;
		auto b = k + a - 1;
		ans[ti] = (b+x-1) / x + k;
	}

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

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    ll x, y, k, s;
    x = rd; y = rd; k = rd;
    x -= 1;
    ll totake = (k*y + k - 1);
    ll trade = totake/x + (totake % x != 0) + k;
    writeln(trade);
}

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

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    ll x, y, k;
    x = rd; y = rd; k = rd;
    x -= 1;
    ll trade = 0;
    ll s = 1;
    ll left = k*y;
    trade += left/x + (left % x != 0);
    if(left % x != 0){ s = left % x; }
    left = k - s;
    trade += left/x + (left % x != 0);
    trade += k;
    writeln(trade);
}

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

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    ll x, y, k, s;
    x = rd; y = rd; k = rd;
    if(k == 1){
        writeln(0);
    }
    x -= 1;
    ll trade = 1;
    ll left = k*y - x - 1;
    trade += left/x + (left % x != 0);
    if(left % x != 0){ s = x - (left % x); }
    left = max(k - s, 0);
    debug writeln(" L ", left);
    trade += left/x + (left % x != 0);
    trade += k;
    writeln(trade);
}

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

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    ll x, y, k, s;
    x = rd; y = rd; k = rd;
    x -= 1;
    ll trade = 1;
    ll left = k*y - x - 1;
    trade += left/x + (left % x != 0);
    if(left % x != 0){ s = x - (left % x); }
    left = max(k - s, 0);
    trade += left/x + (left % x != 0);
    trade += k;
    writeln(trade);
}

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


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 n = readln.strip.to!int;
    auto s = readln.strip;
    long ans;
    foreach (i ; 0 .. s.length) {
      int used = 0;
      int distinct = 0;
      int[10] cnt;
      foreach (j ; i .. s.length) {
        int digit = cast(int)(s[j] - '0');
//        writeln(digit);
        if ((used & (1 << digit)) == 0)
          distinct++;
        used |= (1 << digit);
        if (++cnt[digit] > 10)
          break;
        bool good = true;
//        writeln(cnt);
        foreach (x ; cnt) {
          if (x > distinct) {
            good = false;
            break;
          }
        }
        if (good)
          ans++;
      }
    }
    writeln(ans);
  }
}

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;
import std.functional;

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

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 solve() {
    int n = read!int;
    auto s = readln.strip();
    long res;
    foreach(i; 0 .. n) {
        int[10] num;
        int cnt, maxNum;
        foreach(k; i .. n) {
            auto t = s[k] - '0';
            if (num[t] >= 10)
                break;
            if(!num[t]) ++cnt;
            num[t]++;
            maxNum = max(maxNum, num[t]);
            if (maxNum <= cnt)
                ++res;
        }
    }
    writeln(res);
}

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

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;
import std.functional;

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

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 solve() {
    int n = read!int;
    auto s = readln.strip();
    long res, max_freq;
    foreach(i; 0 .. n)
        foreach(k; i .. n) {
            max_freq = 0;
            if (k - i > 1) {
                auto tmp = s[i..k].array.sort;
                auto dist = tmp.uniq.array.length;
                auto freq = tmp.group;
                max_freq = (freq.maxElement!"a[1]")[1];
                if (max_freq <= dist)
                    res++;
            }
            else if (k - i == 1)
                res++;
            if (max_freq > 10)
                break;
        }
    writeln(res);
}

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

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;
import std.functional;

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

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 solve() {
    int n = read!int;
    auto s = readln.strip();
    long res, max_freq;
    foreach(i; 0 .. n + 1)
        foreach(k; i .. n + 1) {
            if (k - i > 1) {
                auto tmp = s[i..k].array.sort;
                auto dist = tmp.uniq.array.length;
                auto freq = tmp.group;
                max_freq = (freq.maxElement!"a[1]")[1];
                if (max_freq <= dist)
                    res++;
            }
            else if (k - i == 1)
                res++;
            if (max_freq > 10)
                break;
        }
    writeln(res);
}

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

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;
import std.functional;

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

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 solve() {
    int n = read!int;
    auto s = readln.strip();
    long res, max_freq;
    foreach(i; 0 .. n)
        foreach(k; i .. n + 1) {
            auto tmp = s[i..k].array.sort;
            if (k - i > 1) {
                auto dist = tmp.uniq.array.length;
                auto freq = tmp.group;
                max_freq = (freq.maxElement!"a[1]")[1];
                if (max_freq <= dist)
                    res++;
            }
            else if (k - i == 1)
                res++;
            if (max_freq > 10)
                break;
        }
    writeln(res);
}

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


module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] m = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &m[i]);
	int l = 1;
	for (int i = 1; i < n; ++i)
	    if (m[i] == m[i-1])
	        l += 1;
	    else
	        break;

	bool f = false;
	int frst = m[0];
	for (int i = 0; i < n; ++i){
	    if (i % l == 0)
	        f = !f;
	    if ((f && m[i] != frst) || (!f && m[i] == frst)){
	        printf("NO");
	        return 0;
	    }
	}
	if (n % l == 0){
	    printf("YES");
	}
	else{
	    printf("NO");
	}

	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d",&n);
	int [] s = new int[n];
	for (int i=0; i<n; i++)
		scanf("%d", &s[i]);
	int x=0, y=0;
	bool isOk = true;
	for (int i=1; i<n; i++)
	{
		if (s[i] == s[i-1])
		{
			x++;
		}
		if (s[i] != s[i-1])
		{
			if (!isOk)
			{
				if (x != y)
				{
					printf("NO");
					return 0;
				}
			}
			if (isOk)
			{
				isOk = false;
			}
			y = x;
			x = 0;

		}
	}
	if (x != y && !isOk)
	{
		printf("NO");
		return 0;
	}
	printf("YES");
	return 0;
}

import std.algorithm;
import std.container;
import std.conv;
import std.exception;
import std.format;
import std.math;
import std.random;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main()
{
    immutable n = readln.strip.to!int;

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

    int w = 1;
    int prev = -1;
    bool ok = true;
    foreach (i; 1 .. n)
    {
        if (p[i - 1] == p[i])
        {
            w++;
        }
        else
        {
            ok &= prev < 0 || prev == w;
            prev = w;
            w = 1;
        }
    }
    ok &= prev < 0 || prev == w;

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

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n,k;
	int curr;
	int firstPeriod;
	int currentPeriod;
	scanf("%d", &n);
	firstPeriod = 0;
	currentPeriod= 0;
	for(int i = 0; i<n; i++){
		scanf("%d", &k);
		if(i==0){
			curr = k;
		}

		if(curr!=k){
			if(firstPeriod == 0){
				firstPeriod = currentPeriod;
			}
			if(firstPeriod != currentPeriod){
					printf("No");
					return 0;
			}
			currentPeriod = 0;
			curr = k;
		}
		currentPeriod++;

	}

	if(currentPeriod == firstPeriod || firstPeriod == 0){
		printf("YES");
	} else {
		printf("NO");
	}
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
	int q;
	if (a[0] == 1) {
	    for (int i = 0; i < n; i++)
	        a[i] = (a[i] + 1) % 2;
	}
	int k = 0;
	while (k < n && a[k] == 0)
	    k++;
	if (k == n)
	{
	    printf("YES\n");
	    return 0;
	}
	int ok = (n % k == 0);
	int type = 0;
	for (int i = 0; i < n && ok; i += k)
	{
	    for (int j = 0; j < k; j++)
	        if (a[i] != a[i + j] || a[i] != type)
	            ok = 0;
	    type ^= 1;
	}
	if (ok)
	    printf("YES\n");
	else
	    printf("NO\n");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
	int q=1,lq=-1,ok=1;
	for(int i = 1; i<n; i++){
            if(a[i]==a[i-1])
                q++;
            else{
                if(lq!=-1 && q!=lq)
                    ok=0;
                lq=q;
                q=1;
            }
	}
	if(!ok || (lq!=-1 && lq!=q))
        printf("NO");
    else
        printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n + 6];
	for(int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
	}
	int sz = 1;
	for(int i = 2; i <= n; i++) {
		if(a[i] != a[i - 1]) break;
		sz++;
	}
	if(sz == n) {
		printf("YES");
		return 0;
	}
	int cur = 1;
	for(int i = 2; i <= n; i++) {
		if(a[i] != a[i - 1]) {
			if(cur != sz) {
				printf("NO");
				return 0;
			}
			cur = 1;
		}
		else {
			cur++;
		}
	}
	if(cur != sz) {
		printf("NO");
		return 0;
	}
	printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv) {
    int n,k;
    scanf("%d", &n);
    int [] arr = new int[n];
    for(int i = 0; i<n; i++)
        scanf("%d", &arr[i]);
    int q;
    for(int i = 0; i<n; i++)
        if(arr[0] == arr[i])
            q++;
        else break;
    int now = 1;
    if (k == n) {
        printf("YES");
        return 0;
    }
    for (int i = k+1; i<n; i++) {
        if (arr[i] != arr[i-1]) {
            if (now!=q) {
                printf("NO");
                return 0;
            }
            now = 1;
        } else now++;
    }
    if (now != q) {
        printf("NO");
        return 0;
    }
    printf("YES");
    return 0;
}

module main;

import core.stdc.stdio;

int main()
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n];
	int [] b = new int [n];
	int k = 1, id = 0;
	a[0]=-1;
	for(int i = 1; i <= n; i ++)
	{
		scanf("%d", &a[i]);
		if(a[i] == a[i - 1])
			k ++;
		else
		{
		    if(i != 1) {
			id ++;
			b[id] = k;
			k = 1;
			}
		}
	}
	id ++;
	b[id] = k;
	k = 1;
	int t = 0;
	for(int i = 2; i <= id; i ++)
	{
		if(b[i] != b[i - 1])
			t = 1;
	}
	if(t == 1)
		printf("NO");
	else
		printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);

	k = 1;
	int w = -1;
	for(int i = 1; i<n; i++){
	    if (arr[i] == arr[i - 1])
	    {
	        k++;
	    }
	    else
	    {
	        if (w == -1)
	            w = k;
	        else
	        {
	            if (w != k)
	            {
	                //printf("%d ", k);
	                printf("NO");
	                return 0;
	            }

	        }
	        k = 1;

	    }
	}
	if (w == -1)
	  w = k;
	 else
	 {
	   if (w != k)
	    {
	                //printf("%d ", k);
	       printf("NO");
	       return 0;
      }

   }

	printf("YES");
	return 0;
}

module main;

import std.c.stdio;

void main(){
    int[100010] a;
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    int x=a[0];
    int res=1;
    int diff=0;
    int f=0;
    for(int i=1;i<n;i++){
        if(a[i]==x){
            res++;
        }
        else{
            x=a[i];
            if(diff==0) diff=res;
            else{
                if(res!=diff){
                    f=1;
                    break;
                }
            }
            res=1;
        }
    }
    if(res!=diff && diff!=0) f=1;
    if(!f) puts("YES");
    else puts("NO");

}

module main;

import core.stdc.stdio;

int main(string[] argv)
{
	int n,l,tmp;
	scanf("%d", &n);
	int [] a = new int[n+5];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
	for(int i=0;i<n;i++)
	{
		if (i==0||a[i]==a[i-1])
		    l = i + 1;
		else break;
    }
	tmp = l;
	for(int i=0; i<n; i++)
	{
	    if (i==0||a[i]!=a[i-1])
	    {
	        if (tmp!=l)
	        {
	            printf("NO");
	            return 0;
	        }
	        tmp=1;
	    }
	    else tmp++;
	}
	if (tmp==l)
	    printf("YES");
	else
	    printf("NO");
	return 0;
}

import std.stdio;

void main() {
    int n;
    readf("%d ", &n);
    int init = -1;
    int size = -1;
    bool ans = true;
    for (int i = 0; i < n; i++) {
        int q;
        readf("%d ", &q);
        if (i == 0) {
            init = q;
        } else {
            if (size == -1) {
                if (q != init) {
                    size = i;
                }
            } else {
                if (q != (((i / size) + init) % 2)) {
                    ans = false;
                    break;
                }
            }
        }
    }
    if (ans && n % size == 0) {
        writeln("YES");
    } else {
        writeln("NO");
    }
}

import std.stdio;
import std.conv;
import core.stdc.stdio;
import std.string;
int a[100005];
int dp[100005];
int main(string[] argv)
{
	int n;
	int x = 0,y=0;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d",&a[i]);
		dp[i]=dp[i-1]+a[i];
		if (i>1) {if (a[i]!=a[i-1])
		{
		    if (x==0)
		    {
		        x=i-1;
		        y=i;
		    }
		    else {if (i-y==x) y=i;
		    else {printf("NO");return 0;}}
		}
		}

	}
	if (dp[n]==0) {printf("YES");return 0;}
	if (dp[n]==n) {printf("YES");return 0;}
	if (n-y==x-1)
	printf("YES");
	else printf("NO");
	return 0;
}

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

void main() {
	int n, x;
	int ans = 1;
	int a=0, b=0;
	int c=0, d=-1;
	scanf("%d", &n );
	for( int i = 1; i <= n; i ++ )
	{
	    scanf( "%d", &x );
	    if( d == -1 )
	    {
	        d = x;
	    }
	   if( d == x )
	   {
	        c ++;
	   }
	   else
	   {
	    if( x == 1 )
	    {
	        if( a == 0 )
	            a = c;
	       if( a != c )
	            ans = 0;
	    }
	    else
	    {
	        if( b == 0 )
	            b = c;
	        if( b != c )
	            ans = 0;
	    }
	    d = x;
	    c = 1;
	    }
  }
	if( d == 0 )
	{
    	if( a == 0 )
    	   a = c;
    	   if( a != c )
    	        ans = 0;
	}
	else
    {
        if( b == 0 )
            b = c;
	    if( b != c )
	        ans = 0;
	}
	if( a == 0 )
	    a = b;
	if( b == 0 )
	    b = a;
	if( a != b )
	    ans = 0;
	if( ans == 1 )
	    printf( "YES" );
	else
	    printf( "NO" );
}

import std.stdio;

void main() {
    int cnt = 0, temp = 0, last = -1;
    int n;
    readf("%d\n", &n);
    int a;
    int ok = 1;
    for (int i = 0; i < n; i++) {
        readf("%d ", &a);

        if (a == last) {
            temp++;
        } else {
            last = a;
            if (cnt > 0 && cnt != temp) {
                ok = 2;
                break;
            } else {
                cnt = temp;
                temp = 1;
            }
        }
    }
    if (cnt > 0 && cnt != temp) {
        ok = 2;
    }
    if (ok == 1) {
        write("YES\n");
    } else {
        write("NO\n");
    }
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	if (n == 1) {
	    printf("YES");
	    return 0;
	} else {
    	int[] array = new int[n];
    	for(int i = 0; i < n; i++) {
    		scanf("%d", &array[i]);
    	}
    	int j = 1;
    	for (; j < n && array[j] == array[j - 1]; ++j) {}
    	if (j == n) {
    	    printf("YES");
    	    return 0;
    	}
    	if (n % j != 0) {
    	    printf("NO");
    	    return 0;
    	}
	    for(int i = 0; i < n; i += j) {
	        if (i > 0 && array[i] == array[i - 1]) {
	            printf("NO");
	            return 0;
	        }
	        for(int k = i + 1; k < i + j; ++k) {
	            if (array[k] != array[k - 1]) {
	                printf("NO");
	                return 0;
	            }
	        }
	    }
	    printf("YES");
	    return 0;
	}
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	int nw=0;
	int ans=0;
	for(int i=0;i<n;i++){
	  if(i==0 || arr[i]==arr[i-1]) nw++;
	  else{
	    if(ans==0) ans=nw;
	    else{
	      if(ans!=nw){
	        printf("NO");
	        return 0;
	      }
	    }
	    nw=1;
	 }
	}
	 if(ans==0) ans=nw;
	    else{
	      if(ans!=nw){
	        printf("NO");
	        return 0;
	      }
	    }
	printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);

	int pr = -1;
	int ln = 1;
	int ch = arr[0];
	int fl = 0;
	for (int i = 1; i < n; i++) {
	    if (arr[i] == ch) {
	        ln++;
	    } else {
	        if (pr == -1) pr = ln;
	        if (pr != ln) fl = 1;
	        ln = 1;
	        ch = arr[i];
	    }
	}
	if (pr == -1) pr = ln;
	if (ln != pr) fl = 1;

	if (fl == 1) printf("NO"); else printf("YES");
	return 0;
}

//in the name of god
import std.stdio;
void main() {
	int w,x=1,y=-1,z,p;
	bool b=1;
	readf(" %s\n%s",&w,&z);
	for(int i = 1; i<w; i++){
	    readf(" %s",&p);
	    if(z!=p){
	        if(y==-1) y=x;
	        else if(y!=x) b=0;
	        x=1;
	    }
	    else x++;
	    z=p;
	}
	if(y==-1) y=x;
	else if(y!=x) b=0;
	writeln(b?"YES":"NO");
}

module main;
import std.c.stdio;
import std.algorithm;
import std.array;
void main()
{
    int n,w=0,b=0,col=0,x=0;
    scanf("%d",&n);
    auto a = new int[n];
    for (int i=0;i<n;i++)
        scanf("%d",&a[i]);
    for (int i=0;i<n;i++)
    {
        if (i>0 && a[i]!=a[i-1])
        {
            if (col==0)
                col=x;
            if (col!=x)
            {
                printf("NO");
                return ;
            }
            x=0;
        }
        x++;
    }
    if (x!=0 && x!=col && col!=0)
    {
        printf("NO");
        return ;
    }
    printf("YES");
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	int q;
	int cur = arr[0];
	int i=1;
	while(i<n && arr[i] == cur)
	i++;
	q=i;
	int c=0;
	int ans=1;
	while(i<n)
	{
	    cur=arr[i];
	    c=0;
	    while(i<n && arr[i] == cur)
	    {
	        c++;i++;
	    }
	    if(c!=q)
	    ans=0;
	}
	if(ans)
	printf("YES");
	else
	printf("NO");
	return 0;
}

import std.stdio;

void main() {
    int n;
    int[100005] a;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    int cnt = -1;
    bool flag = 1;
    for (int i = 0; i < n; i++) {
        int j = i;
        for (j = i; j+1 < n && a[j+1] == a[i]; j++) {}
        if (cnt == -1 || j-i == cnt) {
            cnt = j-i;
            i = j;
        } else {
            flag = 0;
        }
    }
    if (flag) printf("YES"); else printf("NO");
}

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

void main(){

	int n;

	readf("%s", &n);
	readln;

	//  writeln(n);

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

	int x = a[0];
	int y = 1;

	int [100010]c;

	for (int i = 0; i < n; ++i){
		if (i == 0){
			++c[y];
			continue;
		}

		if (a[i] == a[i - 1]){
			++c[y];
			continue;
		}

		else{
			++y;
			c[y] = 1;
		}
	}

	int flag = 1;
	for (int i = 2; i <= y; ++i){
		if (c[i] != c[i - 1]){
			flag = 0;
			break;
		}
	}

	if (flag == 1) writeln("YES");
	else writeln("NO");

}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n+1];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
	int q=1,lq=-1,ok=1;
	for(int i = 1; i<n; i++){
            if(a[i]==a[i-1])
                q++;
            else{
                if(lq!=-1 && q!=lq)
                    ok=0;
                lq=q;
                q=1;
            }
	}
	if(!ok || lq!=q)
        printf("NO");
    else
        printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
	int q=1,lq=-1,ok=1;
	for(int i = 0; i<n; i++){
            if(a[i]==a[i-1])
                q++;
            else{
                if(lq!=-1 && q!=lq)
                    ok=0;
                lq=q;
                q=1;
            }
	}
	if(!ok || lq!=q)
        printf("NO");
    else
        printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	int nw=0;
	int ans=0;
	for(int i=0;i<n;i++){
	  if(i==0 || arr[i]==arr[i-1]) nw++;
	  else{
	    if(ans==0) ans=nw;
	    else{
	      if(ans!=nw){
	        printf("NO");
	        return 0;
	      }
	    }
	    nw=1;
	 }
	}
	 if(ans!=nw){
	        printf("NO");
	        return 0;
	      }
	printf("YES");
	return 0;
}

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

void main(){

	int n;

	readf("%s", &n);
	readln;

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

	int x = a[0];
	int y = 1;

	int [100010]c;

	for (int i = 0; i < n; ++i){
		if (i == 0){
			++c[y];
			continue;
		}

		if (a[i] == a[i - 1]){
			++c[y];
			continue;
		}

		else{
			++y;
			c[y] = 1;
		}
	}

	int flag = 1;
	for (int i = 2; i <= y; ++i){
		if (c[y] != c[y - 1]){
			flag = 0;
			break;
		}
	}

	if (flag == 1) writeln("YES");
	else writeln("NO");

}