import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

const long mod = 1_000_000_007;

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int n = read.to!int;
	int m = read.to!int;
	int h = read.to!int;

	int[] as;
	foreach(j; 0 .. m) as ~= read.to!int;

	int[] bs;
	foreach(i; 0 .. n) bs ~= read.to!int;

	int[][] cs = new int[][](n, m);
	foreach(i; 0 .. n) foreach(j; 0 .. m) cs[i][j] = read.to!int;

	int[][] ans = new int[][](n, m);

	X[] xs;
	foreach(i; 0 .. n) xs ~= new X(true, i, bs[i]);
	foreach(j; 0 .. m) xs ~= new X(false, j, as[j]);

	xs.sort!"a.value > b.value"();

	int[] has = new int[](m);
	int[] hbs = new int[](n);

	foreach(x; xs){
		if(x.isRow){
			int i = x.number;
			int v = x.value;
			if(hbs[i] == v) continue;
			foreach(j; 0 .. m) if(as[j] >= v && cs[i][j]){
				cs[i][j] = 0;
				ans[i][j] = v;
				if(hbs[i] < v) hbs[i] = v;
				if(has[j] < v) has[j] = v;
				break;
			}
		}
		else{
			int j = x.number;
			int v = x.value;
			if(has[j] == v) continue;
			foreach(i; 0 .. n) if(bs[i] >= v && cs[i][j]){
				cs[i][j] = 0;
				ans[i][j] = v;
				if(hbs[i] < v) hbs[i] = v;
				if(has[j] < v) has[j] = v;
				break;
			}
		}
	}

	foreach(i; 0 .. n) foreach(j; 0 .. m) if(cs[i][j] && ! ans[i][j]) ans[i][j] = 1;

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

}

class X{
	bool isRow;
	int number;
	int value;
	this(bool isRow, int number, int value){
		this.isRow = isRow;
		this.number = number;
		this.value = value;
	}
}

/*

greedy.
taller column or row will be dealt earlier, then shorter ones.

at end, fill unused cells with height 1.

*/

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto H = s[2];
    auto A = readln.split.map!(to!int).array;
    auto B = readln.split.map!(to!int).array;
    auto C = N.iota.map!(_ => readln.split.map!(to!int).array).array;

    auto ans = new int[][](N, M);

    foreach (i; 0..N) {
        foreach (j; 0..M) {
            if (C[i][j] == 0) continue;
            ans[i][j] = min(A[j], B[i]);
        }
    }

    ans.each!(a => a.map!(to!string).join(" ").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; }
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; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
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!uint;
	auto M = RD!uint;
	auto H = RD;
	auto a = RDR.ARR;
	auto b = RDR.ARR;
	auto aa = a.dup;
	auto bb = b.dup;
	auto c = new long[][](N, M);
	auto ans = new long[][](N, M);
	foreach (i; 0..N)
	{
		c[i] = RDR.ARR;
		ans[i] = c[i].dup;
	}

	long cnt_a, cnt_b;
	foreach (x; 0..M)
	{
		if (a[x] != 0) ++cnt_a;
	}
	foreach (y; 0..N)
	{
		if (b[y] != 0) ++cnt_b;
	}

	long last_ca, last_cb;
	while (cnt_a != 0 || cnt_b != 0)
	{
		foreach (x; 0..M)
		{
			if (a[x] == 0) continue;

			long cnt;
			uint last;
			foreach (y; 0..N)
			{
				if (c[y][x] == 1)
				{
					++cnt;
					last = y;
				}
				else if (ans[y][x] == a[x])
				{
					foreach (y2; 0..N)
					{
						c[y2][x] = 0;
					}
					a[x] = 0;
					--cnt_a;
					cnt = -1;
					break;
				}
			}
			if (cnt == 1)
			{
				ans[last][x] = a[x];
				c[last][x] = 0;
				a[x] = 0;
				--cnt_a;
			}
			else if (cnt == 0)
			{
				foreach (y; 0..N)
				{
					if (ans[y][x] == 1)
					{
						ans[y][x] = a[x];
						c[y][x] = 0;
						a[x] = 0;
						--cnt_a;
						break;
					}
				}
			}
		}
		foreach (y; 0..N)
		{
			if (b[y] == 0) continue;

			long cnt;
			uint last;
			foreach (x; 0..M)
			{
				if (c[y][x] == 1)
				{
					++cnt;
					last = x;
				}
				else if (ans[y][x] == b[y])
				{
					foreach (x2; 0..M)
					{
						c[y][x2] = 0;
					}
					b[y] = 0;
					--cnt_b;
					cnt = -1;
					break;
				}
			}
			if (cnt == 1)
			{
				ans[y][last] = b[y];
				c[y][last] = 0;
				b[y] = 0;
				--cnt_b;
			}
			else if (cnt == 0)
			{
				foreach (x; 0..M)
				{
					if (ans[y][x] == 1)
					{
						ans[y][x] = b[y];
						c[y][x] = 0;
						b[y] = 0;
						--cnt_b;
						break;
					}
				}
			}
		}
		if (cnt_a == last_ca && cnt_b == last_cb)
			break;
		last_ca = cnt_a;
		last_cb = cnt_b;
	}

	debug writeln(a);
	debug writeln(b);
	//while (cnt_a != 0 || cnt_b != 0)
	{
		foreach (x; 0..M)
		{
			if (a[x] != 0)
			{
				foreach (y; 0..N)
				{
					if (ans[y][x] == 1 && bb[y] >= a[x])
					{
						ans[y][x] = a[x];
						a[x] = 0;
						--cnt_a;
						break;
					}
				}
			}
		}
		foreach (y; 0..N)
		{
			if (b[y] != 0)
			{
				foreach (x; 0..M)
				{
					if (ans[y][x] == 1 && aa[x] >= b[y])
					{
						ans[y][x] = b[y];
						b[y] = 0;
						--cnt_b;
						break;
					}
				}
			}
		}
	}

	debug writeln(a);
	debug writeln(b);

	foreach (y; 0..N)
	{
		write(ans[y][0]);
		foreach (x; 1..M)
		{
			write(" ", ans[y][x]);
		}
		writeln();
	}

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


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

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

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

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

void bAdd(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    bit[x] += val;
  }
}

// sum of [0, pos)
T bSum(T)(T[] bit, int pos)
in {
  assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold");
}
do {
  T ret = 0;
  for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
    ret += bit[x];
  }
  return ret;
}

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

      const lim = A.maxElement + 1;
      auto poss = new RedBlackTree!int[lim];
      foreach (a; 0 .. lim) {
        poss[a] = new RedBlackTree!int;
      }
      foreach (i; 0 .. N) {
        poss[A[i]].insert(i);
      }

      auto bit = new int[N];
      foreach (i; 0 .. N) {
        bit.bAdd(i, +1);
      }

      long ans;
      int cur;
      foreach (a; 0 .. lim) {
        for (; !poss[a].empty; ) {
          auto ran = poss[a].upperBound(cur - 1);
          if (ran.empty) {
            ans += bit.bSum(N) - bit.bSum(cur);
            cur = 0;
            ran = poss[a][];
          }
          const i = ran.front;
          poss[a].removeKey(i);
          ans += bit.bSum(i) - bit.bSum(cur);
          ans += 1;
          bit.bAdd(i, -1);
          cur = i;
          debug {
            writeln("cur = ", cur, ", ans = ", ans);
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;
    auto B = new int[][](100010);

    if (N == 1) {
        writeln(1);
        return;
    }

    foreach (i, a; A.enumerate) {
        B[a] ~= i.to!int;
    }

    auto C = A.dup;
    C.sort();
    C = C.uniq().array;

    int p = -1;
    long ans = 0;
    auto st = new SegmentTree(100010);

    foreach (c; C) {
        int M = B[c].length.to!int;
        int q = B[c].assumeSorted.lowerBound(p).length.to!int;
        if (q == M) q = 0;
        foreach (i; 0..M) {
            if (B[c][(q+i)%M] >= p) {
                ans += B[c][(q+i)%M] - p;
                ans -= st.sum(p + 1, B[c][(q+i)%M]);
            } else {
                ans += B[c][(q+i)%M] - p + N;
                ans -= st.sum(p + 1, 100010) + st.sum(0, B[c][(q+i)%M]-1);
            }
            p = B[c][(q+i)%M];
            st.add(p, 1);
        }
    }

    ans.writeln;
}

class SegmentTree {
    int[] table;
    int size;

    this(int n) {
        assert(bsr(n) < 29);
        size = 1 << (bsr(n) + 2);
        table = new int[](size);
    }

    void add(int pos, int num) {
        return add(pos, num, 0, 0, size/2-1);
    }

    void add(int pos, int num, int i, int left, int right) {
        table[i] += num;
        if (left == right)
            return;
        auto mid = (left + right) / 2;
        if (pos <= mid)
            add(pos, num, i*2+1, left, mid);
        else
            add(pos, num, i*2+2, mid+1, right);
    }

    int sum(int pl, int pr) {
        if (pl > pr) return 0;
        return sum(pl, pr, 0, 0, size/2-1);
    }

    int sum(int pl, int pr, int i, int left, int right) {
        if (pl > right || pr < left)
            return 0;
        else if (pl <= left && right <= pr)
            return table[i];
        else
            return
                sum(pl, pr, i*2+1, left, (left+right)/2) +
                sum(pl, pr, i*2+2, (left+right)/2+1, right);
    }
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int n;
    int[] arr;

    this (int n) {
        this.n = n;
        arr = new int[n+1];
    }

    void add(int p, int x) {
        while (p <= n) {
            arr[p] += x;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }

    int dist(int fr, int to) {
        if (fr < to) { return sm(fr, to); }

        return sm(fr, n) + sm(0, to);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.dup.sort.uniq) { d[e] = DList!int(); }
    foreach (i, e; arr) { d[e] ~= (i.to!int + 1); }

    debug { d.writeln; }

    auto f = new fw(n);
    foreach (i; 1 .. MX) { f.add(i, 1); }

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys.sort) {
        auto lst = d[k];

        while (f.dist(pos, lst.back) < f.dist(pos, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { write(k, ": "); lst.each!write; writeln; }

        foreach (e; lst) {
            ans += f.dist(pos, e);

            f.add(e, -1);
            pos = e;
        }
    }

    ans.writeln;
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;
    auto B = new int[][](100010);

    if (N == 1) {
        writeln(1);
        return;
    }

    foreach (i, a; A.enumerate) {
        B[a] ~= i.to!int;
    }

    auto C = A.dup;
    C.sort();
    C = C.uniq().array;

    int p = -1;
    long ans = 0;
    auto st = new SegmentTree(100010);

    foreach (c; C) {
        int M = B[c].length.to!int;
        int q = B[c].assumeSorted.lowerBound(p + 1).length.to!int;
        if (q == M) q = 0;
        foreach (i; 0..M) {
            if (B[c][(q+i)%M] >= p) {
                ans += B[c][(q+i)%M] - p;
                ans -= st.sum(B[c][(q+i)%M], p-1);
            } else {
                ans += B[c][(q+i)%M] - p + N;
                ans -= st.sum(p + 1, 100010) + st.sum(0, B[c][(q+i)%M]-1);
            }
            p = B[c][(q+i)%M];
            st.add(p, 1);
        }
    }

    ans.writeln;
}

class SegmentTree {
    int[] table;
    int size;

    this(int n) {
        assert(bsr(n) < 29);
        size = 1 << (bsr(n) + 2);
        table = new int[](size);
    }

    void add(int pos, int num) {
        return add(pos, num, 0, 0, size/2-1);
    }

    void add(int pos, int num, int i, int left, int right) {
        table[i] += num;
        if (left == right)
            return;
        auto mid = (left + right) / 2;
        if (pos <= mid)
            add(pos, num, i*2+1, left, mid);
        else
            add(pos, num, i*2+2, mid+1, right);
    }

    int sum(int pl, int pr) {
        if (pl > pr) return 0;
        return sum(pl, pr, 0, 0, size/2-1);
    }

    int sum(int pl, int pr, int i, int left, int right) {
        if (pl > right || pr < left)
            return 0;
        else if (pl <= left && right <= pr)
            return table[i];
        else
            return
                sum(pl, pr, i*2+1, left, (left+right)/2) +
                sum(pl, pr, i*2+2, (left+right)/2+1, right);
    }
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int[] arr = new int[MX];

    void add(int p) {
        while (p < MX) {
            arr[p] += 1;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.dup.sort.uniq) {
        d[e] = DList!int();
    }

    foreach (i, e; arr) {
        d[e] ~= (i.to!int + 1);
    }

    debug { d.writeln; }

    bool isCloser(int curPos, int pos1, int pos2) {
        return curPos < pos1 || curPos > pos2;
    }

    auto f = new fw();

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys.sort) {
        auto lst = d[k];
        while (!lst.front == lst.back && isCloser(pos, lst.back, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { write(k, ": "); lst.each!write; writeln; }

        int getCards(int le, int r) { return r - le - f.sm(le, r); }

        foreach (e; lst) {
            if (pos < e) {
                ans += getCards(pos, e);
            } else {
                ans += getCards(pos, n) + getCards(0, e);
            }

            f.add(e);
            pos = e;
        }
    }

    ans.writeln;
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int[] arr = new int[MX];

    void add(int p, int x) {
        while (p < MX) {
            arr[p] += x;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.dup.sort.uniq) {
        d[e] = DList!int();
    }

    foreach (i, e; arr) {
        d[e] ~= (i.to!int + 1);
    }

    debug { d.writeln; }

    bool isCloser(int curPos, int pos1, int pos2) {
        return curPos < pos1 || curPos > pos2;
    }

    auto f = new fw();
    foreach (i; 1 .. MX) f.add(i, 1);

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys.sort) {
        auto lst = d[k];
        while (!lst.front == lst.back && isCloser(pos, lst.back, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { write(k, ": "); lst.each!write; writeln; }

        foreach (e; lst) {
            if (pos < e) {
                ans += f.sm(pos, e);
            } else {
                ans += f.sm(pos, n) + f.sm(0, e);
            }

            f.add(e, -1);
            pos = e;
        }
    }

    ans.writeln;
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int[] arr = new int[MX];

    void add(int p) {
        while (p < MX) {
            arr[p] += 1;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.sort.uniq) {
        d[e] = DList!int();
    }

    foreach (i, e; arr) {
        d[e] ~= (i.to!int + 1);
    }

    debug { d.writeln; }

    bool isCloser(int curPos, int pos1, int pos2) {
        return curPos < pos1 || curPos > pos2;
    }

    auto f = new fw();

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys) {
        auto lst = d[k];
        while (!lst.front == lst.back && isCloser(pos, lst.back, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { lst.each!write; writeln; }

        foreach (e; lst) {
            if (pos < e) {
                ans += e - pos - f.sm(pos, e);
            } else {
                ans += n - pos - f.sm(pos, n) + e - f.sm(e);
            }

            f.add(e);
            pos = e;
        }
    }

    ans.writeln;
}

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

struct fw {
    int mx;
    int[] arr;

    this(int mx) {
        this.mx = mx;
        arr = new int[] (mx+1);
    }

    void add(int p) {
        while (p <= mx) {
            arr[p] += 1;
            p += (p & (-p));
        }
    }import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.datetime.stopwatch;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

struct fw {
    int mx;
    int[] arr;

    this(int mx) {
        this.mx = mx;
        arr = new int[] (mx+1);
    }

    void add(int p) {
        while (p <= mx) {
            arr[p] += 1;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int p1, int p2) {
        return sm(p2) - sm(p1);
    }
};

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

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

    Tuple!(int, int)[] arr2;
    int[int] cnt;
    foreach (ref e; arr) {
        arr2 ~= tuple(e, cnt.get(e, 0));
        cnt[e] += 1;
    }

    auto idx = new int[n];
    makeIndex!("a < b")(arr2, idx);

    idx = idx.map!(x => x+1).array;

    debug { idx.writeln; }

    auto f = new fw(n);

    long ans = 0;
    int lst = 0;
    foreach (e; idx) {
        if (e > lst) { ans += e - lst - f.sm(lst, e); }
        else {
            ans += n - lst - f.sm(lst, n) + e - f.sm(e);
        }

        debug { ans.writeln; }

        f.add(e);
        lst = e;
    }

    ans.writeln;
}

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int p1, int p2) {
        return sm(p2) - sm(p1);
    }
};

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

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

    Tuple!(int, int)[] arr2;
    int[int] cnt;
    foreach (ref e; arr) {
        arr2 ~= tuple(e, cnt.get(e, 0));
        cnt[e] += 1;
    }

    auto idx = new int[n];
    makeIndex!("a < b")(arr2, idx);

    idx = idx.map!(x => x+1).array;

    debug { idx.writeln; }

    auto f = new fw(n);

    int ans = 0;
    int lst = 0;
    foreach (e; idx) {
        if (e > lst) { ans += e - lst - f.sm(lst, e); }
        else {
            ans += n - lst - f.sm(lst, n) + e - f.sm(e);
        }

        debug { ans.writeln; }

        f.add(e);
        lst = e;
    }

    ans.writeln;
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int n;
    int[] arr;

    this (int n) {
        this.n = n;
        arr = new int[n+1];
    }

    void add(int p, int x) {
        while (p <= n) {
            arr[p] += x;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }

    int dist(int le, int r) {
        if (le < r) { return sm(le, r); }

        return sm(r, n) + sm(0, le);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.dup.sort.uniq) { d[e] = DList!int(); }

    foreach (i, e; arr) { d[e] ~= (i.to!int + 1); }

    debug { d.writeln; }

    auto f = new fw(n);
    foreach (i; 1 .. MX) f.add(i, 1);

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys.sort) {
        auto lst = d[k];
        while (!lst.front == lst.back && f.dist(pos, lst.back) < f.dist(pos, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { write(k, ": "); lst.each!write; writeln; }

        foreach (e; lst) {
            ans += f.dist(pos, e);

            f.add(e, -1);
            pos = e;
        }
    }

    ans.writeln;
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int n;
    int[] arr;

    this (int n) {
        this.n = n;
        arr = new int[n+1];
    }

    void add(int p, int x) {
        while (p <= n) {
            arr[p] += x;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }

    int dist(int le, int r) {
        if (le < r) { return sm(le, r); }

        return sm(r, n) + sm(0, le);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.dup.sort.uniq) { d[e] = DList!int(); }

    foreach (i, e; arr) { d[e] ~= (i.to!int + 1); }

    debug { d.writeln; }

    auto f = new fw(n);
    foreach (i; 1 .. MX) f.add(i, 1);

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys.sort) {
        auto lst = d[k];
        while (f.dist(pos, lst.back) < f.dist(pos, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { write(k, ": "); lst.each!write; writeln; }

        foreach (e; lst) {
            ans += f.dist(pos, e);

            f.add(e, -1);
            pos = e;
        }
    }

    ans.writeln;
}


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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;

	long best = long.max;
	long cnt;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2+1)
	{
		auto l = ((i-1)*2) % n;
		auto r = (l+(n/2*2)) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
		debug writeln("l:", l, " r:", r, " cnt:", cnt);
	}

	cnt = 0;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2+1];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2)
	{
		auto l = ((i-1)*2+1) % n;
		auto r = (l+(n/2*2)) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
		debug writeln("l:", l, " r:", r, " cnt:", cnt);
	}

	long ans;
	foreach (e; a)
		ans += e;
	ans -= best;

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

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

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

	int [] b;
	for (int i = 0; i < n; i++)
	{
		b ~= a[(i * 2) % n];
	}
	b ~= b;
	debug {writeln (b);}

	long [] s = [0L];
	foreach (c; b)
	{
		s ~= s.back + c;
	}
	debug {writeln (s);}

	int half = n / 2 + 1;
	long res = 0;
	foreach (i; half..s.length)
	{
		res = max (res, s[i] - s[i - half]);
	}
	writeln (res);
}

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

void main ()
{
	auto n = readln.strip.to !(int);
	auto a = readln.splitter.map !(to !(int)).array;
	long cur = 0;
	long res = 0;
	auto b = a.cycle;
	foreach (i; 0..n * 2)
	{
		cur += b.front;
		b.popFront ();
		b.popFront ();
		if (i > n / 2)
		{
			cur -= b[n];
		}
		res = max (res, cur);
//		writeln (cur);
	}
	writeln (res);
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;

	long best = long.max;
	long cnt;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2+1)
	{
		auto l = ((i-1)*2) % n;
		auto r = (i*2+n/2-1) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
		debug writeln("l:", l, " r:", r, " cnt:", cnt);
	}

	cnt = 0;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2+1];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2+1)
	{
		auto l = ((i-1)*2+1) % n;
		auto r = (i*2+n/2) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
		debug writeln("l:", l, " r:", r, " cnt:", cnt);
	}

	long ans;
	foreach (e; a)
		ans += e;
	ans -= best;

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;

	long best = long.max;
	foreach (i; 0..4)
	{
		foreach (dir; [-2, 2])
		{
			long cnt;
			int pos = i % n;
			foreach (j; 0..n/2)
			{
				cnt += a[pos];
				pos += dir;
				pos = (pos + n) % n;
			}
			best.chmin(cnt);
		}
	}

	auto ans = a.sum - best;

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;

	long best = long.max;
	long cnt;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2+1)
	{
		auto l = ((i-1)*2) % n;
		auto r = (i*2+n/2-1) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
	}

	cnt = 0;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2+1];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2+1)
	{
		auto l = ((i-1)*2+1) % n;
		auto r = (i*2+n/2) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
	}

	auto ans = a.sum - best;

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


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

void main()
{
    readln;

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

    int div3 (ulong x) {
        return x % 3 == 0 ? 1 + div3(x/3) : 0;
    }

    auto b = a
        .map!(x => tuple(div3(x), x)).array
        .multiSort!(q{ a[0] > b[0] }, q{ a[1] < b[1] })
        .map!(q{ a[1] });

    writefln ("%(%s %)", b);
}

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

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

    bool[BigInt] d;

    int maxPow = -1;
    BigInt curValue = ulong.max;

    foreach (_; 0 .. n)
    {
        ulong t;
        readf(" %s", t);
        d[cast(BigInt)t] = true;

        int pow = 0;
        BigInt tc = t;

        while (tc % 3 == 0)
        {
            tc /= 3;
            pow++;
        }

        if (pow > maxPow || pow == maxPow && curValue > t)
        {
            maxPow = pow;
            curValue = t;
        }
    }

    foreach (_; 0 .. n)
    {
        write(curValue, ' ');

        if (curValue * 2 in d)
        {
            curValue *= 2;
        }
        else
        {
            curValue /= 3;
        }
    }
}

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

void main()
{
    readln;

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

    int div3 (ulong x) {
        int r = 0;
        while (x % 3 == 0) x /= 3, ++r;
        return r;
    }

    auto b = a
        .map!(x => tuple(div3(x), x)).array
        .multiSort!(q{ a[0] > b[0] }, q{ a[1] < b[1] })
        .map!(q{ a[1] });

    writefln ("%(%s %)", b);
}

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

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

  auto p = new int[](n); p[] = -1;
  foreach (i; 0..n)
    foreach (j; 0..n)
      if (a[j]%3 == 0 && a[j]/3 == a[i] || a[j]*2 == a[i]) p[j] = i;

  auto i = iota(n).countUntil!(i => !p.canFind(i));
  while (i != -1) {
    write(a[i], " ");
    i = p[i];
  }
}

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

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

    bool[ulong] d;

    int maxPow = -1;
    ulong curValue;

    foreach (_; 0 .. n)
    {
        ulong t;
        readf(" %s", t);
        d[t] = true;

        int pow = 0;
        ulong tc = t;

        while (tc % 3 == 0)
        {
            tc /= 3;
            pow++;
        }

        if (pow > maxPow)
        {
            maxPow = pow;
            curValue = t;
        }
    }

    foreach (_; 0 .. n)
    {
        write(curValue, ' ');

        if (curValue * 2 in d)
        {
            curValue *= 2;
        }
        else
        {
            curValue /= 3;
        }
    }
}

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

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

    bool[BigInt] d;

    int maxPow = -1;
    BigInt curValue = ulong.max;

    foreach (_; 0 .. n)
    {
        ulong t;
        readf(" %s", t);
        d[cast(BigInt)t] = true;

        int pow = 0;
        BigInt tc = t;

        while (tc % 3 == 0)
        {
            tc /= 3;
            pow++;
        }

        if (pow > maxPow && curValue > t)
        {
            maxPow = pow;
            curValue = t;
        }
    }

    foreach (_; 0 .. n)
    {
        write(curValue, ' ');

        if (curValue * 2 in d)
        {
            curValue *= 2;
        }
        else
        {
            curValue /= 3;
        }
    }
}

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

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

    bool[BigInt] d;

    int maxPow = -1;
    BigInt curValue;

    foreach (_; 0 .. n)
    {
        ulong t;
        readf(" %s", t);
        d[cast(BigInt)t] = true;

        int pow = 0;
        BigInt tc = t;

        while (tc % 3 == 0)
        {
            tc /= 3;
            pow++;
        }

        if (pow > maxPow)
        {
            maxPow = pow;
            curValue = t;
        }
    }

    foreach (_; 0 .. n)
    {
        write(curValue, ' ');

        if (curValue * 2 in d)
        {
            curValue *= 2;
        }
        else
        {
            curValue /= 3;
        }
    }
}

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

void main()
{
    readln;

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

    int div3 (ulong x) {
        int r = 0;
        while (x % 3 == 0) x /= 3, ++r;
        return r;
    }

    auto b = a.map!(x => tuple(div3(x), x)).array.sort!(q{ a[0] > b[0] }).map!(q{ a[1] });
    writefln ("%(%s %)", b);

}


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

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

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

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

        auto f = (int x) => zip(arr, arr.drop(x)).filter!(t => t[0] == t[1]).map!(t => t[0]).uniq;
        auto nrs1 = f(1);
        auto nrs2 = f(3);

        auto nrs = nrs1.chain(nrs2).array.sort();

        debug { nrs.writeln; }

        auto ans = tuple(nrs[0], nrs[1]);
        foreach (a, b; lockstep(nrs.dropOne, nrs.drop(2))) {
            if (ans[1] * a > ans[0] * b) ans = tuple(a, b);
        }

        writeln(ans[0], ' ', ans[0], ' ', ans[1], ' ', ans[1]);
    }
}

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

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

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

    foreach (a; A) C[a] += 1;
    foreach (k; C.keys) if (C[k] >= 2) B ~= k;
    B.sort();

    bool comp(long a1, long b1, long a2, long b2) {
        return
            4 * (a1 + b1) * (a1 + b1) * a2 * b2 <=
            4 * (a2 + b2) * (a2 + b2) * a1 * b1;
    }

    long aa = -1;
    long bb = -1;

    foreach (i; 0..B.length.to!int) {
        long b = B[i];
        long a1 = -1;
        long a2 = -1;
        if (C[b] >= 4) {
            a1 = a2 = b;
        } else if (i == 0) {
            a1 = a2 = B[i+1];
        } else if (i == B.length.to!int - 1) {
            a1 = a2 = B[i-1];
        } else {
            a1 = B[i+1];
            a2 = B[i-1];
        }
        long a = comp(a1, b, a2, b) ? a1 : a2;
        if (aa == -1) {
            aa = a;
            bb = b;
        } else if (comp(a, b, aa, bb)) {
            aa = a;
            bb = b;
        }
    }

    writeln(aa, " ", aa, " ", bb, " ", bb);
}

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

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

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

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

        auto nrs1 = zip(arr, arr.dropOne).filter!(t => t[0] == t[1]).map!(t => t[0]).uniq.array;
        auto nrs2 = zip(arr, arr.drop(3)).filter!(t => t[0] == t[1]).map!(t => t[0]).uniq.array;

        auto nrs = nrs1.chain(nrs2).sort().array;

        debug { nrs.writeln; }

        auto ans = tuple(nrs[0], nrs[1]);
        foreach (a, b; lockstep(nrs.dropOne, nrs.drop(2))) {
            if (ans[1] * a > ans[0] * b) ans = tuple(a, b);
        }

        writeln(ans[0], ' ', ans[0], ' ', ans[1], ' ', ans[1]);
    }
}


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

struct Word {
  string s;
  int last;
}

void main() {
  int[char] v = [
    'a' : 0,
    'e' : 1,
    'i' : 2,
    'o' : 3,
    'u' : 4
  ];
  int vowel (char c) {
    return v.get(c, -1);
  }
  immutable n = readln.strip.to!int;
  auto a = new string[n];
  size_t maxlen;
  foreach (i; 0 .. n) {
    a[i] = readln.strip;
    maxlen = max(maxlen, a[i].length);
  }
  auto l = new int[][5 * (maxlen+1)];
  foreach (i; 0 .. n) {
    int t, last = -1;
    foreach (c; a[i]) {
      int x = vowel (c);
      if (x >= 0){
        ++t;
        last = x;
      }
    }
    l[5 * t + last] ~= i;
  }
  alias T = Tuple!(int, int);
  T[] b;
  T[] c;
  foreach (k; 1 .. maxlen+1) {
    int[] tail;
    foreach (i; 0 .. 5) {
      auto idx = 5 * k + i;
      int cur = -1;
      foreach (j; l[idx]) {
        if (cur >= 0) {
          b ~= tuple (cur, j);
          cur = -1;
        } else {
          cur = j;
        }
      }
      if (cur >= 0) tail ~= cur;
    }
    foreach (i; 0 .. tail.length / 2) {
      c ~= tuple (tail[2*i], tail[2*i+1]);
    }
  }
  immutable bl = b.length;
  immutable cl = c.length;
  auto m = min (bl, (bl + cl) / 2);
  c ~= b[m .. $];
  writeln (m);
  foreach (i; 0 .. m) {
    int p12 = b[i][0], p22 = b[i][1];
    int p11 = c[i][0], p21 = c[i][1];
    writeln (a[p11], ' ', a[p12]);
    writeln (a[p21], ' ', a[p22]);
  }
}

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

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

	string[] ws;
	foreach(i; 0 .. n) ws ~= readln.chomp;

	struct X{ char last; int count; }
	string[][X] dic;
	foreach(w; ws){
		int k;
		char x;
		foreach(c; w) if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
			x = c;
			k += 1;
		}
		if(X(x, k) !in dic) dic[X(x, k)] = [];
		dic[X(x, k)] ~= w;
	}
	log("dic:", dic);

	string[2][] latters;
	X[] ks = dic.keys;
	string[][int] dic2;
	foreach(k; ks){
		string[] qs = dic[k];
		for(int i = 0; i < qs.length - 1; i += 2){
			latters ~= [qs[i], qs[i + 1]];
		}
		if(qs.length % 2){
			if(k.count !in dic2) dic2[k.count] = [];
			dic2[k.count] ~= qs[$ - 1];
		}
	}
	log("latters:", latters);
	log("dic2:", dic2);

	string[2][] firsts;
	int[] cts = dic2.keys;
	foreach(ct; cts){
		string[] qs = dic2[ct];
		for(int i = 0; i < qs.length - 1; i += 2){
			firsts ~= [qs[i], qs[i + 1]];
		}
	}

	int m = (latters.length + firsts.length).to!int / 2;
	if(m > latters.length) m = latters.length.to!int;
	else{
		foreach(i; m .. latters.length) firsts ~= latters[i];
	}

	m.writeln;
	foreach(i; 0 .. m){
		writeln(firsts[i][0], " ", latters[i][0]);
		writeln(firsts[i][1], " ", latters[i][1]);
	}
}

/*

settify with (last vowel, vowel count)

greedily make pair for latter words
greedily make pair for first words

*/

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto s = new string[](n);
	int[2][][int] info1;
	int[2][][int] info2;
	auto toNum = ['a':0, 'i':1, 'u':2, 'e':3, 'o':4];
	foreach (i; 0..n)
	{
		s[i] = RD!string;
		int last;
		int cnt;
		foreach (c; s[i])
		{
			auto num = toNum.get(c, -1);
			if (num != -1)
			{
				++cnt;
				last = num;
			}
		}
		info1[cnt]         ~= [i, last];
		info2[cnt*10+last] ~= [i, last];
	}

	int[] ansSec;
	auto used = new bool[](n);
	auto keys2 = info2.keys;
	foreach (key2; keys2)
	{
		auto arr2 = info2[key2];
		auto len2 = arr2.length;
		foreach (i; 0..len2/2)
		{
			auto j  = arr2[i*2][0];
			auto k  = arr2[i*2+1][0];
			ansSec ~= [j, k];
			used[j] = true;
			used[k] = true;
		}
	}

	int[] ansFst;
	auto keys1 = info1.keys;
	foreach (key1; keys1)
	{
		auto arr1 = info1[key1];
		auto len1 = arr1.length;
		int[] tmp;
		foreach (i; 0..len1)
		{
			auto j  = arr1[i][0];
			if (used[j]) continue;

			tmp ~= j;
			if (tmp.length == 2)
			{
				ansFst ~= tmp;
				tmp.length = 0;
			}
		}
	}

	auto diff = max(0, (cast(int)ansSec.length - cast(int)ansFst.length) / 4);
	foreach (i; 0..diff)
	{
		ansFst ~= [ansSec[$-2], ansSec[$-1]];
		ansSec.length = ansSec.length - 2;
	}

	auto len = min(ansFst.length, ansSec.length);
	writeln(len/2);
	foreach (i; 0..len)
	{
		auto j = ansFst[i];
		auto k = ansSec[i];
		writeln(s[j], " ", s[k]);
	}
	stdout.flush();
	debug readln();
}

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto s = new string[](n);
	int[2][][int] info1;
	int[2][][int] info2;
	auto toNum = ['a':0, 'i':1, 'u':2, 'e':3, 'o':4];
	foreach (i; 0..n)
	{
		s[i] = RD!string;
		int last;
		int cnt;
		foreach (c; s[i])
		{
			auto num = toNum.get(c, -1);
			if (num != -1)
			{
				++cnt;
				last = num;
			}
		}
		info1[cnt]         ~= [i, last];
		info2[cnt*10+last] ~= [i, last];
	}

	int[] ansSec;
	auto used = new bool[](n);
	auto keys2 = info2.keys;
	foreach (key2; keys2)
	{
		auto arr2 = info2[key2];
		auto len2 = arr2.length;
		foreach (i; 0..len2/2)
		{
			auto j  = arr2[i*2][0];
			auto k  = arr2[i*2+1][0];
			ansSec ~= [j, k];
			used[j] = true;
			used[k] = true;
		}
	}

	int[] ansFst;
	auto keys1 = info1.keys;
	foreach (key1; keys1)
	{
		auto arr1 = info1[key1];
		auto len1 = arr1.length;
		int[] tmp;
		foreach (i; 0..len1)
		{
			auto j  = arr1[i][0];
			if (used[j]) continue;

			tmp ~= j;
			if (tmp.length == 2)
			{
				ansFst ~= tmp;
				tmp.length = 0;
			}
		}
	}

	auto diff = max(0, (cast(int)ansSec.length - cast(int)ansFst.length) / 4);
	foreach (i; 0..diff)
	{
		ansFst ~= [ansSec[$-2], ansSec[$-1]];
		ansSec.length = ansSec.length - 2;
	}

	writeln(ansSec.length/2);
	foreach (i; 0..ansSec.length)
	{
		auto j = ansFst[i];
		auto k = ansSec[i];
		writeln(s[j], " ", s[k]);
	}
	stdout.flush();
	debug readln();
}


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

immutable int MAX_N = 100_005;
immutable int MAX_C = 0x3F3F3F3F;
immutable int NA    = -1;

void main ()
{
	int n, x;
	while (readf (" %s %s", &n, &x) > 0)
	{
		x--;
		auto p = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &p[i]);
		}
		p[] -= 1;

		auto r = new int [n];
		r[] = NA;
		foreach (i; 0..n)
		{
			if (p[i] != NA)
			{
				r[p[i]] = i;
			}
		}

		int [] [] s;
		int d = NA;

		foreach (i; 0..n)
		{
			if (p[i] == NA)
			{
				int [] cur;
				int j = i;
				cur ~= j;
				while (r[j] != NA)
				{
					j = r[j];
					cur ~= j;
				}
				int e = cur.countUntil (x);
				if (e != NA)
				{
					d = e;
				}
				else
				{
					s ~= cur;
				}
			}
		}
		assert (d != NA);

		auto f = new bool [n + 1];
		f[0] = true;
		foreach (cur; s)
		{
			int l = cur.length;
			for (int i = n; i >= l; i--)
			{
				f[i] |= f[i - l];
			}
		}

		foreach (i; 0..n)
		{
			if (f[i])
			{
				writeln (i + d + 1);
			}
		}
	}
}


module C;

import std.stdio : readln, write, writeln;

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

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

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

  string[] tokens;
}

import std.container : Array;
import std.typecons : Tuple, tuple;

const int N = 30000;

Tuple!(int, int)[N] best;
Array!int[N] divisors;

void main() {
  import std.algorithm : min;
  import std.math : abs;

  for (int d = 1; d < N; ++d) {
    for (int n = d; n < N; n += d) {
      divisors[n].insert(d);
    }
  }
  IO io;
  int T = io.readInt;
  while (T--) {
    int a = io.readInt;
    int b = io.readInt;
    int c = io.readInt;
    auto result = tuple(a + b + c, 0, 0, 0);
    for (int z = 1; z < N; ++z) {
      best[z] = tuple(result[0], 0);
      foreach (y; divisors[z]) {
        best[z] = min(best[z], tuple(abs(y - a), y));
      }
    }
    for (int z = 1; z < N; ++z) {
      if (abs(z - c) < result[0]) {
        foreach (y; divisors[z]) {
          result = min(result, tuple(abs(z - c) + abs(y - b) + best[y][0], best[y][1], y, z));
        }
      }
    }
    writeln(result[0]);
    writeln(result[1], " ", result[2], " ", result[3]);
  }
}

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

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

void solve(){
    foreach(_; 0 .. rint){
        long a = rlong, b = rlong, c = rlong;
        long best = c * 3, A = a, B = b, C = c;
        foreach(long y; 1 .. 40000){
            long x = f(a, y);
            long z = g(c, y);
            long tmp = abs(x - a) + abs(y - b) + abs(z - c);
            log("a:", a, "b:", b, "c:", c, "x:", x, "y:", y, "z:", z, "tmp:", tmp, "best:", best, "A:", A, "B:", B, "C:", C);
            if(tmp < best) best = tmp, A = x, B = y, C = z;
        }
        best.writeln;
        writeln(A, " ", B, " ", C);
    }
}
long f(long a, long y){
    static long[][] us;
    if(! us.length){
        us ~= new long[](0);
        foreach(long i; 1 .. 40000) us ~= divisors(i);
    }

    long best = 40000, ans = -1;
    foreach(d; us[y.to!int]){
        if(abs(a - d) < best) best = abs(a - d), ans = d;
    }
    return ans;
}
long[] divisors(long a){
	long[] res, res2;
	for(long d = 1; d * d <= a; d ++){
		if(a % d == 0) res ~= d, res2 ~=  a / d;
	}
	foreach_reverse(d; res2) if(res[$ - 1] < d) res ~= d;
	return res;
}
long g(long c, long y){
    if(c % y > y / 2 || c / y == 0) return y * (c / y + 1);
    else return y * (c / 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)); }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[][](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto c = RD;
		ans[ti] = [long.max];
		foreach (i; 1..10^^4+1)
		{
			auto cnt1 = abs(a - i);
			foreach (j; 1..10^^4+1)
			{
				if (i * j > (10^^4)*2) break;
				auto cnt2 = abs(b - i*j);
				long num = c / (i*j), cnt3;
				if (num == 0)
				{
					num = 1;
					cnt3 = (i*j) - c % (i*j);
				}
				else
				{
					if ((i*j) - c % (i*j) < c % (i*j))
						++num;
					cnt3 = min(c % (i*j), (i*j) - c % (i*j));
				}
				auto tmp = cnt1 + cnt2 + cnt3;
				if (tmp < ans[ti][0])
				{
					ans[ti] = [tmp, i, i*j, i*j*num];
				}
			}
		}
	}

	foreach (e; ans)
	{
		writeln(e[0]);
		e[1..$].map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}

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

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

void solve(){
    foreach(_; 0 .. rint){
        long a = rlong, b = rlong, c = rlong;
        long best = c * 3, A = a, B = b, C = c;
        foreach(long y; 1 .. 4000){
            long x = f(a, y);
            long z = g(c, y);
            long tmp = abs(x - a) + abs(y - b) + abs(z - c);
            log("a:", a, "b:", b, "c:", c, "x:", x, "y:", y, "z:", z, "tmp:", tmp, "best:", best, "A:", A, "B:", B, "C:", C);
            if(tmp < best) best = tmp, A = x, B = y, C = z;
        }
        best.writeln;
        writeln(A, " ", B, " ", C);
    }
}
long f(long a, long y){
    static long[][] us;
    if(! us.length){
        us ~= new long[](0);
        foreach(long i; 1 .. 4000) us ~= divisors(i);
    }

    long best = 4000, ans = -1;
    foreach(d; us[y.to!int]){
        if(abs(a - d) < best) best = abs(a - d), ans = d;
    }
    return ans;
}
long[] divisors(long a){
	long[] res, res2;
	for(long d = 1; d * d <= a; d ++){
		if(a % d == 0) res ~= d, res2 ~=  a / d;
	}
	foreach_reverse(d; res2) if(res[$ - 1] < d) res ~= d;
	return res;
}
long g(long c, long y){
    if(c % y > y / 2 || c / y == 0) return y * (c / y + 1);
    else return y * (c / 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)); }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[][](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto c = RD;
		ans[ti] = [long.max];
		foreach (i; 1..10^^4+1)
		{
			auto cnt1 = abs(a - i);
			foreach (j; 1..10^^4+1)
			{
				if (i * j > (10^^4)*2) break;
				auto cnt2 = abs(b - i*j);
				auto num  = max(c / (i*j), 1);
				if ((i*j) - c % (i*j) < c % (i*j))
					++num;
				auto cnt3 = min(c % (i*j), (i*j) - c % (i*j));
				auto tmp = cnt1 + cnt2 + cnt3;
				if (tmp < ans[ti][0])
				{
					ans[ti] = [tmp, i, i*j, i*j*num];
				}
			}
		}
	}

	foreach (e; ans)
	{
		writeln(e[0]);
		e[1..$].map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[][](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto c = RD;
		ans[ti] = [long.max];
		foreach (i; 1..10^^4+1)
		{
			auto cnt1 = abs(a - i);
			foreach (j; 1..10^^4+1)
			{
				if (i * j > 10^^4) break;
				auto cnt2 = abs(b - i*j);
				auto num  = max(c / (i*j), 1);
				if ((i*j) - c % (i*j) < c % (i*j))
					++num;
				auto cnt3 = min(c % (i*j), (i*j) - c % (i*j));
				auto tmp = cnt1 + cnt2 + cnt3;
				if (tmp < ans[ti][0])
				{
					ans[ti] = [tmp, i, i*j, i*j*num];
				}
			}
		}
	}

	foreach (e; ans)
	{
		writeln(e[0]);
		e[1..$].map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}


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

bool solve(long power, ref long[][] caves)
{
  foreach (cave ; caves) {
    if (power <= cave[0])
      return false;
    power += cave.length - 1;
  }
  return true;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n_caves;
    readf!" %d "(n_caves);
    long[][] caves;
    foreach (i ; 0 .. n_caves) {
      auto a = readln.strip.split.map!(to!long).array;
      foreach (j ; 1 .. a.length) {
        a[j] -= j - 1;
      }
      a[0] = a[1 .. $].maxElement;
      caves ~= a;
    }
    caves.sort!((a, b) => a[0] < b[0]);
    writeln(iota(0L, 1000000000L + 1 + 1).map!(power => solve(power, caves)).assumeSorted.lowerBound(true).length);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto b = new long[](n);
		foreach (i; 0..n)
		{
			foreach (j; 0..cast(int)a[i][0])
			{
				b[i].chmax(a[i][j+1]-j+1);
			}
		}

		auto index = b.MAKE_IDX();
		long p;
		foreach (i; index)
		{
			if (p < b[i])
			{
				ans[ti] += b[i] - p;
				p = b[i];
			}
			p += a[i][0];
		}
	}

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

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

bool solve(long power, ref long[][] caves)
{
  foreach (cave ; caves) {
    if (power <= cave[0])
      return false;
    power += cave.length - 1;
  }
  return true;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n_caves;
    readf!" %d "(n_caves);
    long[][] caves;
    foreach (i ; 0 .. n_caves) {
      auto a = readln.strip.split.map!(to!long).array;
      foreach (j ; 1 .. a.length) {
        a[j] -= j - 1;
      }
      a[0] = a[1 .. $].maxElement;
      caves ~= a;
    }
    caves.sort!((a, b) => a[0] == b[0] ? a.length > b.length : a[0] < b[0]);
    writeln(iota(0L, 1000000000L).map!(power => solve(power, caves)).assumeSorted.lowerBound(true).length);
  }
}

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

bool solve(long power, ref long[][] caves)
{
  foreach (cave ; caves) {
    if (power <= cave[0])
      return false;
    power += cave.length - 1;
  }
  return true;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n_caves;
    readf!" %d "(n_caves);
    long[][] caves;
    foreach (i ; 0 .. n_caves) {
      auto a = readln.strip.split.map!(to!long).array;
      foreach (j ; 1 .. a.length) {
        a[j] -= j - 1;
      }
      a[0] = a[1 .. $].maxElement;
      caves ~= a;
    }
    caves.sort!((a, b) => a[0] < b[0]);
    writeln(iota(0L, 1000000000L).map!(power => solve(power, caves)).assumeSorted.lowerBound(true).length);
  }
}


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 = [0] ~ readln.splitter.map !(to !(int)).array;
		a[] -= 1;
		auto s = readln.strip;

		auto c = new int [2] [n];
		int res = 0;

		foreach_reverse (i; 0..n)
		{
			c[i][s[i] == 'W'] += 1;
			res += (c[i][0] == c[i][1]);
			if (a[i] >= 0)
			{
				c[a[i]][] += c[i][];
			}
		}
		writeln (res);
	}
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N - 1);
      auto S = scan.map!(c => c == 'B' ? 1 : -1).array;

      int[][] graph = new int[][](N, 0);
      foreach(i, a; A) graph[a - 1] ~= cast(int)i + 1;

      int[] tour;
      int step;
      int ans;
      int dfs(int cur) {
        int summ = S[cur];
        foreach(child; graph[cur]) {
          summ += dfs(child);
        }

        if (summ == 0) ans++;
        return summ;
      }

      dfs(0);
      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N - 1);
      auto S = scan;

      int[][] graph = new int[][](N, 0);
      foreach(i, a; A) graph[a - 1] ~= cast(int)i + 1;

      int ans;
      int[] colors = new int[](N);
      colors[0] = S[0] == 'B' ? 1 : -1;
      for(auto q = new DList!int(0); !q.empty;) {
        auto p = q.front; q.removeFront;
        foreach(near; graph[p]) {
          auto c = colors[p] + (S[near] == 'B' ? 1 : -1);
          colors[near] = c;
          q.insertBack(near);
          if (c == 0) ans++;
        }
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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


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

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

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
}

long solve (long[] a) {
  long curs = 0, maxs = 0;
  foreach (x; a) {
    curs += x;
    if (curs < 0) {
      curs = 0;
    }
    maxs = max (maxs, curs);
  }
  return maxs;
}

void main() {
  auto r = new InputReader;
  immutable n = r.next!int;
  immutable x = r.next!int;
  auto a = new long[n];
  foreach (i; 0 .. n) {
    a[i] = r.next!long;
  }
  long[3] curs;
  long maxs = 0;
  foreach (i; 0 .. n) {
    foreach_reverse (state; 0 .. 3) {
      long y = a[i];
      if (state == 1) {
        y *= x;
      }
      long s = long.min;
      foreach (oldstate; max (0, state - 1) .. state + 1) {
        s = max (s, curs[oldstate]);
      }
      s += y;
      if (s < 0) {
        s = 0;
      }
      curs[state] = s;
      maxs = max (maxs, s);
    }
  }
  writeln (maxs);
}

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

immutable long INF = 1L << 59;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto X = s[1].to!long;
    auto A = readln.split.map!(to!long).array;

    auto dp = new long[][](N+1, 3);
    foreach (i; 0..N+1) dp[i][] = -INF;
    dp[0][0] = 0;

    foreach (i; 0..N) {
        long tmp = dp[i][0];
        dp[i+1][0] = max(dp[i+1][0], tmp + A[i], A[i]);

        tmp = max(tmp, dp[i][1]);
        dp[i+1][1] = max(dp[i+1][1], tmp + X * A[i], X * A[i]);

        tmp = max(tmp, dp[i][2]);
        dp[i+1][2] = max(dp[i+1][2], tmp + A[i], A[i]);
    }

    dp.map!(d => d.reduce!max).reduce!max.writeln;
}

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

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

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

    debug { arr.writeln; }

    auto sr = new long[] (n+2);
    foreach_reverse (i, e; arr.enumerate(1)) { sr[i] = max(0, e + sr[i+1]); }

    auto sl = new long[] (n+2);
    foreach (i, e; arr.enumerate(1)) { sl[i] = max(0, e + sl[i-1]); }

    auto nl = new long[] (n+2);
    foreach (i, e; arr.enumerate(1)) { nl[i] = max(sl[i], nl[i-1] + e.to!long * x); }

    debug { writeln(sl, ' ', sr, ' ', nl); }

    long ans = 0;
    foreach (i; 0 .. n+1) { ans = max(ans, nl[i] + sr[i+1]); }

    ans.writeln;
}

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

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

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

    debug { arr.writeln; }

    auto sr = new long[] (n+2);
    foreach_reverse (i, e; arr.enumerate(1)) { sr[i] = max(0, e + sr[i+1]); }

    auto sl = new long[] (n+2);
    foreach (i, e; arr.enumerate(1)) { sl[i] = max(0, e + sl[i-1]); }

    auto nl = new long[] (n+2);
    foreach (i, e; arr.enumerate(1)) { nl[i] = max(sl[i], nl[i-1] + e * x); }

    debug { writeln(sl, ' ', sr, ' ', nl); }

    long ans = 0;
    foreach (i; 0 .. n+1) { ans = max(ans, nl[i] + sr[i+1]); }

    ans.writeln;
}


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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = readln.split.map!(to!long).array;

    long a = 0;
    A.sort();

    for (int p = 0, x = 0; x < M; ++x) {
        while (p < N && A[p] - a == 0)
            ++p;
        if (p >= N) {
            writeln(0);
            continue;
        }
        writeln(A[p] - a);
        a = A[p];
    }
}

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

void main() {
  int n,k,lst = 0;
  readf!"%d %d\n" (n, k);
  auto v = readln.splitter.map!(to!int).array.sort;
  foreach(x;v) {
    if(x>lst) {
      writeln(x-lst);
      if(--k == 0) break;
    }
    lst = x;
  }
  foreach(i;0..k) writeln(0);
}


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

struct ev {
    int le, r, x;
    int opCmp(ev e) { return r - e.r; }
}

ev[] evs;

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

    foreach (_; 0..q) {
        ev e;
        readf("%s %s %s", &e.le, &e.r, &e.x);
        readln;

        evs ~= e;
    }

    evs.sort();

    auto reach = (0).repeat(n+1).array;

    debug { writeln(evs); }

    foreach (e; evs) {
        foreach_reverse (i; e.x+1..n+1) {
            if (reach[i - e.x] >= e.le) reach[i] = max(reach[i], reach[i - e.x]);
        }
        reach[e.x] = max(reach[e.x], e.r);
    }

    auto oks = reach.enumerate.filter!(t => t.value > 0).map!(t => t.index).array;

    oks.length.writeln;
    oks.writefln!("%(%s %)");
}

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

immutable long mod = 1_000_000_000_000_000_003;

alias Segment = Tuple !(int, q{l}, int, q{r}, int, q{x});
alias Event = Tuple !(int, q{pos}, bool, q{state}, int, q{value});

void main ()
{
	int n, q;
	while (readf (" %s %s", &n, &q) > 0)
	{
		auto s = new Segment [q];
		Event [] e;
		foreach (ref c; s)
		{
			readf (" %s %s %s", &c.l, &c.r, &c.x);
			c.l -= 1;
			e ~= Event (c.l, true,  c.x);
			e ~= Event (c.r, false, c.x);
		}
		e ~= Event (n, true, 0);
		sort (e);

		auto ans = new bool [n + 1];
		auto f = new long [n + 1];
		f[0] = 1;
		int pos = -1;
		foreach (event; e)
		{
			if (pos != event.pos)
			{
				foreach (i; 0..n + 1)
				{
					ans[i] |= (f[i] != 0);
				}
				pos = event.pos;
			}
			auto x = event.value;
			if (event.state)
			{
				foreach_reverse (u; x..n + 1)
				{
					f[u] += f[u - x];
					if (f[u] >= mod)
					{
						f[u] -= mod;
					}
				}
			}
			else
			{
				foreach (u; x..n + 1)
				{
					f[u] -= f[u - x];
					if (f[u] < 0)
					{
						f[u] += mod;
					}
				}
			}
		}

		ans[0] = false;
		writeln (ans.sum);
		writefln ("%(%s %)", (n + 1).iota.filter !(x => ans[x]));
	}
}

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

struct ev { int p; bool isStart; int x; }

ev[] evs;

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

    foreach (_; 0..q) {
        int le, r, x;
        readf("%s %s %s", &le, &r, &x);
        readln;

        evs ~= ev(le, true, x);
        evs ~= ev(r, false, x);
    }

    evs.multiSort!(q{ a.p < b.p }, q{ (a.isStart ? 0 : 1) < (b.isStart ? 0 : 1) });

    debug { writeln(evs); }

    auto ans = false.repeat(n+1).array.BitArray;
    auto cur = false.repeat(n+1).array.BitArray;
    foreach (evt; evs) {
        if (evt.isStart) cur <<= evt.x, cur[evt.x] = true;
        else cur >>= evt.x;
        ans |= cur;
    }

    debug { writefln("%b", ans); }

    auto toPrint = ans.array.dropOne.enumerate(1).filter!(t => t.value).map!(t => t.index).array;
    toPrint.length.writeln;
    toPrint.writefln!("%(%s %)");
}

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

struct ev {
    int le, r, x;
    int opCmp(ev e) { return le - e.le; }
}

ev[] evs;

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

    foreach (_; 0..q) {
        ev e;
        readf("%s %s %s", &e.le, &e.r, &e.x);
        readln;

        evs ~= e;
    }

    evs.sort();

    auto reach = (0).repeat(n+1).array;

    debug { writeln(evs); }

    foreach (e; evs) {
        foreach_reverse (i; e.x+1..n+1) {
            if (reach[i - e.x] >= e.le) reach[i] = max(reach[i], reach[i - e.x]);
        }
        reach[e.x] = max(reach[e.x], e.r);
    }

    auto oks = reach.enumerate.filter!(t => t.value > 0).map!(t => t.index).array;

    oks.length.writeln;
    oks.writefln!("%(%s %)");
}

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

struct ev {
    int le, r, x;
    int opCmp(ev e) { return le - e.le; }
}

ev[] evs;

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

    foreach (_; 0..q) {
        ev e;
        readf("%s %s %s", &e.le, &e.r, &e.x);
        readln;

        evs ~= e;
    }

    evs.sort();

    auto reach = (0).repeat(n+1).array;

    debug { writeln(evs); }

    foreach (e; evs) {
        foreach_reverse (i; e.x+1..n+1) {
            if (reach[i - e.x] >= e.le) reach[i] = max(reach[i], e.r);
        }
        reach[e.x] = max(reach[e.x], e.r);
    }

    auto oks = reach.enumerate.filter!(t => t.value > 0).map!(t => t.index).array;

    oks.length.writeln;
    oks.writefln!("%(%s %)");
}

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

struct ev { int p; bool isStart; int x; }

ev[] evs;

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

    foreach (_; 0..q) {
        int le, r, x;
        readf("%s %s %s", &le, &r, &x);
        readln;

        evs ~= ev(le, true, x);
        evs ~= ev(r, false, x);
    }

    evs.multiSort!(q{ a.p < b.p }, q{ (a.isStart ? 0 : 1) < (b.isStart ? 0 : 1) });

    debug { writeln(evs); }

    auto ans = false.repeat(n+1).array.BitArray;
    auto cur = false.repeat(n+1).array.BitArray;
    foreach (evt; evs) {
        if (evt.isStart) cur <<= evt.x, cur[evt.x] = true;
        else cur >>= evt.x;
        ans |= cur;
    }

    debug { writefln("%b", ans); }

    auto toPrint = ans.array.enumerate.filter!(t => t.value).map!(t => t.index).array;
    toPrint.length.writeln;
    toPrint.writefln!("%(%s %)");
}

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

struct ev {
    int le, r, x;
    int opCmp(ev e) { return r - e.r; }
}

ev[] evs;

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

    foreach (_; 0..q) {
        ev e;
        readf("%s %s %s", &e.le, &e.r, &e.x);
        readln;

        evs ~= e;
    }

    evs.sort();

    auto reach = (0).repeat(n+1).array;

    debug { writeln(evs); }

    foreach (e; evs) {
        foreach_reverse (i; e.x+1..n+1) {
            if (reach[i - e.x] >= e.le) reach[i] = max(reach[i], e.r);
        }
        reach[e.x] = max(reach[e.x], e.r);
    }

    auto oks = reach.enumerate.filter!(t => t.value > 0).map!(t => t.index).array;

    oks.length.writeln;
    oks.writefln!("%(%s %)");
}