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

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    string str = strip(readln());
    int n = str.length;
    int[] a = new int[n];
    foreach (i; 0..n-1) {
        a[i] = str[i] == str[i+1];
    }
    foreach (i; 1..n-1) {
        a[i] += a[i-1];
    }
    int m;
    readf("%d ", &m);
    foreach (i; 0..m) {
        int l;
        int r;
        readf("%d %d ", &l, &r);
        l--;
        r--;
        int res = a[r-1]-(l == 0 ? 0 : a[l-1]);
        writeln(res);
    }
}

// https://codeforces.com/problemset/problem/313/B
import std.stdio;
import std.string;
import std.conv;

void main() {
    string s = readln.chomp;

    int[100005] a;

    for(int i = 1; i < s.length; i++) {
        if(s[i] == s[i-1])
            a[i] = 1;
    }

    for(int i = 1; i < s.length; i++) {
        a[i] += a[i-1];
    }

    int m = readln.chomp.to!int;
    //m.writeln;

    int l, r;
    foreach(idx; 0..m) {
        readf("%d %d\n", &l, &r);
        writefln("%d", a[--r]-a[--l]);
    }
}

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

void main ()
{
	string s;
	while ((s = readln ()) != null)
	{
		int n = s.length;
		auto a = new int [n];
		a[0] = 0;
		foreach (i; 1..n)
		{
			a[i] = (s[i - 1] == s[i]);
		}
		foreach (i; 1..n)
		{
			a[i] += a[i - 1];
		}

		int m;
		readf (" %s ", &m);
		foreach (i; 0..m)
		{
			int l, r;
			readf (" %s %s ", &l, &r);
			writeln (a[r - 1] - a[l - 1]);
		}
	}
}

import std.stdio: readln, writeln;
import std.string: strip;
import std.conv: to;
import std.array: split;

/**
 * User: Jior
 * Date: 03.06.13
 * Time: 14:25
 */

void main(string[] args) {
    int[100001] m;
    char[] inString = strip(readln()).dup;
    for(int i = 0; i < inString.length-1; i++) {
        m[i+1] = m[i] + (inString[i] == inString[i+1]);
    }

    int countReq = to!int(strip(readln()).dup);
    foreach(int regNum; 0..countReq) {
        string request = strip(readln());
        int[] reqValue = to!(int[])(request.split());
        writeln(m[reqValue[1]-1] - m[reqValue[0]-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, core.stdc.stdio, std.bitmanip;

void main() {
    auto S = readln.chomp;
    auto N = S.length.to!int;

    auto same = new int[](N);
    foreach (i; 1..N) {
        same[i] = (S[i] == S[i-1]);
    }

    auto acm = new int[](N);
    foreach (i; 1..N) {
        acm[i] = acm[i-1] + same[i];
    }

    auto M = readln.chomp.to!int;
    foreach (_; 0..M) {
        auto s = readln.split.map!(to!int);
        auto l = s[0]-1;
        auto r = s[1]-1;
        writeln(acm[r] - acm[max(0, l-1)] - same[l]);
    }

}

// https://codeforces.com/problemset/problem/313/B
import std.stdio;
import std.string;
import std.conv;

void main() {
    string s = readln.chomp;

    int[100005] a;

    for(int i = 1; i < s.length; i++) {
        if(s[i] == s[i-1])
            a[i] = 1;
        a[i] += a[i-1];
    }

    int m = readln.chomp.to!int;
    //m.writeln;

    int l, r;
    foreach(idx; 0..m) {
        readf("%d %d\n", &l, &r);
        writefln("%d", a[--r]-a[--l]);
    }
}

// https://codeforces.com/problemset/problem/313/B
import std.stdio;
import std.string;
import std.conv;

void main() {
    string s = readln.chomp;

    int[100005] a;

    for(int i = 1; i < s.length; i++) {
        if(s[i] == s[i-1])
            a[i+1] = 1;
        a[i] += a[i-1];
    }

    int m = readln.chomp.to!int;
    //m.writeln;

    int l, r;
    foreach(idx; 0..m) {
        readf("%d %d\n", &l, &r);
        writefln("%d", a[--r]-a[--l]);
    }
}


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;
    int[] res;
    for(int i = 1; i <= n / 2 + n % 2; i++) {
        res ~= i;
        if (i > n - i)
            break;
        res ~= n - i + 1;
    }
    writefln("%(%s %)",res);
}

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()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = iota(1, n + 1).array;
    swap(a[1], a[$ - 1]);
    writefln("%(%s %)", a);
  }
}

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

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

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

void solve() {
    int N = read!int;
    auto a = new int[N];
    int l = 0, r = N - 1;
    for (int k = 1; k <= N; k++) {
        if (k % 2 == 0) {
            a[r--] = k;
        } else {
            a[l++] = k;
        }
    }
    writefln("%(%s %)", a);
}

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;
    int[] res;
    for(int i = 1; i <= n; i++) {
        res ~= i;
        if (i > n - i)
            break;
        res ~= n - i + 1;
    }
    writefln("%(%s %)",res);
}

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


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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		long res = 0;
		foreach (i; 1..n / 2 + 1)
		{
			res += i * 8L * i;
		}
		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) { x.modm(y.modpow(mod - 2)); }

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

		foreach (i; 0..n/2)
		{
			auto size = n - (i*2);
			auto cnt = size * 2 + (size-2) * 2;
			auto d = n/2 - i;
			ans[ti] += cnt * d;
		}
	}

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


import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.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 n = RD!int;
	auto a = RDR.ARR;
	auto toI = [4:0, 8:1, 15:2, 16:3, 23:4, 42:5];
	auto cnt = new long[](6);
	foreach (i; 0..n)
	{
		auto pos = toI[cast(int)a[i]];
		bool ok = true;
		foreach (j; 0..pos)
		{
			if (cnt[j] <= cnt[pos])
			{
				ok = false;
				break;
			}
		}
		if (ok)
			++cnt[pos];
	}
	long ans;
	ans = n - (cnt[$-1]*6);

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

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;

void main() {
  GC.disable();

  int n;
  readf(" %s", n);
  int[] a = new int[n];
  int[] v = new int[n];
  v[] =0;
  foreach(i;0..n) readf(" %s", a[i]);

  int[] nn =[4, 8, 15, 16, 23, 42];
  int[] aa;
  int ii = 0;
  int cc = 0;
  int[6] sii;
  sii[] = 0;
  int i;
  i =0;
  while(i < n) {
    if (v[i] == 0 && a[i] == nn[ii]) {
      cc++;
      v[i] = 1;
      sii[ii] = i;
      ii = (ii+1) % nn.length;
      i = sii[0 .. ii+1].maxElement;
    }
    i++;
  }

  writeln(n - (cc/6)*6);

}

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;

void main() {
  GC.disable();

  int n;
  readf(" %s", n);
  int[] a = new int[n];
  int[] v = new int[n];
  v[] =0;
  foreach(i;0..n) readf(" %s", a[i]);

  int[] nn =[4, 8, 15, 16, 23, 42];
  int[] aa;
  int ii = 0;
  int cc = 0;
  int[6] sii;
  int i;
  i =0;
  while(i < n) {
    if (v[i] == 0 && a[i] == nn[ii]) {
      sii[ii] = i;
      ii = (ii+1) % nn.length;
      cc++;
      v[i] = 1;
      i = sii[ii];
    }
    i++;
  }

  writeln(n - (cc/6)*6);

}

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;

void main() {
  GC.disable();

  int n;
  readf(" %s", n);
  int[] a = new int[n];
  foreach(i;0..n) readf(" %s", a[i]);

  int[] nn =[4, 8, 15, 16, 23, 42];
  int[] aa;
  int ii = 0;
  int cc = 0;
  foreach(e; a) {
    if (e == nn[ii]) {
      ii = (ii+1) % nn.length;
      cc++;
    }
  }

  writeln(n - (cc/6)*6);

}

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;

void main() {
  GC.disable();

  int n;
  readf(" %s", n);
  int[] a = new int[n];
  int[] v = new int[n];
  v[] =0;
  foreach(i;0..n) readf(" %s", a[i]);

  int[] nn =[4, 8, 15, 16, 23, 42];
  int[] aa;
  int ii = 0;
  int cc = 0;
  int[6] sii;
  sii[] = 0;
  int i;
  i =0;
  while(i < n) {
    if (v[i] == 0 && a[i] == nn[ii]) {
      sii[ii] = i;
      ii = (ii+1) % nn.length;
      cc++;
      v[i] = 1;
      i = sii[ii];
    }
    i++;
  }

  writeln(n - (cc/6)*6);

}

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;

void main() {
  GC.disable();

  int n;
  readf(" %s", n);
  int[] a = new int[n];
  foreach(i;0..n) readf(" %s", a[i]);

  int[] nn =[4, 8, 15, 16, 23, 42];
  int[] aa;
  int ii = 0;
  int cc = 0;
  foreach(e; a) {
    if (e == nn[ii]) {
      ii = (ii+1) % nn.length;
      cc++;
    }
  }

  writeln(n - (n/6)*6);

}

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 n = RD!int;
	auto a = RDR.ARR;
	auto toI = [4:0, 8:1, 15:2, 16:3, 23:4, 42:5];
	auto cnt = new long[](6);
	long ans;
	foreach (i; 0..n)
	{
		auto pos = toI[cast(int)a[i]];
		bool ok = true;
		foreach (j; 0..pos)
		{
			if (cnt[j] <= cnt[pos])
			{
				ok = false;
				break;
			}
		}
		if (ok)
			++cnt[pos];
		else
			++ans;
	}
	debug writeln(ans);
	ans += (n-ans) % 6;

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


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

string FMT_F = "%.10f";

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

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

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

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(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)); }

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

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

		auto cnt = new long[][](s.length+1, 3);
		foreach (i; 0..s.length)
		{
			auto num = s[i]-'1';
			cnt[i+1] = cnt[i].dup;
			++cnt[i+1][num];
		}

		int tmp = int.max;
		foreach (int i; 0..cast(int)s.length)
		{
			bool f(int j)
			{
				auto x = cnt[j].dup;
				x[] -= cnt[i][];
				return x[0] != 0 && x[1] != 0 && x[2] != 0;
			}
			auto r = binarySearch!(f)(cast(int)s.length+1, i);
			if (r != s.length+1)
			{
				tmp.chmin(r-i);
			}
		}
		if (tmp != int.max)
		{
			ans[ti] = tmp;
		}
	}

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

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto S = readln.chomp;
        auto len = S.length;
        auto l1 = new size_t[](len);
        auto r1 = new size_t[](len);
        auto l2 = new size_t[](len);
        auto r2 = new size_t[](len);
        auto l3 = new size_t[](len);
        auto r3 = new size_t[](len);

        auto i1 = len, i2 = len, i3 = len;
        foreach (i, c; S) {
            switch (c) {
                case '1': i1 = i; break;
                case '2': i2 = i; break;
                default: i3 = i;
            }
            l1[i] = i1;
            l2[i] = i2;
            l3[i] = i3;
        }
        i1 = len, i2 = len, i3 = len;
        foreach_reverse (i, c; S) {
            switch (c) {
                case '1': i1 = i; break;
                case '2': i2 = i; break;
                default: i3 = i;
            }
            r1[i] = i1;
            r2[i] = i2;
            r3[i] = i3;
        }

        auto res = size_t.max;
        foreach (i; 0..len) {
            switch (S[i]) {
                case '1':
                    if (l2[i] != len && r3[i] != len) {
                        res = min(res, r3[i] - l2[i] + 1);
                    }
                    if (l3[i] != len && r2[i] != len) {
                        res = min(res, r2[i] - l3[i] + 1);
                    }
                    break;
                case '2':
                    if (l1[i] != len && r3[i] != len) {
                        res = min(res, r3[i] - l1[i] + 1);
                    }
                    if (l3[i] != len && r1[i] != len) {
                        res = min(res, r1[i] - l3[i] + 1);
                    }
                    break;
                default:
                    if (l2[i] != len && r1[i] != len) {
                        res = min(res, r1[i] - l2[i] + 1);
                    }
                    if (l1[i] != len && r2[i] != len) {
                        res = min(res, r2[i] - l1[i] + 1);
                    }
            }
        }
        writeln(res == size_t.max ? 0 : 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)); }

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

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

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

enum LIM_K = 10^^5 + 5;

void main() {
  prepare();

  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      const Q = readInt();
      auto E = new int[N];
      foreach (i; 0 .. N) {
        E[i] = readInt() - 1;
      }
      auto L = new int[Q];
      auto R = new int[Q];
      auto K = new int[Q];
      foreach (q; 0 .. Q) {
        L[q] = readInt() - 1;
        R[q] = readInt();
        K[q] = readInt();
      }

      debug {
        // brute
        writeln("brute");
        foreach (q; 0 .. Q) {
          auto as = new int[M];
          auto bs = new int[M];
          foreach (i; 0 .. N) {
            ++as[E[i]];
            if (L[q] <= i && i < R[q]) {
              ++bs[E[i]];
            }
          }
          Mint ans = 1;
          foreach (j; 0 .. M) {
            ans *= fac[K[q] + as[j]] * invFac[K[q] + as[j] - bs[j]];
          }
          foreach (i; R[q] - L[q] .. N) {
            ans *= (1L * K[q] * M + N - i);
          }
          writeln(ans);
        }
      }

      auto as = new int[M];
      foreach (i; 0 .. N) {
        ++as[E[i]];
      }

      class Query {
        int l, r;
        int id;
        int key0, key1;
        this(int l, int r, int id) {
          this.l = l;
          this.r = r;
          this.id = id;
        }
        override string toString() const {
          return format("[%s, %s)", l, r);
        }
      }
      auto queriess = new Query[][LIM_K];
      foreach (q; 0 .. Q) {
        queriess[K[q]] ~= new Query(L[q], R[q], q);
      }
      auto ans = new Mint[Q];
      foreach (k; 0 .. LIM_K) {
        auto queries = queriess[k];
        if (queries) {
          // suffix prod for (k M + N - 0) ... (k M + N - (N - 1))
          auto prod = new Mint[N + 1];
          prod[N] = 1;
          foreach_reverse (i; 0 .. N) {
            prod[i] = (1L * k * M + N - i) * prod[i + 1];
          }

          const queriesLen = cast(int)(queries.length);
          // int sz = cast(int)(sqrt(cast(real)(N)));
          // chmax(sz, 10^^5 / queriesLen);
          const sz = max(N / cast(int)(sqrt(cast(real)(queriesLen))), 1);
          foreach (q; queries) {
            q.key0 = q.l / sz;
            q.key1 = q.r;
            if (q.key0 % 2 != 0) {
              q.key1 *= -1;
            }
          }
          queries.sort!((a, b) => ((a.key0 != b.key0) ? (a.key0 < b.key0) : (a.key1 < b.key1)));
          debug {
            writeln("k = ", k, ", sz = ", sz);
            writeln("  queries = ", queries);
          }

          Mint now = 1;
          auto bs = new int[M];
          void add(int i) {
            const j = E[i];
            /*
            now *= fac[k + as[j] - bs[j]];
            ++bs[j];
            now *= invFac[k + as[j] - bs[j]];
            */
            now *= (k + as[j] - bs[j]);
            ++bs[j];
          }
          void rem(int i) {
            const j = E[i];
            /*
            now *= fac[k + as[j] - bs[j]];
            --bs[j];
            now *= invFac[k + as[j] - bs[j]];
            */
            --bs[j];
            now *= inv[k + as[j] - bs[j]];
          }

          int l, r;
          foreach (q; queries) {
            for (; l > q.l; ) add(--l);
            for (; r < q.r; ) add(r++);
            for (; l < q.l; ) rem(l++);
            for (; r > q.r; ) rem(--r);
            ans[q.id] = now * prod[q.r - q.l];
          }
        }
      }
      foreach (q; 0 .. Q) {
        writeln(ans[q]);
      }
    }
  } 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)); }

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

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

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

enum LIM_K = 10^^5 + 5;

void main() {
  prepare();

  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      const Q = readInt();
      auto E = new int[N];
      foreach (i; 0 .. N) {
        E[i] = readInt() - 1;
      }
      auto L = new int[Q];
      auto R = new int[Q];
      auto K = new int[Q];
      foreach (q; 0 .. Q) {
        L[q] = readInt() - 1;
        R[q] = readInt();
        K[q] = readInt();
      }

      debug {
        // brute
        writeln("brute");
        foreach (q; 0 .. Q) {
          auto as = new int[M];
          auto bs = new int[M];
          foreach (i; 0 .. N) {
            ++as[E[i]];
            if (L[q] <= i && i < R[q]) {
              ++bs[E[i]];
            }
          }
          Mint ans = 1;
          foreach (j; 0 .. M) {
            ans *= fac[K[q] + as[j]] * invFac[K[q] + as[j] - bs[j]];
          }
          foreach (i; R[q] - L[q] .. N) {
            ans *= (1L * K[q] * M + N - i);
          }
          writeln(ans);
        }
      }

      auto as = new int[M];
      foreach (i; 0 .. N) {
        ++as[E[i]];
      }

      class Query {
        int l, r;
        int id;
        int key0, key1;
        this(int l, int r, int id) {
          this.l = l;
          this.r = r;
          this.id = id;
        }
        override string toString() const {
          return format("[%s, %s)", l, r);
        }
      }
      auto queriess = new Query[][LIM_K];
      foreach (q; 0 .. Q) {
        queriess[K[q]] ~= new Query(L[q], R[q], q);
      }
      auto ans = new Mint[Q];
      foreach (k; 0 .. LIM_K) {
        auto queries = queriess[k];
        if (queries) {
          // suffix prod for (k M + N - 0) ... (k M + N - (N - 1))
          auto prod = new Mint[N + 1];
          prod[N] = 1;
          foreach_reverse (i; 0 .. N) {
            prod[i] = (1L * k * M + N - i) * prod[i + 1];
          }

          const queriesLen = cast(int)(queries.length);
          int sz = cast(int)(sqrt(cast(real)(N)));
          chmax(sz, 10^^6 / queriesLen);
          // const sz = max(N / cast(int)(sqrt(cast(real)(queriesLen))), 1);
          foreach (q; queries) {
            q.key0 = q.l / sz;
            q.key1 = q.r;
            if (q.key0 % 2 != 0) {
              q.key1 *= -1;
            }
          }
          queries.sort!((a, b) => ((a.key0 != b.key0) ? (a.key0 < b.key0) : (a.key1 < b.key1)));
          debug {
            writeln("k = ", k, ", sz = ", sz);
            writeln("  queries = ", queries);
          }

          Mint now = 1;
          auto bs = new int[M];
          void add(int i) {
            const j = E[i];
            /*
            now *= fac[k + as[j] - bs[j]];
            ++bs[j];
            now *= invFac[k + as[j] - bs[j]];
            */
            now *= (k + as[j] - bs[j]);
            ++bs[j];
          }
          void rem(int i) {
            const j = E[i];
            /*
            now *= fac[k + as[j] - bs[j]];
            --bs[j];
            now *= invFac[k + as[j] - bs[j]];
            */
            --bs[j];
            now *= inv[k + as[j] - bs[j]];
          }

          int l, r;
          foreach (q; queries) {
            for (; l > q.l; ) add(--l);
            for (; r < q.r; ) add(r++);
            for (; l < q.l; ) rem(l++);
            for (; r > q.r; ) rem(--r);
            ans[q.id] = now * prod[q.r - q.l];
          }
        }
      }
      foreach (q; 0 .. Q) {
        writeln(ans[q]);
      }
    }
  } catch (EOFException e) {
  }
}


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

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

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

    auto vals = make!(RedBlackTree!(int, "a > b", true));

    int ans = int.max;
    int biggersm = ds.sum(), smallersm = 0;
    auto arr = zip(ls, ds).sort!((t1, t2) => t1[0] < t2[0]).array;
    for (int i = 0; i < n; ) {
        debug { arr[i].writeln; }

        int j = i+1;

        while (j < n && arr[i][0] == arr[j][0]) { j += 1; }
        auto cursm = arr[i .. j].map!(t => t[1]).sum();
        biggersm -= cursm;

        debug { biggersm.writeln; }

        int[] omitted;
        for (int k = i; k < j-1 && ! vals.empty(); ++k) {
            omitted ~= vals.front;
            vals.removeFront();
        }

        ans = min(ans, biggersm + smallersm - omitted.sum());

        foreach (e; omitted) { vals.insert(e); }
        smallersm += cursm;
        for (int k = i; k < j; ++k) vals.insert(arr[k][1]);
        i = j;
    }

    ans.writeln;
}

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

alias Leg = Tuple!(int, "l", int, "d");

void main() {
  int n;
  scanf("%d", &n);
  Leg[] a = new Leg[n];
  foreach(i; 0..n) {
    scanf("%d", &a[i].l);
  }
  foreach(i; 0..n) {
    scanf("%d", &a[i].d);
  }
  a.sort();
  int[] s = new int[n + 1];
  foreach(i; 0..n) {
    s[i + 1] = s[i] + a[i].d;
  }
  int p = 0, q = 0;
  auto pq = BinaryHeap!(int[])(new int[n], 0);
  int ans = int.max, sum = 0;
  while (q < n) {
    while (p < n && a[p].l == a[q].l) {
      p++;
    }
    int ct = p - q;
    int cost = s[n];
    cost -= s[p] - s[q];
    int[] vs;
    foreach (v; pq.take(ct - 1)) {
      cost -= v;
      vs ~= v;
    }
    foreach(v; vs) {
      pq.insert(v);
    }
    ans = min(ans, cost);
    while (q < p) {
      sum += a[q].d;
      pq.insert(a[q].d);
      q++;
    }
  }
  writeln(ans);
}

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

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

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

    auto vals = make!(RedBlackTree!(int, "a > b", true));

    int ans = int.max;
    int biggersm = ds.sum(), smallersm = 0;
    auto arr = zip(ls, ds).sort!((t1, t2) => t1[0] < t2[0]).array;
    for (int i = 0; i < n; ) {
        debug { arr[i].writeln; }

        int j = i+1;

        while (j < n && arr[i][0] == arr[j][0]) { j += 1; }
        auto cursm = arr[i .. j].map!(t => t[1]).sum();
        biggersm -= cursm;

        debug { biggersm.writeln; }

        int[] ommited;
        for (int k = i; k < j-1 && ! vals.empty(); ++k) {
            ommited ~= vals.front;
            vals.removeFront();
        }

        ans = min(ans, biggersm + smallersm - ommited.sum());

        foreach (e; ommited) { vals.insert(e); }
        smallersm += cursm;
        for (int k = i; k < j; ++k) vals.insert(arr[k][1]);
        i = j;
    }

    ans.writeln;
}


module main;
__gshared:
import core.bitop, std.algorithm, std.bigint, std.bitmanip, std.complex,
	std.container, std.conv, std.datetime, std.functional, std.math, std.meta;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.parallelism, std.random, std.range, std.regex, std.stdio, std.string,
	std.traits, std.typecons, std.uni, std.variant;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
enum mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///lcm
		T lcm(T)(auto ref T a, auto ref T b)
		{
			return a / gcd(a, b) * b;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///BigInt greatest common divizor
		BigInt gcd(BigInt a, BigInt b)
		{
			while (b)
			{
				a %= b;
				swap(a, b);
			}
			return a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///integer size
		int sz(T)(T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l = 0, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (!(a[m] < g))
					r = m;
				else
					l = m;
			}
			return (!(a[l] < g)) ? l : r;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l = 0, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (g < a[m])
					r = m;
				else
					l = m;
			}
			return (g < a[l]) ? l : r;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return binf(a, g) != a.length;
		}
	}
	///write an array
	void putarr(X)(in X a, in char ch = ' ') if (isInputRange!X)
	{
		writefln("%(%s" ~ ch ~ "%)", a);
	}
	///write a matrix
	void putarr(X)(in X a)
			if (isInputRange!X && isInputRange!(ElementType!X) && !isSomeString!(ElementType!X))
	{
		writefln("%(%(%s %)\n%)", a);
	}
	///get an array
	bool getarr(X)(X a, in size_t n)
	{
		bool b = 1;
		foreach (ref i; a[0 .. n])
			b = input(&i);
		return b;
	}
	///read without format
	bool input(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s = 0;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		return s == ptrs.length;
	}
	///readln without format
	bool read(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s = 0;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		readln;
		return s == ptrs.length;
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version (home)
	{
		freopen("input.txt", "r", core.stdc.stdio.stdin);
		//freopen("output.txt", "w", core.stdc.stdio.stdout);
		/*StopWatch sw;
		sw.start;
		scope (exit)
		{
			sw.stop;
			stderr.writefln("\nTime: %d ms", sw.peek.msecs);
		}*/
	}
	int n;
	loop: while (read(n))
	{
		auto st = new SList!int;
		int cnt, ans, sp;
		foreach (_; 0 .. n)
		{
			int t;
			input(t);
			switch (t)
			{
			case 1:
				read(sp);
				while (!st.empty && st.front < sp)
				{
					ans++;
					st.removeFront;
				}
				break;
			case 2:
				ans += cnt;
				cnt = 0;
				break;
			case 3:
				int g;
				read(g);
				st.insert(g);
				while (!st.empty && st.front < sp)
				{
					ans++;
					st.removeFront;
				}
				break;
			case 4:
				cnt = 0;
				break;
			case 5:
				st.clear;
				break;
			case 6:
				cnt++;
				break;
			default:
				assert(0);
			}

		}
		writeln(ans);
	}
}

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

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

    int[] overtakes;
    Tuple!(int, int)[] speeds;
    foreach (i; 0 .. n) {
        int t;
        readf("%s", &t);
        if (t == 2 || t == 4 || t == 6) { overtakes ~= t; }
        else {
            int x = 0;
            if (t == 1 || t == 3) { readf(" %s", &x); }

            speeds ~= tuple(t, x);
        }
        readln;
    }

    int ans = 0;
    int ostack = 0;
    foreach (e; overtakes) {
        if (e == 2) {
            ans += ostack;
            ostack = 0;
        } else if (e == 4) { ostack = 0; }
        else { ostack += 1; }
    }

    int cspeed = 0;
    int[] speedlims;
    foreach (e; speeds) {
        if (e[0] == 1) {
            while (!speedlims.empty() && speedlims.back() < e[1]) {
                ans += 1;
                speedlims.popBack();
            }
            cspeed = e[1];
        } else if (e[0] == 3) {
            if (cspeed > e[1]) { ans += 1; }
            else { speedlims ~= e[1]; }
        } else {
            speedlims = [];
        }
    }

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

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = ok - (ok-ng) / 2;
		if (unaryFun!pred(mid))
			ok = mid;
		else ng = mid;
	}
	return ok;
}

void main()
{
	auto n = RD!int;
	auto s = new int[][](n);
	auto mm = new int[][](n);
	auto oks = new bool[](n);
	foreach (i; 0..n)
	{
		auto l = RD!int;
		s[i].length = l;
		foreach (j; 0..l)
			s[i][j] = RD!int;

		mm[i] = [int.max, int.min];
		int x = int.max;
		foreach (j; 0..l)
		{
			if (s[i][j] > x)
				oks[i] = true;
			x.chmin(s[i][j]);
			mm[i][0].chmin(s[i][j]);
			mm[i][1].chmax(s[i][j]);
		}
	}

	long cnt_ok;
	foreach (i; 0..n)
		if (oks[i]) ++cnt_ok;

	int[] list;
	foreach (i; 0..n)
	{
		if (oks[i]) continue;
		list ~= mm[i][1];
	}
	list.sort!"a > b"();

	long ans = cnt_ok * cnt_ok;
	ans += cnt_ok * (n - cnt_ok) * 2;
	foreach (i; 0..n)
	{
		debug writeln("i:", i, " ans:", ans);
		if (oks[i]) continue;
		bool f(int x)
		{
			return list[x] > mm[i][0];
		}
		auto r = binarySearch!(f)(-1, cast(int)list.length);
		debug writeln("i:", i, " r:", r);
		ans += r+1;
	}

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

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = new int [] [n];
		foreach (ref c; a)
		{
			c = readln.splitter.drop (1).map !(to !(int)).array;
		}

		long res = n * 1L * n;
		a = a.filter !(c => c.isSorted !(q{a > b})).array;
		auto lo = a.map !(minElement).array;
		auto hi = a.map !(maxElement).array;
		sort (lo);
		sort (hi);

		int k = lo.length.to !(int);
		int j = 0;
		foreach (i; 0..k)
		{
			while (j < k && hi[j] <= lo[i])
			{
				j += 1;
			}
			res -= j;
		}
		writeln (res);
	}
}

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(){
	int n = rint;
	int[long] uc, vc;
	foreach(i; 0 .. n){
		int l = rint;
		long[] aq = rlong(l);

		if(aq.hasAscent) continue;
		else{
			if(aq[0] !in uc) uc[aq[0]] = 0;
			uc[aq[0]] += 1;

			if(aq[$ - 1] !in vc) vc[aq[$ - 1]] = 0;
			vc[aq[$ - 1]] += 1;
		}
	}
	log("uc:", uc, "vc:", vc);

	long[] uks = uc.keys, vks = vc.keys;

	long[] zs = uks.dup;
	foreach(uk; uks) if(uk !in vc) vc[uk] = 0;
	foreach(vk; vks) if(vk !in uc) uc[vk] = 0, zs ~= vk;
	log("uks:", uks, "vks:", vks, "zs:", zs);

	zs.sort();
	log("zs:", zs);

	int[long] uu, vu;
	int vt = 0;
	foreach_reverse(z; zs){
		vu[z] = vt + vc[z];
		vt += vc[z];
	}
	int ut = 0;
	foreach(z; zs){
		uu[z] = ut + uc[z];
		ut += uc[z];
	}
	log( "uu:", uu, "vc:", vc);

	long ans = n.to!long * n.to!long;
	foreach(z; zs){
		ans -= uu[z].to!long * vc[z].to!long;
	}

	ans.writeln;

}
bool hasAscent(long[] aq){
	long b = aq[0];
	foreach(a; aq){
		if(b < a) return 1;
		else b = a;
	}
	return 0;
}

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 N = readInt();
      auto L = new int[N];
      auto S = new int[][N];
      foreach (i; 0 .. N) {
        L[i] = readInt();
        S[i] = new int[L[i]];
        foreach (x; 0 .. L[i]) {
          S[i][x] = readInt();
        }
      }

      auto decr = new bool[N];
      foreach (i; 0 .. N) {
        decr[i] = true;
        foreach (x; 0 .. L[i] - 1) {
          decr[i] = decr[i] && (S[i][x] >= S[i][x + 1]);
        }
      }

      int lim;
      foreach (i; 0 .. N) {
        foreach (x; 0 .. L[i]) {
          chmax(lim, S[i][x]);
        }
      }
      lim += 10;
      auto fs = new long[lim];
      foreach (i; 0 .. N) {
        if (decr[i]) {
          ++fs[S[i][0]];
        }
      }
      foreach (a; 1 .. lim) {
        fs[a] += fs[a - 1];
      }

      long ans = 1L * N * N;
      foreach (i; 0 .. N) {
        if (decr[i]) {
          ans -= fs[S[i][L[i] - 1]];
        }
      }
      writeln(ans);
    }
  } 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; }
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 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); }

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = ok - (ok-ng) / 2;
		if (unaryFun!pred(mid))
			ok = mid;
		else ng = mid;
	}
	return ok;
}

void main()
{
	auto n = RD!int;
	auto s = new int[][](n);
	auto mm = new int[][](n);
	auto oks = new bool[](n);
	foreach (i; 0..n)
	{
		auto l = RD!int;
		s[i].length = l;
		foreach (j; 0..l)
			s[i][j] = RD!int;

		mm[i] = [int.max, int.min];
		int x = int.max;
		foreach (j; 0..l)
		{
			if (s[i][j] > x)
				oks[i] = true;
			x.chmin(s[i][j]);
			mm[i][0].chmin(s[i][j]);
			mm[i][1].chmax(s[i][j]);
		}
	}

	int cnt_ok;
	foreach (i; 0..n)
		if (oks[i]) ++cnt_ok;

	int[] list;
	foreach (i; 0..n)
	{
		if (oks[i]) continue;
		list ~= mm[i][1];
	}
	list.sort!"a > b"();

	long ans = max(cnt_ok * (cnt_ok+1) / 2 * 2 - cnt_ok, 0);
	ans += cnt_ok * (n - cnt_ok) * 2;
	foreach (i; 0..n)
	{
		debug writeln("i:", i, " ans:", ans);
		if (oks[i]) continue;
		bool f(int x)
		{
			return list[x] > mm[i][0];
		}
		auto r = binarySearch!(f)(-1, cast(int)list.length);
		debug writeln("i:", i, " r:", r);
		ans += r+1;
	}

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


import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
import std.range.primitives;
import std.conv;
import std.bigint;

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

    int[2000] arr;
    int[] toomany, toofew;
    int[int] freq;
    int n, m;
    readf(" %s %s\n", &n, &m);
    int minmax = n / m;
    foreach ( i; 1 .. m + 1 ) {
        freq[i] = 0;
    }
    foreach ( i; 0 .. n ) {
        readf(" %s", &arr[i]);
        if (arr[i] > m) toomany ~= arr[i];
        else freq[arr[i]] += 1;
    }
    foreach ( i; freq.byKey ) {
        if (freq[i] > minmax) {
            foreach ( j; 0 .. freq[i] - minmax) {
                toomany ~= i;
            }
        }
        else if (freq[i] < minmax) {
            foreach ( j; 0 .. minmax - freq[i]) {
                toofew ~= i;
            }
        }
    }
    int cnter = 0;
    for (int i = 0; !toofew.empty; ++i) {
        int idx = toomany.length - toomany.find(arr[i]).length;
        if (idx != toomany.length) {
            ++cnter;
            arr[i] = toofew.back;
            toofew.popBack;
            toomany = toomany.remove(idx);
        }
    }
    writeln(minmax, " ", cnter);
    foreach ( i; 0 .. n ) {
        write(arr[i], " ");
    }
    writeln();

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
import std.range.primitives;
import std.conv;
import std.container.rbtree;

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

    int[2000] arr;
    auto toomany = new RedBlackTree!(int, "a < b", true);
    int[] toofew;
    int[int] freq;
    int n, m;
    readf(" %s %s\n", &n, &m);
    int minmax = n / m;
    foreach ( i; 1 .. m + 1 ) {
        freq[i] = 0;
    }
    foreach ( i; 0 .. n ) {
        readf(" %s", &arr[i]);
        if (arr[i] > m) toomany.insert(arr[i]);
        else freq[arr[i]] += 1;
    }
    foreach ( i; freq.byKey ) {
        if (freq[i] > minmax) {
            foreach ( j; 0 .. freq[i] - minmax) {
                toomany.insert(i);
            }
        }
        else if (freq[i] < minmax) {
            foreach ( j; 0 .. minmax - freq[i]) {
                toofew ~= i;
            }
        }
    }
    int cnter = 0;
    for (int i = 0; !toofew.empty; ++i) {
        auto er = toomany.equalRange(arr[i]);
        if (!er.empty) {
            ++cnter;
            toomany.removeKey(arr[i]);
            arr[i] = toofew.back;
            toofew.popBack;
        }
    }
    writeln(minmax, " ", cnter);
    foreach ( i; 0 .. n ) {
        write(arr[i], " ");
    }
    writeln();

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
import std.range.primitives;
import std.conv;

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

    int[2000] arr;
    int[int] freq;
    int[int] toomany;
    int[] toofew;
    int n, m;
    readf(" %s %s\n", &n, &m);
    int minmax = n / m;
    foreach ( i; 1 .. m + 1 ) {
        freq[i] = 0;
    }
    foreach ( i; 0 .. n ) {
        readf(" %s", &arr[i]);
        if (arr[i] > m) toomany[arr[i]] += 1;
        else freq[arr[i]] += 1;
    }
    foreach ( i; freq.byKey ) {
        if (freq[i] > minmax) {
            foreach ( j; 0 .. freq[i] - minmax) {
                toomany[i] += 1;
            }
        }
        else if (freq[i] < minmax) {
            foreach ( j; 0 .. minmax - freq[i]) {
                toofew ~= i;
            }
        }
    }
    int cnter = 0;
    for (int i = 0; !toofew.empty; ++i) {
        auto val = arr[i] in toomany;
        if (val && *val > 0) {
            ++cnter;
            *val -= 1;
            arr[i] = toofew.back;
            toofew.popBack;
        }
    }
    writeln(minmax, " ", cnter);
    foreach ( i; 0 .. n ) {
        write(arr[i], " ");
    }
    writeln();

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
import std.range.primitives;
import std.conv;
import std.bigint;

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

    int[2000] arr;
    int[] toomany, toofew;
    int[int] freq;
    int n, m;
    readf(" %s %s\n", &n, &m);
    int minmax = n / m;
    foreach ( i; 1 .. m + 1 ) {
        freq[i] = 0;
    }
    foreach ( i; 0 .. n ) {
        readf(" %s", &arr[i]);
        if (arr[i] > m) toomany ~= arr[i];
        else freq[arr[i]] += 1;
    }
    foreach ( i; freq.byKey ) {
        if (freq[i] > minmax) toomany ~= i;
        else if (freq[i] < minmax) toofew ~= i;
    }
    int cnter = 0;
    for (int i = 0; !toofew.empty; ++i) {
        int idx = toomany.length - toomany.find(arr[i]).length;
        if (idx != toomany.length) {
            ++cnter;
            arr[i] = toofew.back;
            toofew.popBack;
            toomany = toomany.remove(idx);
        }
    }
    writeln(minmax, " ", cnter);
    foreach ( i; 0 .. n ) {
        write(arr[i], " ");
    }
    writeln();

    return 0;
}


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

string solve (int n, int [] a)
{
	foreach_reverse (b; 0..30)
	{
		auto z = a.count !(x => (x & (1 << b)) > 0);
		if (z & 1)
		{
			if (z % 2 == n % 2 && z % 4 == 3)
			{
				return "LOSE";
			}
			return "WIN";
		}
	}
	return "DRAW";
}

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;
		writeln (solve (n, a));
	}
}

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

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

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

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

void main() {
  debug {
    enum lim = 100;
    auto dp = new int[][][][](lim, lim, 2, 2);
    foreach (a; 0 .. lim) foreach (b; 0 .. lim) foreach (s; 0 .. 2) foreach (t; 0 .. 2) {
      if (a + b == 0) {
        dp[a][b][s][t] = s;
      } else if (t == 1) {
        dp[a][b][s][t] = 0;
        if (a > 0 && dp[a - 1][b][s ^ 0][t ^ 1] == 1) dp[a][b][s][t] = 1;
        if (b > 0 && dp[a][b - 1][s ^ 1][t ^ 1] == 1) dp[a][b][s][t] = 1;
      } else {
        dp[a][b][s][t] = 1;
        if (a > 0 && dp[a - 1][b][s][t ^ 1] == 0) dp[a][b][s][t] = 0;
        if (b > 0 && dp[a][b - 1][s][t ^ 1] == 0) dp[a][b][s][t] = 0;
      }
    }
    foreach (a; 0 .. lim) foreach (b; 0 .. lim) {
      if (b % 2 != 0) {
        // writeln(a, " ", b, ": ", dp[a][b]);
        foreach (s; 0 .. 2) foreach (t; 0 .. 2) {
          assert(dp[a][b][s][t] == ((a % 2 == 0) ? (((b >> 1) & 1) ^ s ^ t) : t));
        }
      }
    }
  }

  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        auto A = new long[N];
        foreach (i; 0 .. N) {
          A[i] = readLong();
        }

        long sum;
        foreach (i; 0 .. N) {
          sum ^= A[i];
        }
        if (sum == 0) {
          writeln("DRAW");
        } else {
          const e = bsr(sum);
          auto cnt = new int[2];
          foreach (i; 0 .. N) {
            ++cnt[cast(int)((A[i] >> e) & 1)];
          }
          debug {
            writeln(cnt);
          }
          const ans = (cnt[0] % 2 == 0) ? (((cnt[1] >> 1) & 1) ^ 1) : 1;
          writeln(ans ? "WIN" : "LOSE");
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

string solve (int n, int [] a)
{
	foreach_reverse (b; 0..30)
	{
		auto z = a.count !(x => (x & (1 << b)) > 0);
		if (z & 1)
		{
			if (z == n && z % 4 == 3)
			{
				return "LOSE";
			}
			return "WIN";
		}
	}
	return "DRAW";
}

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;
		writeln (solve (n, a));
	}
}

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;
		writeln (a.fold !(q{a ^ b}) == 0 ? "DRAW" : "WIN");
	}
}


import std.stdio, std.string;

int f[100010];

void main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
        foreach (int i; 0 .. 100001)
        {
            f[i] = -1;
        }
        int succ = 1;
        foreach (int i; 0 .. n)
        {
            int x, k;
            scanf("%d%d", &x, &k);
            if (f[k] + 1 < x)
            {
                succ = 0;
            }
            else if (f[k] + 1 == x)
            {
                ++ f[k];
            }
        }
        if (succ == 1)
        {
            printf("YES\n");
        }
        else
        {
            printf("NO\n");
        }
    }
}

import std.stdio;

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

	bool[uint][] nums = new bool[uint][100_000];

	for(uint i = 0; i < n; i++)
	{
		uint x, k;
		readf(" %s %s", &x, &k);

		if(x != 0)
		{
			if(x - 1 !in nums[k])
			{
				writeln("NO");
				return;
			}
		}

		nums[k][x] = true;
	}

	writeln("YES");
}


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

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

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

    d = d ~ d;

    debug { d.writeln; }

    long sumklast( int mx, int k ) {
        long sm( int k ) {
            return (1 + k).to!long * k / 2;
        }
        return sm( mx ) - sm( mx - k );
    }

    int le = 2*n - 1;
    long tot = 0;
    long ans = 0, cur = 0;
    foreach_reverse ( r; n .. 2*n ) {
        le = min( le, r );

        while ( tot + d[le] <= x ) {
            tot += d[le];
            cur += sumklast( d[le], d[le] );
            --le;
        }

        auto spillover = sumklast( d[le], (x - tot).to!int );

        debug { writeln( r, ' ', cur, ' ', spillover ); }

        ans = max( ans, cur + spillover );

        if ( r - le > 0 ) {
            auto tosub = min( d[r], x ).to!int;
            cur -= sumklast( d[r], tosub );
            tot -= tosub;
        }
    }

    ans.writeln;
}

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

long t (long x)
{
	return x * (x + 1L) / 2;
}

void main ()
{
	int n;
	long x;
	while (readf !(" %s %s") (n, x) > 0)
	{
		readln;
		auto d = readln.splitter.map !(to !(int)).array;
		long res = 0;
		long cur = 0;
		int j = n - 1;
		foreach_reverse (i; 0..n)
		{
			while (d[j] <= x)
			{
				cur += t (d[j]);
				x -= d[j];
				j = (j + n - 1) % n;
			}
			res = max (res, cur + t (d[j]) - t (d[j] - x));
			cur -= t (d[i]);
			x += d[i];
		}
		writeln (res);
	}
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;
import std.traits;

void main(string[] args)
{
  auto n = next!int;
  auto x = next!long;
  auto d = next!long(n);
  if (x == 0) return 0.println;
  int i = 0;
  int j = 0;
  long noDaysInMonth = d[i];
  long hugs = d[i] * (d[i] + 1) / 2;
  long best = long.min;
  while (noDaysInMonth < x)
    {
      j--; if (j == -1) j = n - 1;
      noDaysInMonth += d[j];
      hugs += d[j] * (d[j] + 1) / 2;
    }
  while(i < n)
    {
      auto rem = noDaysInMonth - x;
      auto realHugs = hugs - rem * (rem + 1) / 2;

      debug print("i", i, "j", j, "rem", rem, "realHugs", realHugs);
      debug writeln;

      best = max(realHugs, best);
      i++;
      if (i == n) break;
      noDaysInMonth += d[i];
      hugs += d[i] * (d[i] + 1) / 2;
      while(noDaysInMonth >= x)
	{
	  noDaysInMonth -= d[j];
	  hugs -= d[j] * (d[j] + 1) / 2;
	  j++; if (j == n) j = 0 ;
	}
      j--; if (j < 0) j = n - 1;
      noDaysInMonth += d[j];
      hugs += d[j] * (d[j] + 1) / 2;
    }
  best.writeln;
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}

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 n = RD!int;
	auto x = RD;
	auto d = RDA;

	long ans;
	long cnt;
	long remain = x;
	long[][] log;
	foreach_reverse (_i; 0..n*2)
	{
		auto i = _i % n;
		auto y = d[i] * (d[i]+1) / 2;
		auto z = max(d[i]-remain, 0);
		ans.chmax(cnt + y - z * (z+1) / 2);
		debug writeln("i:", i, " cnt1:", cnt, " remain:", remain, " log:", log);
		if (remain < d[i])
		{
			(){
			while (remain < d[i])
			{
				if (log.empty)
				{
					cnt = 0;
					auto zz = max(d[i]-x, 0);
					cnt    += y - zz * (zz+1) / 2;
					ans.chmax(cnt);
					cnt = 0;
					remain = x;
					debug writeln("i:", i, " cnt2:", cnt);
					return;
				}
				else
				{
					auto l = log.front; log.popFront;
					remain += l[1];
					cnt    -= l[0];
					auto zz = max(d[i]-remain, 0);
					if (remain > 0)
						ans.chmax(cnt + y - zz * (zz+1) / 2);
					debug writeln("i:", i, " cnt3:", cnt, " ans:", ans);
				}
			}
			cnt += y;
			ans.chmax(cnt);
			remain -= d[i];
			log ~= [y, d[i]];
			}();
		}
		else
		{
			cnt    += y;
			remain -= d[i];
			log    ~= [y, d[i]];
		}
		debug writeln("ans:", ans);
	}

	writeln(ans);
	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.typecons;

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

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

    d = d ~ d;

    debug { d.writeln; }

    long sumklast( int mx, int k ) {
        long sm( int k ) {
            return (1 + k).to!long * k / 2;
        }
        return sm( mx ) - sm( mx - k );
    }

    int le = 2*n - 1, tot = 0;
    long ans = 0, cur = 0;
    foreach_reverse ( r; n .. 2*n ) {
        while ( tot + d[le] <= x ) {
            tot += d[le];
            cur += sumklast( d[le], d[le] );
            --le;
        }

        auto spillover = sumklast( d[le], x - tot );

        debug { writeln( r, ' ', cur, ' ', spillover ); }

        ans = max( ans, cur + spillover );

        auto tosub = min( d[r], x );
        cur -= sumklast( d[r], tosub );
        tot -= tosub;
    }

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

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

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

    d = d ~ d;

    debug { d.writeln; }

    long sumklast( int mx, int k ) {
        long sm( int k ) {
            return (1 + k).to!long * k / 2;
        }
        return sm( mx ) - sm( mx - k );
    }

    int le = 2*n - 1;
    long tot = 0;
    long ans = 0, cur = 0;
    foreach_reverse ( r; n .. 2*n ) {
        while ( tot + d[le] <= x ) {
            tot += d[le];
            cur += sumklast( d[le], d[le] );
            --le;
        }

        auto spillover = sumklast( d[le], (x - tot).to!int );

        debug { writeln( r, ' ', cur, ' ', spillover ); }

        ans = max( ans, cur + spillover );

        auto tosub = min( d[r], x ).to!int;
        cur -= sumklast( d[r], tosub );
        tot -= tosub;
    }

    ans.writeln;
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;
import std.traits;

void main(string[] args)
{
  auto n = next!int;
  auto x = next!int;
  auto d = next!long(n);
  if (x == 0) return 0.println;
  int i = 0;
  int j = 0;
  long noDaysInMonth = d[i];
  long hugs = d[i] * (d[i] + 1) / 2;
  long best = long.min;
  while (noDaysInMonth < x)
    {
      j--; if (j == -1) j = n - 1;
      noDaysInMonth += d[j];
      hugs += d[j] * (d[j] + 1) / 2;
    }
  while(i < n)
    {
      auto rem = noDaysInMonth - x;
      auto realHugs = hugs - rem * (rem + 1) / 2;

      debug print("i", i, "j", j, "rem", rem, "realHugs", realHugs);
      debug writeln;

      best = max(realHugs, best);
      i++;
      if (i == n) break;
      noDaysInMonth += d[i];
      hugs += d[i] * (d[i] + 1) / 2;
      while(noDaysInMonth >= x)
	{
	  noDaysInMonth -= d[j];
	  hugs -= d[j] * (d[j] + 1) / 2;
	  j++; if (j == n) j = 0 ;
	}
      j--; if (j < 0) j = n - 1;
      noDaysInMonth += d[j];
      hugs += d[j] * (d[j] + 1) / 2;
    }
  best.writeln;
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}


import std.stdio;
import std.array;
import std.range : enumerate, slide;
import std.algorithm : map;
import std.math : abs;
import std.string : strip, split;
import std.conv : to;

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

  foreach (i; 0..t) {
    int n;
    readf!"%d\n"(n);
    auto a = readln.strip.split.map!(to!int);
    auto found = false;
    // an array is interesting if max(a) - min(a) >= len(a)
    // find an interesting nonempty subarray if it exists
    foreach (l, w; a.slide(2).enumerate) {
      if (abs(w[0] - w[1]) >= 2) {
	writefln("YES\n%d %d", l+1, l+2);
	found = true;
	break;
      }
    }

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

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
multitest_loop:
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		foreach (i; 1..n)
		{
			if (abs (a[i] - a[i - 1]) > 1)
			{
				writeln ("YES");
				writeln (i, " ", i + 1);
				continue multitest_loop;
			}
		}
		writeln ("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;
		long[] as = rlong(n);

		foreach(i; 0 .. n - 1){
			long a = as[i], b = as[i + 1];
			if(abs(b - a) >= 2){
				"YES".writeln;
				writeln(i + 1, " ", i + 2);
				continue A;
			}
		}

		"NO".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 a = RDA;
		int l, r;
		foreach (i; 0..n)
		{
			auto d = a[i] - a[l];
			auto len = i-l+1;
			if (d >= len)
			{
				r = i;
				break;
			}
			else if (a[i] < a[l]+len)
			{
				l = i;
			}
		}
		if (r != 0)
		{
			ans[ti] = [l, r];
			continue;
		}
		l = 0;
		foreach (i; 0..n)
		{
			auto d = a[l] - a[i];
			auto len = i-l+1;
			if (d >= len)
			{
				r = i;
				break;
			}
			else if (a[i] > a[l]-len)
			{
				l = i;
			}
		}
		if (r != 0)
		{
			ans[ti] = [l, r];
			continue;
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			writeln(e[0]+1, " ", e[1]+1);
		}
	}
	stdout.flush;
	debug readln;
}

void main() {
	auto t = ri;
	foreach(_; 0..t) {
		auto n = ri;
		auto a = readAs!(int[]);
		bool flag = false;
		foreach(i; 0..n-1) {
			if(abs(a[i] - a[i+1]) >= 2) {
				writeln("YES");
				writefln("%d %d", i+1, i+2);
				flag = true;
				break;
			}
		}
		if(!flag) writeln("NO");
	}
}

// ===================================

import std.stdio;
import std.string;
import std.functional;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;

T readAs(T)() if (isBasicType!T) {
	return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
	return readln.split.to!T;
}

T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		res[i] = readAs!(T[]);
	}
	return res;
}

T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		auto s = rs;
		foreach(j; 0..width) res[i][j] = s[j].to!T;
	}
	return res;
}

int ri() {
	return readAs!int;
}

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}


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

void solve(){
	int n = read.to!int;

	int[][] zf = [
		[8, 9, 1, 13],
		[3, 12, 7, 5],
		[0, 2, 4, 11],
		[6, 10, 15, 14]
	];

	int[][] xf = new int[][](n, n);
	foreach(i; 0 .. n) foreach(j; 0 .. n){
		int zi = i % 4, zj = j % 4;
		int wi = i / 4, wj = j / 4;
		int w = wi * (n / 4) + wj;
		xf[i][j] = w * 16 + zf[zi][zj];
	}

	log("check i:", n.iota.map!((i){ int res = 0; foreach(j; 0 .. n) res ^= xf[i][j]; return res;}));
	log("check j:", n.iota.map!((j){ int res = 0; foreach(i; 0 .. n) res ^= xf[i][j]; return res;}));

	foreach(i; 0 .. n) xf[i].map!(to!string).array.join(" ").writeln;

}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();

      auto a = new int[][](N, N);
      foreach (x; 0 .. N) foreach (y; 0 .. N) {
        a[x][y] = (y / 4) * (4 * N) + x * 4 + (y % 4);
      }

      debug {
        foreach (x; 0 .. N) {
          int sum;
          foreach (y; 0 .. N) {
            sum ^= a[x][y];
          }
          writeln("row ", x, ": ", sum);
        }
        foreach (y; 0 .. N) {
          int sum;
          foreach (x; 0 .. N) {
            sum ^= a[x][y];
          }
          writeln("col ", y, ": ", sum);
        }
      }

      foreach (x; 0 .. N) {
        foreach (y; 0 .. N) {
          if (y > 0) {
            write(" ");
          }
          write(a[x][y]);
        }
        writeln();
      }
    }
  } catch (EOFException e) {
  }
}