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

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

alias T = RedBlackTree!(int, "a < b", true);

final class DisjointSet {
  int [] p, h, s;
  int n;
  T t;
  public:
  int bs () {
    if (t.empty) return 0;
    int u = findSet (n - 1);
    int v = t.back;
    if (s[u] == v) {
      t.removeBack ();
      int r = t.empty ? 0 : t.back;
      t.insert (v);
      return r;
    }
    return t.back;
  }
  this (in int _n) {
    n = _n;
    p = iota (0, n).array;
    h = new int[n];
    s = new int[n];
    //s[] = 0;
    t = new T ();
  }
  pure nothrow @nogc
  int findSet (in int x) {
    if (p[x] == x) {
      return x;
    }
    return p[x] = findSet (p[x]);
  }
  bool merge (int i, int j) {
    i = findSet (i);
    j = findSet (j);
    if (i != j) {
      if (s[i] > 0) t.removeKey (s[i]);
      if (s[j] > 0) t.removeKey (s[j]);
      if (h[i] < h[j]) {
        p[i] = j;
        s[j] += s[i];
        t.insert (s[j]);
      } else if (h[i] > h[j]) {
        p[j] = i;
        s[i] += s[j];
        t.insert (s[i]);
      } else {
        p[i] = j;
        s[j] += s[i];
        t.insert (s[j]);
        ++h[j];
      }
      return true;
    }
    return false;
  }
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  bool test () {
    const n = r.next!uint;
    auto a = r.nextA!uint (n);
    a[] -= 1;
    auto rank = new int[n];
    foreach (i; 0 .. n) {
      rank[a[i]] = i;
    }
    auto ds = new DisjointSet (n);
    foreach (i; 0 .. n) {
      int pos = rank[i];
      int t;
      if (pos > 0) {
        int x = ds.findSet (pos - 1);
        t = ds.s[x];
      }
      debug stderr.writefln!("pos = %d, i = %d, t = %d, bs = %d")(pos, i, t, ds.bs());
      if (t != ds.bs ()) {
        return false;
      }
      int u = ds.findSet (pos);
      ds.t.insert(++ds.s[u]);
      if (pos > 0 && a[pos-1] < a[pos]) ds.merge (pos - 1, pos);
      if (pos + 1 < n && a[pos+1] < a[pos]) ds.merge (pos, pos + 1);
    }
    return true;
  }
  foreach (tid; 0 .. nt) {
    writeln (test () ? "Yes" : "No");
  }
}

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

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

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

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

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

        bool ans = true;
        for (int i = 0, j; i < N; i = j) {
          j = P[i] + 1;
          foreach (k; i .. j) {
            ans = ans && (P[i] + i == P[k] + k);
          }
          if (!ans) {
            break;
          }
        }
        writeln(ans ? "Yes" : "No");
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto p = RDA(-1);

		auto rbt = new RedBlackTree!int;
		foreach (e; p)
			rbt.insert(e);

		auto tmp = new int[](n);
		tmp[] = 1;
		auto heap = heapify(tmp);

		auto cnt = new int[](n);
		cnt[] = 1;

		bool ok = true;
		auto index = p.MAKE_IDX;
		foreach (_i; index)
		{
			auto i = cast(int)_i;
			auto c = heap.front; heap.removeFront;
			if (cnt[i] != c)
			{
				debug writeln("i:", i);
				debug writeln(cnt);
				ok = false;
				break;
			}
			auto r = rbt.upperBound(i);
			if (!r.empty)
			{
				auto num = r.front;
				cnt[num] += cnt[i];
				heap.insert(cnt[num]);
			}
			cnt[i] = 0;
			rbt.remove(rbt.equalRange(i));
		}
		ans[ti] = ok;
	}

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

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

void solve()
{
    auto N = readln.chomp.to!int;
    auto ps = readln.split.to!(int[]);

    auto ii = new size_t[](N);
    foreach (i, ref p; ps) {
        p -= 1;
        ii[p] = i;
    }

    auto bs = new bool[](N);
    size_t i = ii[0];
    int n;
    for (;;)  {
        bs[i] = true;
        ++i;
        ++n;
        if (n == N) break;
        if (i == N || bs[i]) {
            i = ii[n];
            continue;
        }
        if (ps[i] != n) {
            writeln("No");
            return;
        }
    }
    writeln("Yes");
}

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

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

void main ()
{
	readln;
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto q = new int [n];
		foreach (i, c; p)
		{
			q[c] = i;
		}
		bool ok = true;
		foreach (i; 1..n)
		{
			ok &= (q[i] == q[i - 1] + 1) || (q[i] < q[i - 1]);
		}
		writeln (ok ? "Yes" : "No");
	}
}


import std.algorithm.comparison : min;
import std.algorithm.sorting : sort;
import std.stdio;

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

  foreach (q; 0..t) {
    int n;
    readf!"%d\n"(n);
    auto a = new int[n];
    foreach(i; 0..n) readf!"%d%c"(a[i], c);
    a.sort!"a > b";

    writeln(min(a[1] - 1, n - 2));
  }
}

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 t = read.to!int;
	foreach(q; 0 .. t){
		int n = read.to!int;
		long[] as;
		foreach(i; 0 .. n) as ~= read.to!long;

		as.sort!"a>b"();
		long ans = min(as[1] - 1, as.length - 2);
		ans.writeln;
	}
}

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; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } 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 = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto T = RD!int;
	foreach (i; 0..T)
	{
		auto n = RD!int;
		auto a = RDA;
		a.sort();
		auto len = min(a[$-1], a[$-2]);
		auto ans = min(a.length - 2, len - 1);
		writeln(ans);
	}

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


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

int m, k;
int n;
int[] a;
void main() {
    readf("%d %d %d\n", &n, &m, &k);
    int um, uk;
    a = stdin.readln.chop.split(" ").map!(to!int).array;
    foreach (x; a) {
        if (x == 1) {
            um++;
        } else {
            if (uk < k) {
                uk++;
            } else {
                um++;
            }
        }
    }
    writeln(max(um - m, 0) + max(uk - k, 0));
}

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                int b = cin.readInt;
                int p = cin.readInt;
                int w = 0;
                for (int i = 0; i < n; i++) {
                        int x = cin.readInt;
                        if (x == 1) {
                                (b == 0) ? w++ : b--;
                        }
                        if (x == 2) {
                                if (b == 0 && p == 0) w++;
                                else if (b == 0 && p > 0) p--;
                                else if (p == 0 && b > 0) b--;
                                else p--;
                        }
                }
                writeln(w);
        }
}

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

void main() {
  auto input = readln.chomp.split.map!(to!int).array;
  auto n = input[0];
  auto m = input[1];
  auto k = input[2];
  auto a = readln.chomp.split.map!(to!int).array;

  foreach (e; a) {
    switch (e) {
    case 1:
      m--;
      break;
    case 2:
      if (k > 0) { k--; } else { m--; }
      break;
    default:
      break;
    }
  }

  auto answer = 0;
  if (m < 0) { answer += -m; }
  if (k < 0) { answer += -k; }

  answer.writeln;
}

import std.stdio;

void main() {
    debug stdin = File("input.txt", "r");
    int n, m, k;
    readf(" %s %s %s", &n, &m, &k);

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

        if (x == 1) {
            if (m == 0) {
                ++ans;
            } else {
                --m;
            }

        } else {
            if (k > 0) {
                --k;
            } else if (m > 0) {
                --m;
            } else
                ++ans;
        }
    }

    writeln(ans);
}

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

int m, k;
int n;
int[] a;
void main() {
    readf("%d %d %d\n", &n, &m, &k);
    int um, uk;
    a = stdin.readln.chop.split(" ").map!(to!int).array;
    foreach (x; a) {
        if (x == 1) {
            um++;
        } else {
            if (uk < k) {
                uk++;
            } else {
                um++;
            }
        }
    }
    (uk + um - k - m).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 long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }
      auto B = new long[N];
      foreach (i; 0 .. N) {
        B[i] = readLong();
      }

      auto sel = new bool[N];
      auto as = A.dup;
      sort(as);
      foreach (k; 0 .. N - 1) {
        if (as[k] == as[k + 1]) {
          foreach (i; 0 .. N) {
            if ((as[k] | A[i]) == as[k]) {
              sel[i] = true;
            }
          }
        }
      }
      long ans;
      foreach (i; 0 .. N) {
        if (sel[i]) {
          ans += B[i];
        }
      }
      writeln(ans);

      debug {
        long brt;
        foreach (h; 0 .. 1 << N) {
          if (popcnt(h) >= 2) {
            bool ok = true;
            foreach (i; 0 .. N) if (h & 1 << i) {
              bool every = true;
              foreach (j; 0 .. N) if (h & 1 << j) {
                if (i != j) {
                  every = every && ((A[i] & ~A[j]) != 0);
                }
              }
              ok = ok && !every;
            }
            if (ok) {
              long sum;
              foreach (i; 0 .. N) if (h & 1 << i) {
                sum += B[i];
              }
              writeln(h, " ", sum);
              chmax(brt, sum);
            }
          }
        }
        assert(brt == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

    bool isBetter(long x, long y) {
        return (x & (x ^ y)) > 0;
    }

    auto inleaders = make!(RedBlackTree!long);
    int[] leaders;
    foreach (i; 0 .. n) {
        if (a[i] in inleaders) { continue; }

        bool same = false;
        foreach (j; 0 .. n) {
            if (i == j) { continue; }

            if (a[j] == a[i]) {
                same = true;
            }
        }

        if (same) {
            inleaders.insert(a[i]);
            leaders ~= i;
        }
    }

    auto added = new bool[] (n);
    added[] = false;
    foreach (p; leaders) {
        added[p] = true;
        foreach (j; 0 .. n) {
            if (added[j]) { continue; }

            if (a[j] == a[p] || !isBetter(a[j], a[p])) {
                added[j] = true;
            }
        }
    }

    long ans = 0;
    foreach (i; 0 .. n) {
        if (added[i]) { ans += b[i]; }
    }
    ans.writeln;
}

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

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

void solve(){
	int n = rint;
	long[] as = rlong(n);
	long[] bs = rlong(n);

	X[] xs;
	foreach(i; 0 .. n) xs ~= X(as[i], bs[i]);
	log("xs:", xs);

	int[long] xc;
	foreach(x; xs){
		if(x.a !in xc) xc[x.a] = 0;
		xc[x.a] += 1;
	}
	log("xc:", xc);

	long[] xas = xc.keys;
	long[] topas = [];
	foreach(a; xas) if(xc[a] > 1) topas ~= a;
	log("xas:", xas, "topas:", topas);

	long ans;
	foreach(x; xs){
		foreach(a; topas){
			log("x:", x, "a:", a, "x.a & a:", x.a & a);
			if((x.a & a) == x.a){
				ans += x.b;
				break;
			}
		}
		log("x:", x, "ans:", ans);
	}

	ans.writeln;
}
struct X{
	long a, b;
}

/*
- "Top team": two or more students with same ability.
 (there may be more than one top teams)
- "Sub team" of a top team: students strictly weaker than the top team student

Union of all top teams and their sub teams are the solution.
*/

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 long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }
      auto B = new long[N];
      foreach (i; 0 .. N) {
        B[i] = readLong();
      }

      long ans;
      foreach (i; 0 .. N) {
        bool ok;
        long sum = B[i];
        foreach (j; 0 .. N) {
          if (i != j) {
            if ((A[i] | A[j]) == A[i]) {
              ok = ok || (A[i] == A[j]);
              sum += B[j];
            }
          }
        }
        debug {
          writeln(i, " ", A[i], ": ", ok, " ", sum);
        }
        if (ok) {
          chmax(ans, sum);
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


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

const long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto dp = new long[](1 << 3);
    fill(dp, INF);
    dp[0] = 0;

    foreach (_; 0..N) {
        auto s = readln.split;
        auto c = s[0].to!long;
        auto S = s[1];
        int mask = 0;
        if (S.canFind('A')) mask |= 1;
        if (S.canFind('B')) mask |= (1 << 1);
        if (S.canFind('C')) mask |= (1 << 2);
        foreach (nmask; 0..8) {
            dp[mask | nmask] = min(dp[mask | nmask], dp[nmask] + c);
        }
    }

    writeln( dp[7] == INF ? -1 : dp[7] );
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; rd(n);
  auto mns=new int[](8);
  fill(mns, 1000000000);
  foreach(_; 0..n){
    auto args=readln.split.to!(char[][]);
    int kind=0;
    foreach(c; args[1]){
      kind^=(1<<(c-'A'));
    }
    mns[kind]=min(mns[kind], args[0].to!(int));
  }
  struct T{int kind, price;}
  T[] as, bs, cs;
  foreach(bit; 1..(1<<3)){
    if(mns[bit]==1000000000) continue;
    if(bit&(1<<0)) as~=T(bit, mns[bit]);
    if(bit&(1<<1)) bs~=T(bit, mns[bit]);
    if(bit&(1<<2)) cs~=T(bit, mns[bit]);
  }
  as~=T(0, 0); bs~=T(0, 0); cs~=T(0, 0);
  int mincost=1000000000;
  foreach(a; as){
    foreach(b; bs){
      foreach(c; cs){
        int bit=a.kind|b.kind|c.kind;
        if(bit==((1<<3)-1)){
          mincost=min(mincost, a.price+b.price+c.price);
        }
      }
    }
  }
  if(mincost<1000000000){
    writeln(mincost);
  }else{
    writeln(-1);
  }

}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


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; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } 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 = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto s = RD!string;
	long cnt;
	bool ans = true;
	foreach (i; 0..n)
	{
		if (s[i] == '(')
			++cnt;
		else
			--cnt;

		if (cnt < -1)
		{
			ans = false;
			break;
		}
	}

	writeln(ans && cnt == 0 ? "Yes" : "No");
	stdout.flush();
	debug readln();
}

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

void main() {
    int n;
    string s;
    readf!" %s %s"(n,s);
    s = s.strip;

    int a = 0;
    int mn = 0;
    foreach (c; s) {
        if (c == '(') a++;
        else a--;
        mn = min(mn, a);
    }

    if (a == 0 && mn >= -1) {
        writeln("Yes");
    } else {
        writeln("No");
    }
}

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

int N;
string S;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      S = readToken();

      auto as = new int[N + 1];
      auto ls = new int[N + 1];
      auto rs = new int[N + 1];
      foreach (i; 0 .. N) {
        as[i + 1] = as[i] + ((S[i] == '(') ? +1 : -1);
      }
      foreach (i; 0 .. N) {
        ls[i + 1] = min(ls[i], as[i + 1]);
      }
      foreach_reverse (i; 0 .. N) {
        rs[i] = min(rs[i + 1], as[i]);
      }

      bool ans;
      if (as[N] == 0) {
        debug {
          writeln("as = ", as);
          writeln("ls = ", ls);
          writeln("rs = ", rs);
        }
        ans = false;
        foreach (i; 0 .. N) {
          if (S[i] == '(') {
            if (1 + ls[i] >= 0 && rs[i + 1] >= 0) {
              ans = true;
            }
          } else {
            if (ls[i] >= 0 && 1 + rs[i + 1] >= 0) {
              ans = true;
            }
          }
        }
      } else {
        ans = false;
      }
      writeln(ans ? "Yes" : "No");
    }
  } catch (EOFException e) {
  }
}


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

int test () {
  auto s = readln.strip;
  auto t = readln.strip;
  immutable l = s.length.to!int;
  auto next = new int[26][l+1];
  next[l][] = l;
  foreach_reverse (i; 0 .. l) {
    next[i][] = next[i+1][];
    immutable k = s[i].to!int - 97;
    next[i][k] = i;
  }
  foreach (c; t) {
    immutable k = c.to!int - 97;
    if (next[0][k] >= l) return -1;
  }
  int i, res;
  foreach (c; t) {
    immutable k = c.to!int - 97;
    while (true) {
      i = next[i][k];
      if (i >= l) {
        ++res;
        i = 0;
      } else {
        break;
      }
    }
    ++i;
  }
  res++;
  return res;
}

void main() {
  immutable nt = readln.strip.to!int;
  foreach (tid; 0 .. nt) {
    writeln (test ());
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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 int[](T);
	foreach (ti; 0..T)
	{
		auto s = RD!string;
		auto t = RD!string;
		auto arr = new int[][](26);
		foreach (i; 0..s.length)
		{
			arr[s[i]-'a'] ~= cast(int)i;
		}

		ans[ti] = 1;
		int pos = -1;
		foreach (i; 0..t.length)
		{
			auto c = t[i]-'a';
			bool f(int x)
			{
				return arr[c][x] > pos;
			}
			auto r = binarySearch!(f)(cast(int)arr[c].length, -1);
			if (r == arr[c].length)
			{
				++ans[ti];
				pos = -1;
				r = binarySearch!(f)(cast(int)arr[c].length, -1);
				if (r == arr[c].length)
				{
					ans[ti] = -1;
					break;
				}
			}
			pos = arr[c][r];
			debug writeln("pos:", pos);
		}
	}

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


immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	auto viA = new int[2][](n);
	foreach(i, ai; a) viA[i] = [ai, cast(int)i];
	sort!((a, b) => a > b)(viA);
	long minTime = 0;
	long currentX = 1;
	void pop()
	{
		if (currentX > 0) currentX = -currentX;
		else currentX = -currentX + 1;
	}
	auto xs = new long[](n);
	foreach(viAi; viA)
	{
		auto value = viAi[0];
		auto index = viAi[1];
		minTime += 2 * abs(currentX * value);
		xs[index] = currentX;
		pop;
	}
	writeln(minTime);
	write("0 ");
	foreach(x; xs) write(x, " ");
	writeln;
}

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

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

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

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

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

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

void solve(){
    int n  = scan!int;
    auto arr = scanArray;
    tup[] zipp;
    for(int i = 0; i < n; ++i){
        zipp ~= tup(arr[i], i);
    }
    zipp.sort;
    ll sol = 0;
    auto res = new ll[](n);
    long cnt = 1;
    for(int i = n-1; i >= 0; i -= 2){
        res[zipp[i][1]] = cnt;
        sol += cnt * zipp[i][0];
        ++cnt;
    }
    cnt = -1;
    for(int i = n-2; i >= 0; i -= 2){
        res[zipp[i][1]] = cnt;
        sol += (- cnt) * zipp[i][0];
        --cnt;
    }
    writeln(2*sol);
    write(0, " ");
    res.each!((a) => write(a, " "));
    writeln;
}

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

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		ans2[ti].length = n+1;
		auto index = a.MAKE_IDX!"a > b";
		foreach (ii, i; index)
		{
			auto cnt = ii / 2 + 1;
			ans1[ti] += cnt * a[i] * 2;
			ans2[ti][i+1] = cnt;
			if (ii % 2)
				ans2[ti][i+1] *= -1;
		}
	}

	foreach (ti; 0..t)
	{
		writeln(ans1[ti]);
		ans2[ti].map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}


import std.stdio;

void main() {
    auto s = readln()[0 .. $ - 1];//Strip trailing '\n'.
    auto t = readln()[0 .. $ - 1];
    int[26] m;
    foreach (c; s)
        m[c - 'a']++;

    void writeRest() {
        foreach (i, cnt; m)
            foreach (j; 0 .. cnt)
                write(cast(char)(i + 'a'));
        writeln();
    }

    int i = 0;
    foreach (c; t) {
        if (!m[c - 'a'])
            break;
        m[c - 'a']--;
        i++;
    }

    if (i == t.length) {
        if (s.length > i) {
            write(t);
            writeRest();
            return;
        }
        m[t[--i] - 'a']++;
    }
    while (i >= 0) {
        debug writeln(m);
        foreach (j; t[i] - 'a' + 1 .. 26)
            if (m[j]) {
                write(t[0 .. i]);
                write(cast(char)(j + 'a'));
                m[j]--;
                writeRest();
                return;
            }
        if (i--)
            m[t[i] - 'a']++;
    }
    writeln("-1");
}

import std.stdio;

void main() {
    auto s = readln()[0 .. $ - 1];//Strip trailing '\n'.
    auto t = readln()[0 .. $ - 1];
    int[26] m;
    foreach (c; s)
        m[c - 'a']++;

    void writeRest() {
        foreach (i, cnt; m)
            foreach (j; 0 .. cnt)
                write(cast(char)(i + 'a'));
        writeln();
    }

    int i = 0;
    foreach (c; t) {
        if (!m[c - 'a'])
            break;
        m[c - 'a']--;
        i++;
    }

    if (i == t.length && s.length > i) {
        write(t);
        writeRest();
    } else {
        if (i == t.length)
            m[t[--i] - 'a']++;
        for (; i >= 0; ) {
            debug writeln(m);
            foreach (j; t[i] - 'a' + 1 .. 26)
                if (m[j]) {
                    write(t[0 .. i]);
                    write(cast(char)(j + 'a'));
                    m[j]--;
                    writeRest();
                    return;
                }
            if (i--)
                m[t[i] - 'a']++;
        }
        writeln("-1");
    }
}

import std.stdio;

void main() {
    auto s = readln()[0 .. $ - 1];//Strip trailing '\n'.
    auto t = readln()[0 .. $ - 1];
    int[26] m;
    foreach (c; s)
        m[c - 'a']++;
    int i = 0;
    foreach (c; t[0 .. $ - 1]) {
        if (!m[c - 'a'])
            break;
        m[c - 'a']--;
        i++;
    }
    for (; i >= 0; i--) {
        foreach (j; t[i] - 'a' + 1 .. 26)
            if (m[j]) {
                write(t[0 .. i]);
                write(cast(char)(j + 'a'));
                m[j]--;
                foreach (c, cnt; m)
                    foreach (k; 0 .. cnt)
                        write(cast(char)(c + 'a'));
                writeln();
                return;
            }
        m[s[i] - 'a']++;
    }
    writeln("-1");
}


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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        int _Q, D; get(_Q, D);
        int[] dd;
        foreach (i; 0..10) dd ~= [i * 10 + D, D * 10 + i];
        sort(dd);
        auto DP = new int[](100);
        DP[0] = 1;
        foreach (i; 0..100) if (DP[i] == 0) {
            int solve(int i) {
                if (DP[i] != 0) return DP[i];
                foreach (d; dd) {
                    if (i - d < 0) break;
                    if (solve(i - d) == 1) return DP[i] = 1;
                }
                return DP[i] = -1;
            }
            solve(i);
        }
        foreach (Q; readln.split.to!(int[])) {
            if (Q >= 100) goto ok;
            if (DP[Q] == 1) goto ok;
            writeln("NO");
            continue;
            ok:
            writeln("YES");
        }
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int q, d;
		readf !(" %s %s") (q, d);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		immutable int limit = 100;
		auto f = new bool [limit];
		f[0] = true;
		f[d * 10..$] = true;
		foreach (x; 0..10)
		{
			auto y = x * 10 + d;
			foreach (z; y..limit)
			{
				f[z] |= f[z - y];
			}
		}
		foreach (ref c; a)
		{
			writeln ((c >= limit || f[c]) ? "YES" : "NO");
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[][](t);
	foreach (ti; 0..t)
	{
		auto q = RD!int;
		auto d = RD!int;
		auto a = RDA;

		foreach (e; a)
		{
			if (e >= d*10 || e % d == 0)
			{
				ans[ti] ~= true;
			}
			else
			{
				auto cnt = e / d;
				bool ok;
				foreach (i; 0..cnt)
				{
					auto x = e - i * d;
					if ((x % 10) == d)
					{
						ok = true;
						break;
					}
				}
				ans[ti] ~= ok;
			}
		}
	}

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

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

void theCode(){
    int q;
    q = scan!int;
    ll d = scan;
    bool[100] check;
    for(int el = 1; el < 100; ++el){
        if(el % d == 0){
            check[el] = 1; continue;
        }
        ll tim = 1;
        ll num = el;
        while(num > 0){
            num /= tim;
            ll dig = num % 10;
            if(dig == d){
                check[el] = 1;
                break;
            }
            tim *= 10;
        }
        if(check[el]){
            for(int i = el; i < 100; i += d){
                check[i] = 1;
            }
        }
    }
    auto arr = scanArray;
    foreach(el; arr){
        bool f = 0;
        for(ll i = 1; i < 100; ++i){
            if(el < i){ break; }
            if(el % d == i % d){
                f |= check[to!int(i)];
            }
        }
        if(f){
            writeln("YES");
        }else{
            writeln("NO");
        }
    }
}

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

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

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

void theCode(){
    int q;
    q = scan!int;
    ll d = scan;
    ll[] arr;
    for(int i = 0; i <= d; ++i){
        ll fnum = i*10 +  d;
        if(fnum % d != 0){
            for(int j = 0; j < 14; ++j){
                arr ~= j*d + fnum;
            }
        }
    }
    arr.sort;
    auto seeq = scanArray;
    foreach(el; seeq){
        show(el);
        bool f = 0;
        if(el % d == 0){
            writeln("YES");
            f = 1;
        }
        if(!f){
            foreach(a; arr){
                if(el < a){ break; }
                if(el % d == a % d){
                    writeln("YES");
                    f = 1;
                    break;
                }
            }
        }
        if(!f){
            ll tim = 1;
            ll num = el;
            while(num > 0){
                num /= tim;
                ll dig = num % 10;
                if(dig == d){
                    writeln("YES");
                    f = 1;
                    break;
                }
                tim *= 10;
            }
        }
        if(!f){
            writeln("NO");
        }
    }
}

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

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

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

void theCode(){
    int q;
    q = scan!int;
    ll d = scan;
    auto arr = iota(0L, 10L).map!(a => (10*a + d) % d).array;
    show(arr);
    auto seeq = scanArray;
    foreach(el; seeq){
        show(el);
        bool f = 0;
        for(int i = 0; i <= d; ++i){
            if(el < 10*i + arr[i]){ break; }
            if(el % d == arr[i]){
                writeln("YES");
                f = 1;
                break;
            }
        }
        if(!f){
            ll tim = 1;
            ll num = el;
            while(num > 0){
                num /= tim;
                ll dig = num % 10;
                if(dig == d){
                    writeln("YES");
                    f = 1;
                    break;
                }
                tim *= 10;
            }
        }
        if(!f){
            writeln("NO");
        }
    }
}

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

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

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        int _Q, D; get(_Q, D);
        foreach (Q; readln.split.to!(int[])) {
            if (Q >= 100) goto ok;
            foreach (i; 1..10) if (Q >= D * i && (Q - D * i) % 10 == 0) goto ok;
            if (Q / 10 >= D && Q % 10 >= D) goto ok;
            writeln("NO");
            continue;
            ok:
            writeln("YES");
        }
    }
}


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

void main ()
{
	int rows, cols;
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		int sRow, sCol;
		readf (" %s %s", &sRow, &sCol);
		int lLimit, rLimit;
		readf (" %s %s", &lLimit, &rLimit);
		auto board = new char [] [] (rows + 2, cols + 2);
		foreach (ref line; board)
		{
			line[] = '#';
		}
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf (" %s", &board[row + 1][col + 1]);
			}
		}

		alias Coord = Tuple !(int, q{row}, int, q{col});
		auto deque = new Coord [rows * cols * 4 + 1];
		int qb = rows * cols * 2;
		int qe = rows * cols * 2;
		auto f = new int [] [] (rows + 2, cols + 2);

		void go (int row, int col, int extra, int add)
		{
			debug {writeln (extra, " ", add, " ", row, " ", col);}
			if (board[row][col] != '.')
			{
				if (board[row][col] != '+' ||
				    f[row][col] <= extra + add)
				{
					return;
				}
			}
			if (add)
			{
				deque[qe] = Coord (row, col);
				qe += 1;
			}
			else
			{
				qb -= 1;
				deque[qb] = Coord (row, col);
			}
			board[row][col] = '+';
			f[row][col] = extra + add;
		}

		go (sRow, sCol, 0, 0);

		while (qb < qe)
		{
			int row = deque[qb].row;
			int col = deque[qb].col;
			int extra = f[row][col];
			qb += 1;

			go (row - 1, col, extra, 0);
			go (row + 1, col, extra, 0);

			{
				int nRow = row;
				int nCol = col + 1;
				int add = (nCol <= sCol);
				int rSteps = max (0, nCol - sCol) +
				    extra + add;
				if (rSteps <= rLimit)
				{
					go (nRow, nCol, extra, add);
				}
			}

			{
				int nRow = row;
				int nCol = col - 1;
				int add = (sCol <= nCol);
				int lSteps = max (0, sCol - nCol) +
				    extra + add;
				if (lSteps <= lLimit)
				{
					go (nRow, nCol, extra, add);
				}
			}
		}

		debug {writefln ("%-(%s\n%)", board);}
		writeln (board.map !(line => line.count ('+')).sum);
		break;
	}
}

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

immutable int INF = 10L ^^ 9 + 23;

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

    int r, c;
    readf("%s %s", &r, &c);
    readln;
    --r, --c;

    int x, y;
    readf("%s %s", &x, &y);
    readln;

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

    auto vis = new int[][][] (n, m, 2);
    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            vis[i][j].fill([-1, -1]);
        }
    }

    int bfs(int sx, int sy, int mvle, int mvr) {
        auto q = make!(DList!(Tuple!(int, int)));

        vis[sx][sy] = [mvle, mvr];
        q.insertFront(tuple(sx, sy));

        auto dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];
        auto qback = (int a, int b) => q.insertBack(tuple(a, b));
        auto qfront = (int a, int b) => q.insertFront(tuple(a, b));
        auto qfunc = [qfront, qfront, qback, qback];
        auto rcchg = [(int a, int b) => [a, b], (int a, int b) => [a, b],
                      (int a, int b) => [a-1, b], (int a, int b) => [a, b-1]];

        int ans = 0;
        while (! q.empty()) {
            auto t = q.front;
            q.removeFront();

            debug { writeln(t, ' ', vis[t[0]][t[1]]); }
            ++ans;
            auto cx = t[0], cy = t[1];
            auto cle = vis[cx][cy][0], cr = vis[cx][cy][1];

            foreach (i; 0 .. 4) {
                int nx = cx + dirs[i][0], ny = cy + dirs[i][1];
                if (nx < 0 || nx >= n || ny < 0 || ny >= m) { continue; }
                if (arr[nx][ny] == '*') { continue; }

                if (vis[nx][ny][0] != -1) { continue; }

                auto nchg = rcchg[i](cle, cr);
                if (nchg[0] < 0 || nchg[1] < 0) { continue; }

                vis[nx][ny] = nchg;
                qfunc[i](nx, ny);
            }
        }

        return ans;
    }

    bfs(r, c, x, y).writeln;
}

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

void main ()
{
	int rows, cols;
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		int sRow, sCol;
		readf (" %s %s", &sRow, &sCol);
		int lLimit, rLimit;
		readf (" %s %s", &lLimit, &rLimit);
		auto board = new char [] [] (rows + 2, cols + 2);
		foreach (ref line; board)
		{
			line[] = '#';
		}
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf (" %s", &board[row + 1][col + 1]);
			}
		}

		alias Coord = Tuple !(int, q{row}, int, q{col});
		auto deque = new Coord [rows * cols * 2 + 1];
		int qb = rows * cols;
		int qe = rows * cols;
		auto f = new int [] [] (rows + 2, cols + 2);

		void go (int row, int col, int extra, int add)
		{
			if (board[row][col] != '.')
			{
				return;
			}
			if (add)
			{
				deque[qe] = Coord (row, col);
				qe += 1;
			}
			else
			{
				qb -= 1;
				deque[qb] = Coord (row, col);
			}
			board[row][col] = '+';
			f[row][col] = extra + add;
		}

		qb -= 1;
		deque[qb] = Coord (sRow, sCol);
		board[sRow][sCol] = '+';

		while (qb < qe)
		{
			int row = deque[qb].row;
			int col = deque[qb].col;
			int extra = f[row][col];
			qb += 1;

			go (row - 1, col, extra, 0);
			go (row + 1, col, extra, 0);

			{
				int nRow = row;
				int nCol = col + 1;
				int add = (nCol <= sCol);
				int rSteps = max (0, nCol - sCol) +
				    extra + add;
				if (rSteps <= rLimit)
				{
					go (nRow, nCol, extra, add);
				}
			}

			{
				int nRow = row;
				int nCol = col - 1;
				int add = (sCol <= nCol);
				int lSteps = max (0, sCol - nCol) +
				    extra + add;
				if (lSteps <= lLimit)
				{
					go (nRow, nCol, extra, add);
				}
			}
		}

		debug {writefln ("%-(%s\n%)", board);}
		writeln (board.map !(line => line.count ('+')).sum);
	}
}


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 = 10^^9 + 7;
alias Mint = ModInt!MO;

int N;
Mint[] A;
int[] U, V;

int[][] G;
int[] par;
Mint[][] dp, DP;

void dfs(int u, int p) {
  par[u] = p;
  foreach (v; G[u]) {
    if (v != p) {
      dfs(v, u);
    }
  }
  auto sums = new Mint[2];
  foreach (v; G[u]) {
    if (v != p) {
      // add dp[v]
      sums[] += dp[v][];
    }
  }
  // calc dp[u]
  dp[u][0] = sums[1];
  dp[u][1] = 1 + sums[0];
}

void DFS(int u, int p) {
  auto sums = new Mint[2];
  foreach (v; G[u]) {
    if (v != p) {
      // add dp[v]
      sums[] += dp[v][];
    }
  }
  if (p != -1) {
    // add DP[u]
    sums[] += DP[u][];
  }
  foreach (v; G[u]) {
    if (v != p) {
      // calc DP[v], removing dp[v]
      sums[] -= dp[v][];
      DP[v][0] = sums[1];
      DP[v][1] = 1 + sums[0];
      sums[] += dp[v][];
    }
  }
  foreach (v; G[u]) {
    if (v != p) {
      DFS(v, u);
    }
  }
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      A = new Mint[N];
      foreach (u; 0 .. N) {
        A[u] = Mint(readLong());
      }
      U = new int[N - 1];
      V = new int[N - 1];
      foreach (i; 0 .. N - 1) {
        U[i] = readInt() - 1;
        V[i] = readInt() - 1;
      }

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[U[i]] ~= V[i];
        G[V[i]] ~= U[i];
      }
      par = new int[N];
      dp = new Mint[][](N, 2);
      DP = new Mint[][](N, 2);
      const rt = 0;
      dfs(rt, -1);
      DFS(rt, -1);
      debug {
        writeln("rt = ", rt);
        writeln("dp = ", dp);
        writeln("DP = ", DP);
      }

      Mint ans;
      foreach (u; 0 .. N) {
        auto sums = new Mint[2];
        Mint[][] seq;
        foreach (v; G[u]) {
          if (v != par[u]) {
            // add dp[v]
            sums[] += dp[v][];
            seq ~= dp[v];
          }
        }
        if (u != rt) {
          // add DP[u]
          sums[] += DP[u][];
          seq ~= DP[u];
        }
        // rooted at u
        Mint sum;
        sum += 1 * 1;
        sum += 1 * sums[0];
        sum += 1 * sums[1];
        foreach (j; 0 .. seq.length) {
          sum += seq[j][0] * 1;
          sum -= seq[j][1] * 1;
          sum += seq[j][0] * (sums[0] - seq[j][0]);
          sum += seq[j][0] * (sums[1] - seq[j][1]);
          sum -= seq[j][1] * (sums[0] - seq[j][0]);
          sum -= seq[j][1] * (sums[1] - seq[j][1]);
        }
        debug {
          writeln(u, ": ", sum);
        }
        ans += A[u] * sum;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

const mod = 10^^9+7;
alias mint = FactorRing!mod;

void main()
{
  int n; readV(n);
  int[] w; readA(n, w);

  auto g = Graph!int(n);
  foreach (_; 0..n-1) {
    int u, v; readV(u, v);
    g.addEdgeB(--u, --v);
  }
  auto t = makeTree(g).rootify(0);

  auto ei = new int[int][](n);
  foreach (u; 0..n)
    foreach (int i, v; g[u]) ei[u][v] = i;

  auto vc = new VC[][](n), vct = new VC[](n);
  foreach (u; 0..n) vc[u] = new VC[](g[u].length);

  auto q = DList!int([0]), rt = new int[](0);
  while (!q.empty) {
    auto u = q.front; q.removeFront();
    rt ~= u;
    foreach (v; t[u])
      if (v != t.parent[u])
        q.insertBack(v);
  }
  rt = rt[1..$];

  foreach_reverse (u; rt) {
    auto p = t.parent[u];
    auto vci = VC(1, 0);
    foreach (i, v; g[u])
      if (v != p)
        vci = vci + vc[u][i].inv;
    vc[p][ei[p][u]] = vci;
  }

  foreach (u; 0..n)
    foreach (vci; vc[u])
      vct[u] = vct[u] + vci;

  foreach (u; rt) {
    auto p = t.parent[u];
    vc[u][ei[u][p]] = VC(1, 0) + (vct[p] - vc[p][ei[p][u]]).inv;
    vct[u] = vct[u] + vc[u][ei[u][p]];
  }

  auto ans = mint(0);
  foreach (u; 0..n) {
    auto vcti = vct[u];
    auto eo = mint(1);
    eo += vcti.o + vcti.e;
    eo += vcti.o - vcti.e;
    foreach (i, v; g[u]) {
      auto vci = vc[u][i], rvci = vcti - vci;
      eo += (mint(vci.o) - vci.e) * (rvci.o + rvci.e);
    }
    ans += eo * w[u];
  }

  writeln(ans);
}

struct VC
{
  int e, o;
  auto inv() { return VC(o, e); }
  auto opBinary(string op: "+")(VC a) { return VC(e+a.e, o+a.o); }
  auto opBinary(string op: "-")(VC a) { return VC(e-a.e, o-a.o); }
}

struct Graph(N = int)
{
  alias Node = N;
  Node n;
  Node[][] g;
  alias g this;
  this(Node n) { this.n = n; g = new Node[][](n); }
  void addEdge(Node u, Node v) { g[u] ~= v; }
  void addEdgeB(Node u, Node v) { g[u] ~= v; g[v] ~= u; }
}

struct Tree(Graph)
{
  import std.algorithm, std.container;
  alias Node = Graph.Node;
  Graph g;
  alias g this;
  Node root;
  Node[] parent;
  int[] size, depth;

  this(ref Graph g) { this.g = g; this.n = g.n; }

  ref auto rootify(Node r)
  {
    this.root = r;

    parent = new Node[](g.n);
    depth = new int[](g.n);
    depth[] = -1;

    struct UP { Node u, p; }
    auto st1 = SList!UP(UP(r, r));
    auto st2 = SList!UP();
    while (!st1.empty) {
      auto up = st1.front, u = up.u, p = up.p; st1.removeFront();

      parent[u] = p;
      depth[u] = depth[p] + 1;

      foreach (v; g[u])
        if (v != p) {
          st1.insertFront(UP(v, u));
          st2.insertFront(UP(v, u));
        }
    }

    size = new int[](g.n);
    size[] = 1;

    while (!st2.empty) {
      auto up = st2.front, u = up.u, p = up.p; st2.removeFront();
      size[p] += size[u];
    }

    return this;
  }

  auto children(Node u) { return g[u].filter!(v => v != parent[u]); }
}
ref auto makeTree(Graph)(ref Graph g) { return Tree!Graph(g); }

struct FactorRing(int m, bool pos = false)
{
  version(BigEndian) union { long vl; struct { int vi2; int vi; } } else union { long vl; int vi; }
  alias FR = FactorRing!(m, pos);
  @property static init() { return FR(0); }
  @property int value() { return vi; }
  @property void value(int v) { vi = mod(v); }
  alias value this;

  this(int v) { vi = v; }
  this(int v, bool runMod) { vi = runMod ? mod(v) : v; }
  this(long v) { vi = mod(v); }

  ref auto opAssign(int v) { vi = v; return this; }

  pure auto mod(int v) const { static if (pos) return v%m; else return (v%m+m)%m; }
  pure auto mod(long v) const { static if (pos) return cast(int)(v%m); else return cast(int)((v%m+m)%m); }

  static if (!pos) pure ref auto opUnary(string op: "-")() { return FR(mod(-vi)); }

  static if (m < int.max / 2) {
    pure ref auto opBinary(string op)(int r) if (op == "+" || op == "-") { return FR(mod(mixin("vi"~op~"r"))); }
    ref auto opOpAssign(string op)(int r) if (op == "+" || op == "-") { vi = mod(mixin("vi"~op~"r")); return this; }
  } else {
    pure ref auto opBinary(string op)(int r) if (op == "+" || op == "-") { return FR(mod(mixin("vl"~op~"r"))); }
    ref auto opOpAssign(string op)(int r) if (op == "+" || op == "-") { vi = mod(mixin("vl"~op~"r")); return this; }
  }
  pure ref auto opBinary(string op: "*")(int r) { return FR(mod(vl*r)); }
  ref auto opOpAssign(string op: "*")(int r) { vi = mod(vl*r); return this; }

  pure ref auto opBinary(string op)(ref FR r) if (op == "+" || op == "-" || op == "*") { return opBinary!op(r.vi); }
  ref auto opOpAssign(string op)(ref FR r) if (op == "+" || op == "-" || op == "*") { return opOpAssign!op(r.vi); }
}


import std.stdio;

void main ()
{
	readln;
	int n;
	while (readf !(" %s") (n) > 0)
	{
		for (int w = 3; ; w += w + 1)
		{
			if (n % w == 0)
			{
				writeln (n / w);
				break;
			}
		}
	}
}

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 N = readln.chomp.to!long;
        long x = 1;
        foreach (k; 1..34) {
            x += 1L<<k;
            if (N%x == 0) {
                writeln(N/x);
                break;
            }
        }
    }
}

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;
		long a = 3;
		while (true)
		{
			if (n % a == 0)
			{
				ans[ti] = n / a;
				break;
			}
			a <<= 1;
			++a;
		}
	}

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


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

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

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

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

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

int P;
int N;
int[] X;

void main(string[] args) {
	try {
	for (; ; ) {
		P = readInt;
		N = readInt;
		X = new int[N];
		foreach (i; 0 .. N) {
			X[i] = readInt;
		}

		int ans = -1;
		bool[] app = new bool[P];
		foreach (i; 0 .. N) {
			const key = X[i] % P;
			if (app[key]) {
				ans = i + 1;
				break;
			}
			app[key] = true;
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}

import std.stdio;
import std.string;
import std.bigint;
import std.array;
import std.ascii;
import std.math;
import std.numeric;
import std.algorithm;
import std.container;
import core.bitop;
import std.conv;

alias Int = long;

void main() {
  int p, n;
  readf(" %s", &p);
  readf(" %s", &n);
  auto list = new bool[300 + 1];
  list[] = false;
  foreach ( i; 0 .. n ) {
    Int x;
    readf(" %s", &x);
    if ( list[x % p] ) {
      writeln(i + 1);
      return;
    }
    list[x % p] = true;
  }
  writeln(-1);
}

//http://codeforces.com/contest/447/problem/A

import std.stdio;

void main(){
  uint p,n;
  readf("%s ",&p);
  readf("%s ",&n);
  uint[] l = new uint[n];
  for(uint i = 0; i < n; i++){
    readf("%s ",&l[i]);
  }
  writefln("%s",run(p,l));
}

long run(uint n, uint[] l){
  bool[] mt = new bool[n];
  for(uint i = 0; i < n; i++){
    mt[i] = false;
  }

  uint j = 0;
  foreach(uint x; l){
    uint h = x % n;
    if (mt[h] == false) {
      mt[h] = true;
    } else {
      return j + 1;
    }
    j++;
  }

  return -1;
}

// TEST CASE AREA
// void test_case(){
//   uint[][] rs;
//   rs ~= [run(10,[0,21,53,41,53]),4];
//   rs ~= [run(5,[0,1,2,3,4]),-1];
//
//   array_assert(rs);
// }
//
// void array_assert(uint[][] rs){
//   uint i = 1;
//   bool failed = false;
//   foreach(uint[] r;rs){
//     if(r[0] != r[1]){
//       failed = true;
//       writefln("%s Failed %s is NOT %s",i,r[0],r[1]);
//     }
//     i++;
//   }
//
//   if(!failed){
//     writefln("OK");
//   }
// }

import std.stdio;
import std.c.stdio;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.regex;
import std.typecons;

int P, N;
int[] X;
void main() {
    scanf("%d %d\n", &P, &N);

    int h(int x) {
        return x % P;
    }

    X = new int[P];
    X[] = -1;
    foreach (i; 0 .. N) {
        int x;
        scanf("%d\n", &x);
        int y = h(x);
        if (X[y] >= 0) {
            writeln(i + 1);
            return;
        } else {
            X[y] = x;
        }
    }
    writeln(-1);
}

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

void main() {
  int p, n;
  readf("%s %s\n", &p, &n);
  auto s = redBlackTree!int();
  int x, i, c=1;
  for (i=0; i<n; i++) {
    x = (readln.strip.to!int) % p;
    if (!(x in s)) {
      c++;
    } else break;
    s.insert(x);
  }
  if (i==n)
    writeln(-1);
  else
    writeln(c);
}

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

void main() {
  int p, n;
  readf("%s %s\n", &p, &n);
  auto s = redBlackTree!int();
  int x, i;
  for (i=0; i<n; i++) {
    x = (readln.strip.to!int) % p;
    if (x in s) {
      i++;
      break;
    }
    s.insert(x);
  }
  if (i==n)
    writeln(-1);
  else
    writeln(i);
}


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 ad = readln.split.to!(long[]);
        auto A = ad[0];
        auto B = ad[1];
        auto C = ad[2];
        auto D = ad[3];

        if (A <= B) {
            writeln(B);
            continue;
        }

        auto e = C - D;
        if (e <= 0) {
            writeln(-1);
            continue;
        }

        A -= B;
        auto f = (A + e - 1) / e;
        writeln(B + C * f);
    }
}

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 a = RD;
		auto b = RD;
		auto c = RD;
		auto d = RD;

		a -= b;
		ans[ti] = b;
		if (a <= 0) continue;

		auto e = c - d;
		if (e <= 0)
		{
			ans[ti] = -1;
			continue;
		}

		ans[ti] += c * ((a+e-1) / e);
	}

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


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 N = readln.chomp.to!int;
    auto S = readln.chomp;

    auto dp = new int[][](N, 3);
    dp[0][0] = dp[0][1] = 1;

    foreach (i; 1..N) {
        bool same = (S[i] == S[i-1]);
        dp[i][0] = dp[i-1][0] + !same;
        dp[i][1] = max(dp[i-1][0]+same, dp[i-1][1]+!same);
        dp[i][2] = max(dp[i-1][1]+same, dp[i-1][2]+!same);
    }

    int ans = 0;
    foreach (i; 0..N) foreach (j; 0..3) ans = max(ans, dp[i][j]);
    writeln(ans);
}

import std.algorithm, std.range, std.stdio;
void main () {
	readln;
	auto s = readln, n = s.length - 1, res = (n - 1).iota.map !(i => s[i] != s[i + 1]).sum;
	n.min (res + 3).writeln;
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln ();
		auto s = readln.strip;
		auto res = (n - 1).iota.map !(i => s[i] != s[i + 1]).sum;
		res = min (res + 3, n);
		writeln (res);
	}
}


import std.algorithm;
import std.conv;
import std.math;
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);
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		writeln (sum (a, 0L) + sum (b, 0L) - maxElement (b));
	}
}

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) {
    long n = readln.strip.to!long;
    auto a = readln.splitter.map!(to!long).array;
    auto b = readln.splitter.map!(to!long).array;
    writeln(a.sum + b.sum - b.maxElement);
  }
}

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 = readarray!long;
    auto B = readarray!long;

    auto r = B.reduce!max;
    writeln(A.reduce!"a+b" + B.reduce!"a+b" - r);
}


import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    int N; scanf("%d\n", &N);
    auto D = readln.chomp.split(" ").map!(to!int).array;
    auto X = new int[N];
    foreach (int i, j; D) {
        X[j - 1] = i + 1;
    }
    writefln("%(%s %)", X);
}

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

void main() {
  int n = readln.chomp.to!int;
  auto p = readln.chomp.split.map!(to!int);

  auto ans = new int[n];

  for (int i = 0; i < n; i++) {
    ans[p[i]-1] = i + 1;
  }

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

import std.stdio;

/*
 * pi: numero della persona che ha dato il regalo alla persona
 * i. Potrebbe essere che pi == i e inoltre si sa che pi != pk per
 * ogni i != k.
 */
int[] gifters(int[] pis, int n) {
  int[] gifters;
  gifters.length = n;
  for (int i=0; i < n; i++) {
    gifters[(pis[i] - 1)] = i + 1;
  }
  return gifters;
}

void print_gifters(int[] gifters) {
  for (int i = 0; i < gifters.length; i++) {
    if (i == 0)
      writef("%s", gifters[i]);
    else
      writef(" %s", gifters[i]);
  }
}

int main() {
  int n, pi;
  readf("%s", &n);
  int[] pis;
  pis.length = n;
  for (int i=0; i < n; i++) {
    readf(" %s", &pi);
    pis[i] = pi;
  }
  print_gifters(gifters(pis, n));
  return 0;
}

import std.stdio;
import std.string;
import core.stdc.stdio;
import std.math;
import std.algorithm;

class Friend
{
	public int f;
	public int p;
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	Friend[] friends;
	friends.length = n;
	foreach (int i; 0..n)
	{
		friends[i] = new Friend();
		scanf("%d", &(friends[i].f));
		friends[i].p = i;
	}
	sort!("a.f < b.f", SwapStrategy.stable)(friends);
	foreach (int i; 0..n)
	{
		printf((i < n-1) ? "%d " : "%d", (friends[i].p + 1));
	}
	return 0;
}


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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.splitter.map !(to !(long)).array;
		sort (s);

		long [] v;
		v.reserve (n - 1);
		foreach (i; 1..n)
		{
			v ~= s[i] - s[i - 1];
		}
		sort (v);
		debug {writeln (v);}

		long [] c;
		c.reserve (n);
		c ~= 0;
		foreach (i; 1..n)
		{
			c ~= c[$ - 1] + v[i - 1];
		}
		debug {writeln (c);}

		long solve (long d)
		{
			int lo = 0;
			int hi = n - 1;
			while (lo < hi)
			{
				int me = (lo + hi) / 2;
				if (v[me] <= d)
				{
					lo = me + 1;
				}
				else
				{
					hi = me;
				}
			}
			debug {writeln (lo, " ", d, " ", n - 1 - lo);}
			return c[lo] + (d + 1) * (n - lo);
		}

		int q;
		readf (" %s", &q);
		long [] res;
		res.reserve (q);
		foreach (j; 0..q)
		{
			long l, r;
			readf (" %s %s", &l, &r);
			long d = r - l;
			res ~= solve (d);
		}
		writefln ("%(%s %)", res);
	}
}

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

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

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

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

enum INF = 3 * 10L^^18;

int N;
long[] S;
int Q;
long[] L, R;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      S = new long[N];
      foreach (i; 0 .. N) {
        S[i] = readLong();
      }
      Q = readInt();
      L = new long[Q];
      R = new long[Q];
      foreach (q; 0 .. Q) {
        L[q] = readLong();
        R[q] = readLong();
      }

      S.sort;

      auto ds = new long[N];
      foreach (i; 0 .. N - 1) {
        ds[i] = S[i + 1] - S[i];
      }
      ds[N - 1] = INF;
      ds.sort;

      auto dsSum = new long[N + 1];
      foreach (i; 0 .. N) {
        dsSum[i + 1] = dsSum[i] + ds[i];
      }

      auto ans = new long[Q];
      foreach (q; 0 .. Q) {
        const pos = ds.lowerBound(R[q] - L[q] + 1);
        ans[q] = dsSum[pos] + (R[q] - L[q] + 1) * (N - pos);
      }
      foreach (q; 0 .. Q) {
        if (q > 0) {
          write(" ");
        }
        write(ans[q]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


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

const long INF = 1L << 59;

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

    auto zero = N.iota.filter!(i => A[i] == 0).map!(i => tuple(i+1, A[i])).array;
    auto minus = N.iota.filter!(i => A[i] < 0).map!(i => tuple(i+1, A[i])).array;
    auto plus = N.iota.filter!(i => A[i] > 0).map!(i => tuple(i+1, A[i])).array;
    minus.sort!("a[1] < b[1]")();
    int cnt = N - 1;
    bool nozero = false;

    if (minus.length % 2 == 1) {
        if (zero.length > 0) {
            zero ~= minus.back;
            minus.popBack;
            foreach (i; 0..zero.length.to!int-1) {
                writeln(1, " ", zero[i][0], " ", zero[i+1][0]);
                cnt--;
            }
            if (cnt > 0) {
                writeln(2, " ", zero.back[0]);
                --cnt;
            }
            nozero = true;
        } else {
            writeln(2, " ", minus.back[0]);
            minus.popBack;
            --cnt;
        }
    } else if (zero.length > 0) {
        foreach (i; 0..zero.length.to!int-1) {
            writeln(1, " ", zero[i][0], " ", zero[i+1][0]);
            cnt--;
        }
        if (cnt > 0) {
            writeln(2, " ", zero.back[0]);
            --cnt;
        }
        nozero = true;
    }

    auto rest = minus ~ plus;
    int len = rest.length.to!int;

    while (cnt > 0) {
        int x = rest.back[0];
        rest.popBack;
        int y = rest.back[0];
        writeln(1, " ", x, " ", y);
        cnt--;
    }
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; rd(n);
  auto a=readln.split.to!(int[]);

  auto count=reduce!((r, e)=>r+(e==0 ? 1 : 0))(0, a);
  auto minus=reduce!((r, e)=>r+(e<0 ? 1 : 0))(0, a);
  int[][] ans;
  if(count==0){
    if(minus%2==0){
      for(int i=1; i<n; i++){
        ans~=[1, i, i+1];
      }
    }else{
      int pos=-1;
      foreach(int i, e; a){
        if(e<0){
          if(pos==-1){
            pos=i;
          }else{
            if(a[pos]<e){
              pos=i;
            }
          }
        }
      }
      writeln(2, " ", pos+1);
      if(pos==0){
        for(int i=2; i<n; i++){
          ans~=[1, i, i+1];
        }
      }else if(pos==n-1){
        for(int i=1; i+1<n; i++){
          ans~=[1, i, i+1];
        }
      }else{
        for(int i=1; i<n; i++){
          if(i+1==pos+1){
            ans~=[1, i, i+2];
            i++;
          }else{
            ans~=[1, i, i+1];
          }
        }
      }
    }
  }else{
    int cnt=0;
    int zeropos=-1;
    if(count>=2){
      int last=-1;
      foreach(int i, e; a){ // 最右の0に寄せる
        if(e==0){
          if(last>=0){
            writeln(1, " ", last+1, " ", i+1);
            cnt++;
          }
          last=i;
          zeropos=i;
        }
      }
    }
    for(int i=n-1; i>=0; i--){
      if(a[i]==0){
        zeropos=i;
        break;
      }
    }
    int pos=-1;
    if(minus&1){
      foreach(int i, e; a){
        if(e<0){
          if(pos==-1){
            pos=i;
          }else{
            if(a[pos]<e){
              pos=i;
            }
          }
        }
      }
      writeln(1, " ", pos+1, " ", zeropos+1);
      cnt++;
    }
    if(cnt+1<n){
      writeln(2, " ", zeropos+1);
    }
    int last=-1;
    foreach(int i, e; a){
      if(e==0 || i==pos || i==zeropos) continue;
      if(last>=0){
        ans~=[1, last+1, i+1];
      }
      last=i;
    }
  }

  foreach(aa; ans){
    writefln("%(%s %)", aa);
  }

}
void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

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

const long INF = 1L << 59;

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

    auto zero = N.iota.filter!(i => A[i] == 0).map!(i => tuple(i+1, A[i])).array;
    auto minus = N.iota.filter!(i => A[i] < 0).map!(i => tuple(i+1, A[i])).array;
    auto plus = N.iota.filter!(i => A[i] > 0).map!(i => tuple(i+1, A[i])).array;
    minus.sort!("a[1] < b[1]")();
    int cnt = N - 1;
    bool nozero = false;

    if (minus.length % 2 == 1) {
        writeln(2, " ", minus.back[0]);
        minus.popBack;
        cnt--;
    } else if (zero.length > 0) {
        foreach (i; 0..zero.length.to!int-1) {
            writeln(1, " ", zero[i][0], " ", zero[i+1][0]);
            cnt--;
        }
        if (cnt > 0) {
            writeln(2, " ", zero.back[0]);
            --cnt;
        }
        nozero = true;
    }

    auto rest = minus ~ plus;
    if (!nozero) rest ~= zero;

    foreach (i; 0..rest.length.to!int-1) {
        int x = rest.back[0];
        rest.popBack;
        int y = rest.back[0];
        writeln(1, " ", x, " ", y);
        cnt--;
    }
}


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

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

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

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

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

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

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

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

void main()
{
    int T; get(T); while (T--) {
        int N; get(N);
        int[] AA; get(AA);

        auto res = new int[](N);
        void solve(int l, int r, int d) {
            if (l == r) return;

            int p, max_a;
            foreach (i; l..r) if (AA[i] > max_a) {
                max_a = AA[i];
                p = i;
            }
            res[p] = d;
            solve(l, p, d + 1);
            solve(p + 1, r, d + 1);
        }
        solve(0, N, 0);
        writefln!"%(%d %)"(res);
    }
}

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;
		auto d = new int [n];

		void build (int lo, int hi, int depth)
		{
			if (lo >= hi)
			{
				return;
			}
			auto me = hi - maxPos (a[lo..hi]).length.to !(int);
			d[me] = depth;
			build (lo, me, depth + 1);
			build (me + 1, hi, depth + 1);
		}

		build (0, n, 0);
		writefln !("%(%s %)") (d);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		void dfs(int pos, int depth)
		{
			ans[ti][pos] = depth;
			auto x = a[pos];
			{
				int j = -1, y;
				foreach_reverse (i; 0..pos)
				{
					if (a[i] > x) break;
					if (a[i] > y)
					{
						j = i;
						y = a[j];
					}
				}
				if (j != -1)
					dfs(j, depth+1);
			}
			{
				int j = -1, y;
				foreach (i; pos+1..n)
				{
					if (a[i] > x) break;
					if (a[i] > y)
					{
						j = i;
						y = a[j];
					}
				}
				if (j != -1)
					dfs(j, depth+1);
			}
		}
		int p;
		foreach (i; 0..n)
		{
			if (a[i] > a[p])
				p = i;
		}
		dfs(p, 0);
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}