import std.stdio, std.string;
import std.random;

class Treap(T)
{
    class Node
    {
        Node left;
        Node right;
        T val;
        int priority;
        int cnt;

        this()
        {
            left = right = null;
        }

        //int opCmp(Node node)
        //{
            //return this.priority - node.priority;
        //}

        int cmpPriority(int priority)
        {
            if (this.priority == priority) return 0;
            return this.priority < priority ? -1 : 1;
        }

        int cmpVal(T val)
        {
            if (this.val == val) return 0;
            return this.val < val ? -1 : 1;
        }
    }

    protected Node root;
    protected Xorshift rnd;

    public this()
    {
        root = null;
        rnd = Xorshift(1234567891);
    }

    protected void leftRotate(ref Node node)
    {
        if (!node.right) return;
        auto rightNode = node.right;
        if (rightNode)
        {
            node.right = rightNode.left;
            rightNode.left = node;
            node = rightNode;
        }
    }

    protected void rightRotate(ref Node node)
    {
        if (!node.left) return;
        auto leftNode = node.left;
        if (leftNode)
        {
            node.left = leftNode.right;
            leftNode.right = node;
            node = leftNode;
        }
    }

    protected Node find(T val)
    {
        return _find(root, val);
    }

    protected Node _find(Node node, T val)
    {
        if (!node) return null;
        auto ret = node.cmpVal(val);
        if (ret == 0) return node;
        if (ret == -1) return _find(node.right, val);
        return _find(node.left, val);
    }

    public void insert(T val)
    {
        _insert(root, val);
    }

    protected void _insert(ref Node node, T val)
    {
        if (!node)
        {
            node = new Node();
            node.val = val;
            node.priority = this.rnd.front;
            node.cnt = 1;
            this.rnd.seed(unpredictableSeed);
            return;
        }
        auto ret = node.cmpVal(val);
        if (ret == 0)
        {
            ++ node.cnt;
            return;
        }
        if (ret == 1)
        {
            _insert(node.left, val);
            if (node.left.priority > node.priority)
            {
                rightRotate(node);
            }
        }
        else if (ret == -1)
        {
            _insert(node.right, val);
            if (node.right.priority > node.priority)
            {
                leftRotate(node);
            }
        }
    }

    public void remove(T val)
    {
        _remove(root, val);
    }

    protected void _remove(ref Node node, T val)
    {
        if (!node) return;
        auto ret = node.cmpVal(val);
        if (ret == 0)
        {
            if (!node.left && !node.right)
            {
                node = null;
                return;
            }
            if (!node.left)
            {
                node = node.right;
                return;
            }
            if (!node.right)
            {
                node = node.left;
                return;
            }
            if (node.left.cmpPriority(node.right.priority) == 1)
            {
                rightRotate(node);
                _remove(node.right, val);
            }
            else
            {
                leftRotate(node);
                _remove(node.left, val);
            }
            return;
        }
        if (ret == -1)
        {
            _remove(node.right, val);
        }
        else
        {
            _remove(node.left, val);
        }
    }

    public void travel()
    {
        _travel(root);
    }

    protected void _travel(Node node)
    {
        if (!node) return;
        _travel(node.left);
        writeln(node.val);
        _travel(node.right);
    }

    public void clear()
    {
        while (root)
        {
            remove(root.val);
        }
    }

    public int getCount(T val)
    {
        auto node = find(val);
        if (!node) return 0;
        return node.cnt;
    }
}

void solve(int[] a, int n, int k)
{
    auto treap = new Treap!long();
    auto lcnt = new int[n];
    foreach (i; 0 .. n)
    {
        lcnt[i] = 0;
        if (a[i] % k == 0)
        {
            auto v = a[i] / k;
            lcnt[i] = treap.getCount(v);
        }
        treap.insert(cast(long)a[i]);
    }
    //treap.clear();
    treap = new Treap!long();
    auto rcnt = new int[n];
    for (int i = n - 1; i >= 0; -- i)
    {
        auto v = cast(long)a[i] * k;
        rcnt[i] = treap.getCount(v);
        treap.insert(a[i]);
    }
    long ans = 0;
    foreach (i; 0 .. n)
    {
        ans += cast(long)lcnt[i] * rcnt[i];
    }
    writeln(ans);
}

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

import std.stdio, std.string;

void solve(int[] a, int n, int k)
{
    int[long] cnt;
    auto lcnt = new int[n];
    foreach (i; 0 .. n)
    {
        lcnt[i] = 0;
        if (a[i] % k == 0)
        {
            auto v = a[i] / k;
            if (v in cnt)
            {
                lcnt[i] = cnt[v];
            }
        }
        if (!(a[i] in cnt))
        {
            cnt[a[i]] = 1;
        }
        else
        {
            ++ cnt[a[i]];
        }
    }
    cnt.clear();
    auto rcnt = new int[n];
    for (int i = n - 1; i >= 0; -- i)
    {
        rcnt[i] = 0;
        auto v = cast(long)a[i] * k;
        if (v in cnt)
        {
            rcnt[i] = cnt[v];
        }
        if (!(a[i] in cnt))
        {
            cnt[a[i]] = 1;
        }
        else
        {
            ++ cnt[a[i]];
        }
    }
    long ans = 0;
    foreach (i; 0 .. n)
    {
        ans += cast(long)lcnt[i] * rcnt[i];
    }
    writeln(ans);
}

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

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

void main() {
  auto input1 = readln().split().map!(to!long);
  long n = input1[0], k = input1[1];
  long[] a = readln().split().map!(to!long).array;
  long[long][3] dp;
  foreach (v; a) {
    if (v % k == 0) {
      dp[2][v] += dp[1].get(v / k, 0);
      dp[1][v] += dp[0].get(v / k, 0);
    }
    dp[0][v] = dp[0].get(v, 0) + 1;
  }
  writeln(sum(dp[2].values));
}

import std.stdio, std.string;
import std.random;

class Treap(T)
{
    class Node
    {
        Node left;
        Node right;
        T val;
        int priority;
        int cnt;

        this()
        {
            left = right = null;
        }

        //int opCmp(Node node)
        //{
            //return this.priority - node.priority;
        //}

        int cmpPriority(int priority)
        {
            if (this.priority == priority) return 0;
            return this.priority < priority ? -1 : 1;
        }

        int cmpVal(T val)
        {
            if (this.val == val) return 0;
            return this.val < val ? -1 : 1;
        }
    }

    protected Node root;
    protected Xorshift rnd;

    public this()
    {
        root = null;
        rnd = Xorshift(1234567891);
    }

    protected void leftRotate(ref Node node)
    {
        if (!node.right) return;
        auto rightNode = node.right;
        if (rightNode)
        {
            node.right = rightNode.left;
            rightNode.left = node;
            node = rightNode;
        }
    }

    protected void rightRotate(ref Node node)
    {
        if (!node.left) return;
        auto leftNode = node.left;
        if (leftNode)
        {
            node.left = leftNode.right;
            leftNode.right = node;
            node = leftNode;
        }
    }

    protected Node find(T val)
    {
        return _find(root, val);
    }

    protected Node _find(Node node, T val)
    {
        if (!node) return null;
        auto ret = node.cmpVal(val);
        if (ret == 0) return node;
        if (ret == -1) return _find(node.right, val);
        return _find(node.left, val);
    }

    public void insert(T val)
    {
        _insert(root, val);
    }

    protected void _insert(ref Node node, T val)
    {
        if (!node)
        {
            node = new Node();
            node.val = val;
            node.priority = this.rnd.front;
            node.cnt = 1;
            this.rnd.seed(unpredictableSeed);
            return;
        }
        auto ret = node.cmpVal(val);
        if (ret == 0)
        {
            ++ node.cnt;
            return;
        }
        if (ret == 1)
        {
            _insert(node.left, val);
            if (node.left.priority > node.priority)
            {
                rightRotate(node);
            }
        }
        else if (ret == -1)
        {
            _insert(node.right, val);
            if (node.right.priority > node.priority)
            {
                leftRotate(node);
            }
        }
    }

    public void remove(T val)
    {
        _remove(root, val);
    }

    protected void _remove(ref Node node, T val)
    {
        if (!node) return;
        auto ret = node.cmpVal(val);
        if (ret == 0)
        {
            if (!node.left && !node.right)
            {
                node = null;
                return;
            }
            if (!node.left)
            {
                node = node.right;
                return;
            }
            if (!node.right)
            {
                node = node.left;
                return;
            }
            if (node.left.cmpPriority(node.right.priority) == 1)
            {
                rightRotate(node);
                _remove(node.right, val);
            }
            else
            {
                leftRotate(node);
                _remove(node.left, val);
            }
            return;
        }
        if (ret == -1)
        {
            _remove(node.right, val);
        }
        else
        {
            _remove(node.left, val);
        }
    }

    public void travel()
    {
        _travel(root);
    }

    protected void _travel(Node node)
    {
        if (!node) return;
        _travel(node.left);
        writeln(node.val);
        _travel(node.right);
    }

    public void clear()
    {
        while (root)
        {
            remove(root.val);
        }
    }

    public int getCount(T val)
    {
        auto node = find(val);
        if (!node) return 0;
        return node.cnt;
    }
}

void solve(int[] a, int n, int k)
{
    auto treap = new Treap!long();
    auto lcnt = new int[n];
    foreach (i; 0 .. n)
    {
        lcnt[i] = 0;
        if (a[i] % k == 0)
        {
            auto v = a[i] / k;
            lcnt[i] = treap.getCount(v);
        }
        treap.insert(cast(long)a[i]);
    }
    treap.clear();
    auto rcnt = new int[n];
    for (int i = n - 1; i >= 0; -- i)
    {
        auto v = cast(long)a[i] * k;
        rcnt[i] = treap.getCount(v);
        treap.insert(a[i]);
    }
    long ans = 0;
    foreach (i; 0 .. n)
    {
        ans += cast(long)lcnt[i] * rcnt[i];
    }
    writeln(ans);
}

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

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio, std.bitmanip;
void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    if (N < 3) {
        writeln(0);
        return;
    }

    if (K == 1) {
        long[long] cnt;
        foreach (a; A) {
            if (a in cnt) cnt[a]++;
            else cnt[a] = 1;
        }
        long ans = 0;
        foreach (v; cnt.values)
            if (v >= 3)
                ans += v * (v-1) * (v-2) / 6;
        writeln(ans);
        return;
    }

    long[long] acm1, acm2;
    if (A[0] == A[1]) {
        acm1[A[0]] = 2;
    }
    else {
        acm1[A[0]] = 1;
        acm1[A[1]] = 1;
    }
    if (A[0] * K == A[1]) acm2[A[1]] = 1;
    long ans = 0;

    foreach (i; 2..N) {
        long a = A[i];
        if (a % K == 0 && (a/K in acm2)) {
            ans += acm2[a/K];
        }
        if (a % K == 0 && (a/K in acm1)) {
            if (a in acm2)
                acm2[a] += acm1[a/K];
            else
                acm2[a] = acm1[a/K];
        }
        if (a in acm1)
            acm1[a] += 1;
        else
            acm1[a] = 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.stdio, std.bitmanip;
void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    if (N < 3) {
        writeln(0);
        return;
    }

    long[long] acm1, acm2;
    if (A[0] == A[1]) {
        acm1[A[0]] = 2;
    }
    else {
        acm1[A[0]] = 1;
        acm2[A[1]] = 1;
    }
    if (A[0] * K == A[1]) acm2[A[1]] = 1;
    long ans = 0;

    foreach (i; 2..N) {
        long a = A[i];
        if (a % K == 0 && (a/K in acm2))
            ans += acm2[a/K];
        if (a in acm1)
            acm1[a] += 1;
        else
            acm1[a] = 1;
        if (a % K == 0 && a/K in acm1) {
            if (a in acm2)
                acm2[a] += acm1[a/K];
            else
                acm2[a] = acm1[a/K];
        }
    }

    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, std.bitmanip;
void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    if (N < 3) {
        writeln(0);
        return;
    }

    if (K == 1) {
        writeln(N-2);
        return;
    }

    long[long] acm1, acm2;
    if (A[0] == A[1]) {
        acm1[A[0]] = 2;
    }
    else {
        acm1[A[0]] = 1;
        acm1[A[1]] = 1;
    }
    if (A[0] * K == A[1]) acm2[A[1]] = 1;
    long ans = 0;

    foreach (i; 2..N) {
        long a = A[i];
        if (a % K == 0 && (a/K in acm2)) {
            ans += acm2[a/K];
        }
        if (a in acm1)
            acm1[a] += 1;
        else
            acm1[a] = 1;
        if (a % K == 0 && (a/K in acm1)) {
            if (a in acm2)
                acm2[a] += acm1[a/K];
            else
                acm2[a] = acm1[a/K];
        }
    }

    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, std.bitmanip;
void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    if (N < 3) {
        writeln(0);
        return;
    }

    if (K == 1) {
        long[long] cnt;
        foreach (a; A) {
            if (a in cnt) cnt[a]++;
            else cnt[a] = 1;
        }
        long ans = 0;
        foreach (v; cnt.values)
            if (v >= 3)
                ans += v * (v-1) * (v-2) / 6;
        writeln(ans);
        return;
    }

    long[long] acm1, acm2;
    if (A[0] == A[1]) {
        acm1[A[0]] = 2;
    }
    else {
        acm1[A[0]] = 1;
        acm1[A[1]] = 1;
    }
    if (A[0] * K == A[1]) acm2[A[1]] = 1;
    long ans = 0;

    foreach (i; 2..N) {
        long a = A[i];
        if (a % K == 0 && (a/K in acm2)) {
            ans += acm2[a/K];
        }
        if (a in acm1)
            acm1[a] += 1;
        else
            acm1[a] = 1;
        if (a % K == 0 && (a/K in acm1)) {
            if (a in acm2)
                acm2[a] += acm1[a/K];
            else
                acm2[a] = acm1[a/K];
        }
    }

    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, std.bitmanip;
void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;

    if (N < 3) {
        writeln(0);
        return;
    }

    long[long] acm1, acm2;
    if (A[0] == A[1]) {
        acm1[A[0]] = 2;
    }
    else {
        acm1[A[0]] = 1;
        acm1[A[1]] = 1;
    }
    if (A[0] * K == A[1]) acm2[A[1]] = 1;
    long ans = 0;

    foreach (i; 2..N) {
        long a = A[i];
        if (a % K == 0 && (a/K in acm2)) {
            ans += acm2[a/K];
        }
        if (a in acm1)
            acm1[a] += 1;
        else
            acm1[a] = 1;
        if (a % K == 0 && (a/K in acm1)) {
            if (a in acm2)
                acm2[a] += acm1[a/K];
            else
                acm2[a] = acm1[a/K];
        }
    }

    ans.writeln;
}


import std.algorithm, std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new uint [] [] [] (2, n, (n + 31) / 32);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
				{
					a[0][i][j >> 5] |= 1u << (j & 31);
					a[1][j][i >> 5] |= 1u << (i & 31);
				}
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] &&
					    (g[v][u >> 5] & (1u << (u & 31))))
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

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

import std.algorithm, std.stdio;

void main ()
{
	stdin.setvbuf (16_384, _IOFBF);
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new bool [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
					a[0][i][j] = a[1][j][i] = true;
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

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

import std.algorithm, std.stdio;

extern (C) nothrow int scanf (const char *, ...);

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new bool [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
					a[0][i][j] = a[1][j][i] = true;
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

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

import std.algorithm, std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		int m = (n + 31) / 32;
		auto a1 = new uint [] [] (n, m);
		auto a2 = new uint [] [] (n, m);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
				{
					a1[i][j >> 5] |= 1u << (j & 31);
					a2[j][i >> 5] |= 1u << (i & 31);
				}
			}

		auto b = new bool [n];
		uint [] [] a;

		void recur (int v)
		{
			b[v] = true;
			foreach (u; 0..n)
				if (!b[u] && (a[v][u >> 5] & (1u << (u & 31))))
					recur (u);
		}

		bool ok = true;

		b[] = false;
		a = a1;
		recur (0);
		ok &= all !("a == true") (b[]);

		b[] = false;
		a = a2;
		recur (0);
		ok &= all !("a == true") (b[]);

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

import std.algorithm, std.string;

extern (C) nothrow int printf (const char *, ...);
extern (C) nothrow int scanf (const char *, ...);

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new bool [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
					a[0][i][j] = a[1][j][i] = true;
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

		printf (toStringz (ok ? "YES\n" : "NO\n"));
	}
}

import std.algorithm, std.stdio;

extern (C) nothrow int printf (const char *, ...);

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new bool [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
					a[0][i][j] = a[1][j][i] = true;
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

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

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

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		int m = (n + 31) / 32;
		auto a1 = new uint [] [] (n, m);
		auto a2 = new uint [] [] (n, m);
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
				{
					a1[i][j >> 5] |= 1u << (j & 31);
					a2[j][i >> 5] |= 1u << (i & 31);
				}
			}
		}

		auto b = new bool [n];
		uint [] [] a;

		void recur (int v)
		{
			b[v] = true;
			foreach (u; 0..n)
			{
				if (!b[u] && (a[v][u >> 5] & (1u << (u & 31))))
				{
					recur (u);
				}
			}
		}

		bool ok = true;

		b[] = false;
		a = a1;
		recur (0);
		ok &= all !("a == true") (b[]);

		b[] = false;
		a = a2;
		recur (0);
		ok &= all !("a == true") (b[]);

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

import std.algorithm, std.stdio;

void main ()
{
	stdin.setvbuf (16_384, _IOFBF);
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new int [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				scanf (" %d", &a[0][i][j]);
				a[1][j][i] = a[0][i][j];
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

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

import std.algorithm, std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new int [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				scanf (" %d", &a[0][i][j]);
				a[1][j][i] = a[0][i][j];
			}

		bool ok = true;
		foreach (g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

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

import std.algorithm, std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new bool [] [] [] (2, n, n);
		foreach (i; 0..n)
			foreach (j; 0..n)
			{
				int c;
				scanf (" %d", &c);
				if (c)
					a[0][i][j] = a[1][j][i] = true;
			}

		bool ok = true;
		foreach (ref g; a)
		{
			auto b = new bool [n];

			void recur (int v)
			{
				b[v] = true;
				foreach (u; 0..n)
					if (!b[u] && g[v][u])
						recur (u);
			}
			recur (0);
			ok &= all !"a" (b);
		}

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


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

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

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

enum long INF = 1L<<50;

void solve() {
    int N = read!int;
    auto S = read!string;
    auto A = readarray!long;

    auto f = new long[][](2, N+1);
    f[0][N] = 0; f[1][N] = -INF;
    for (int k = N - 1; k >= 0; k--) {
        f[0][k] = max(f[1][k+1] + A[k], f[0][k+1] + A[k] * (S[k] == '1'));
        if (S[k] == '1') {
            f[1][k] = max(f[1][k+1] + A[k], f[0][k+1]);
        } else {
            f[1][k] = -INF;
        }
    }
    writeln(max(f[0][0], f[1][0]));
}

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

// Lengths of sequences satisfying the condition (moving to the right)
int[] seq_length_right(alias less = "a < b", T)(T[] a)
{
  if (a.length == 0)
    return new int[](0);
  auto tmp = new int[](a.length);
  int count = 1;
  tmp[$ - 1] = count;
  foreach_reverse (i ; 0 .. a.length - 1) {
    if (binaryFun!less(a[i], a[i + 1]))
      count++;
    else
      count = 1;
    tmp[i] = count;
  }
  return tmp;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto s = "0" ~ readln.strip;
    auto a = [0] ~ readln.splitter.map!(to!int).array;

    int[] x = seq_length_right!((a, b) => a == b)(s);

    long ans;
    size_t i = 0;
    while (i < x.length) {
      if (x[i] >= 1 && s[i] == '1') {
        ans += a[i - 1 .. i - 1 + x[i] + 1].sum - a[i - 1 .. i - 1 + x[i] + 1].minElement;
      }
      i += x[i];
    }
    writeln(ans);
  }
}

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

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

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

void solve() {
    int n = read!int;
    char[] c = readln.strip.dup.to!(char[]);
    auto a = readarray!int;
    long res;
    for(int i = 0; i < n; i++) {
        int minV;
        if (c[i] == '0') {
            minV = a[i];
            int j = i + 1;
            if (j == n) {
                res += minV;
                break;
            }
            while(c[j] != '0') {
                if (a[j] < minV)
                    minV = a[j];
                j++;
                if (j == n)
                    break;
            }
            res += minV;
        }
    }
    writeln(sum(a) - res);
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto s = readln.strip;
    auto a = readln.splitter.map!(to!int).array;
    auto h = redBlackTree!("a>b", true, int)();
    long ans;
    size_t j = 0;
    foreach (i ; 0 .. s.length) {
      if (s[i] != '0') {
        while (j <= i)
          h.insert(a[j++]);
        ans += h.front;
        h.removeFront;
      }
    }
    writeln(ans);
  }
}

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto s = readln.strip;
    auto pos = redBlackTree!("a<b", true, int)();
    foreach (i ; 0 .. s.length)
      if (s[i] != '0')
        pos.insert(cast(int)i);
    auto a = readln.splitter.map!(to!long).array;
    auto b = zip(a, iota(n)).array.sort!((x, y) => x[0] == y[0] ? x[1] < y[1] : x[0] > y[0]).array;
    long ans;
    foreach (x ; b) {
      auto tmp = pos.upperBound(x[1] - 1);
      if (tmp.empty)
        continue;
      ans += x[0];
      pos.removeKey(tmp.front);
    }
    writeln(ans);
  }
}

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto s = readln.strip;
    auto pos = redBlackTree!("a<b", true, int)();
    foreach (i ; 0 .. s.length)
      if (s[i] != '0')
        pos.insert(cast(int)i);
    auto a = readln.splitter.map!(to!long).array;
    auto b = zip(a, iota(n)).array.sort!((x, y) => x[0] == y[0] ? x[1] > y[1] : x[0] > y[0]).array;
    long ans;
    foreach (x ; b) {
      auto tmp = pos.upperBound(x[1] - 1);
      if (tmp.empty)
        continue;
      ans += x[0];
      pos.removeKey(tmp.front);
    }
    writeln(ans);
  }
}

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto s = readln.strip;
    auto pos = redBlackTree!("a<b", true, int)();
    foreach (i ; 0 .. s.length)
      if (s[i] != '0')
        pos.insert(cast(int)i);
    auto a = readln.splitter.map!(to!long).array;
    auto b = zip(a, iota(n)).array.sort!((x, y) => x[0] > y[0]).array;
    long ans;
    foreach (x ; b) {
      auto tmp = pos.upperBound(x[1] - 1);
      if (tmp.empty)
        continue;
      ans += x[0];
      pos.removeKey(tmp.front);
    }
    writeln(ans);
  }
}


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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value = E.init)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

void main()
{
  int t;
  read(t);
  foreach(tc; 0 .. t)
    {
      int n;
      read(n);
      auto points = makeArray!(Tuple!(int, int))(n + 1);
      points[0] = tuple(0, 0);
      foreach(ref point; points[1 .. $])
        point = tuple(next!int, next!int);
      sort(points[]);
      if (points[].map!(t => t[1]).isSorted)
        {
          writeln("YES");
          foreach(i; 1 .. points.length)
            {
              auto delta = tuple(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]);
              assert(delta[0] >= 0 && delta[1] >= 0);
              foreach(j; 0 .. delta[0])
                write('R');
              foreach(j; 0 .. delta[1])
                write('U');
            }
          writeln;
        }
      else
        {
          writeln("NO");
        }
    }
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		alias Point = Tuple !(int, q{x}, int, q{y});
		auto a = new Point [n];
		foreach (ref c; a)
		{
			readf !(" %s %s") (c.x, c.y);
		}

		a.schwartzSort !(c => c.x + c.y);
		auto cur = Point (0, 0);
		bool ok = true;
		string res;
		foreach (ref c; a)
		{
			if (c.x < cur.x || c.y < cur.y)
			{
				ok = false;
				break;
			}
			res ~= 'R'.repeat (c.x - cur.x).text;
			res ~= 'U'.repeat (c.y - cur.y).text;
			cur = c;
		}
		writeln (ok ? "YES" : "NO");
		if (ok)
		{
			writeln (res);
		}
	}
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.outbuffer;
import std.typecons;
import std.algorithm.mutation;
import std.container.array;

string[] tokens;

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

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

void main()
{
    int T = readInt;
    while (T--)
    {
        int n = readInt;
        auto a = new Tuple!(int, int)[n + 1];
        for (int i = 1; i <= n; ++i)
            a[i][0] = readInt, a[i][1] = readInt;
        sort(a);
        bool ok = true;
        for (int i = 1; i <= n; ++i)
            ok &= a[i - 1][1] <= a[i][1];
        if (ok)
        {
            writeln("YES");
            OutBuffer buf = new OutBuffer();
            for (int i = 1; i <= n; ++i)
            {
                for (int y = a[i - 1][0]; y < a[i][0]; ++y)
                    buf.write('R');
                for (int y = a[i - 1][1]; y < a[i][1]; ++y)
                    buf.write('U');
            }
            writeln(buf);
        }
        else
        {
            writeln("NO");
        }
    }
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 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 main()
{
	auto t = RD!int;
	auto ans = new string[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto xy = new long[][](n);
		foreach (i; 0..n)
			xy[i] = [RD, RD];

		xy.sort!"a[0] == b[0] ? a[1] < b[1] : a[0] < b[0]"();

		long x, y;
		foreach (i; 0..n)
		{
			if (xy[i][1] < y)
			{
				ans[ti] = "";
				break;
			}
			foreach (j; 0..xy[i][0]-x)
				ans[ti] ~= "R";
			foreach (j; 0..xy[i][1]-y)
				ans[ti] ~= "U";
			x = xy[i][0];
			y = xy[i][1];
		}
	}

	foreach (e; ans)
	{
		if (e == "")
			writeln("NO");
		else
		{
			writeln("YES");
			writeln(e);
		}
	}
	stdout.flush;
	debug readln;
}


// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm, std.array, std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
int isz(long t){ return to!int(t); }
static string[] tempstr;
T rd(T = long)() { while(!tempstr.length) tempstr = readln.chomp.split; string res = tempstr[0]; tempstr.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    int n, m, x, y;
    n = rd!int; m = rd!int; x = rd!int; y = rd!int;
    char[][] tiles;
    foreach(i; 0..n){
        auto tilerow = rd!(char[]);
        tiles ~= tilerow;
    }
    auto num = new int[][](n, m);
    foreach(i; 0..n){
        int cnt = 0;
        char prev = tiles[i][m-1];
        foreach_reverse(j; 0..m){
            if(tiles[i][j] == '.'){
                ++cnt;
            }else{
                cnt = 0;
            }
            num[i][j] = cnt;
        }
    }
    int take2 = 0, take = 0;
    foreach(i; 0 .. n){
        int j = 0;
        while(j < m){
            if(num[i][j] >= 2){
                ++take2;
                j += 2;
            }else if(num[i][j]){
                ++take;
                ++j;
            }else{
                ++j;
            }
        }
    }
    debug writeln(num);
    ll cost = take2 * min(2*x, y) + take * x;
    writeln(cost);
}

int main(){
    ll t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m, x, y;
		readf !(" %s %s %s %s") (n, m, x, y);
		y = min (y, 2 * x);
		readln;
		int res = 0;
		foreach (row; 0..n)
		{
			auto line = readln.strip;
			int col = 0;
			while (col < m)
			{
				if (line[col] == '*')
				{
					res += 0;
					col += 1;
				}
				else if (col + 1 >= m || line[col + 1] == '*')
				{
					res += x;
					col += 1;
				}
				else
				{
					res += y;
					col += 2;
				}
			}
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		int cnt;
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				if (s[i][j] == '.')
					++cnt;
			}
		}
		if (x*2 <= y)
		{
			ans[ti] = cnt*x;
		}
		else
		{
			foreach (i; 0..n)
			{
				int j = 1;
				while (j < m)
				{
					if (s[i][j] == '.' && s[i][j-1] == '.')
					{
						ans[ti] += y;
						cnt -= 2;
						j += 2;
					}
					else
						++j;
				}
			}
			ans[ti] += x * cnt;
		}
	}

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

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm, std.array, std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
int isz(long t){ return to!int(t); }
static string[] tempstr;
T rd(T = long)() { while(!tempstr.length) tempstr = readln.chomp.split; string res = tempstr[0]; tempstr.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    int n, m, x, y;
    n = rd!int; m = rd!int; x = rd!int; y = rd!int;
    char[][] tiles;
    foreach(i; 0..n){
        auto tilerow = rd!(char[]);
        tiles ~= tilerow;
    }
    auto num = new int[][](n, m);
    foreach(i; 0..n){
        int cnt = 0;
        char prev = tiles[i][m-1];
        foreach_reverse(j; 0..m){
            if(tiles[i][j] == prev && prev == '.'){
                ++cnt;
            }else if(prev == '.'){
                cnt = 1;
            }else{
                cnt = 0;
            }
            num[i][j] = cnt;
        }
    }
    int take2 = 0, take = 0;
    foreach(i; 0 .. n){
        int j = 0;
        while(j < m){
            if(num[i][j] >= 2){
                ++take2;
                j += 2;
            }else if(num[i][j]){
                ++take;
                ++j;
            }else{
                ++j;
            }
        }
    }
    debug writeln(num);
    int cost = take2 * min(2*x, y) + take * x;
    writeln(cost);
}

int main(){
    ll t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}


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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		auto a = new int [] [] (rows, cols);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				readf !(" %s") (a[row][col]);
			}
		}

		bool ok = true;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				auto cur = (row > 0) + (row + 1 < rows);
				cur += (col > 0) + (col + 1 < cols);
				ok &= (a[row][col] <= cur);
				a[row][col] = cur;
			}
		}

		if (ok)
		{
			writeln ("YES");
			writefln !("%(%(%s %)\n%)") (a);
		}
		else
		{
			writeln ("NO");
		}
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const M = readInt();
        const N = readInt();
        auto A = new int[][](M, N);
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          A[x][y] = readInt();
        }

        auto deg = new int[][](M, N);
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          if (x - 1 >= 0) {
            ++deg[x - 1][y];
            ++deg[x][y];
          }
          if (y - 1 >= 0) {
            ++deg[x][y - 1];
            ++deg[x][y];
          }
        }

        bool ans = true;
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          ans = ans && (A[x][y] <= deg[x][y]);
        }
        if (ans) {
          writeln("YES");
          foreach (x; 0 .. M) {
            foreach (y; 0 .. N) {
              if (y > 0) write(" ");
              write(deg[x][y]);
            }
            writeln;
          }
        } else {
          writeln("NO");
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = m;
		bool ok = true;
		(){
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				auto x = 4;
				if (i == 0 || i == n-1)
					--x;
				if (j == 0 || j == m-1)
					--x;

				if (a[i][j] > x)
				{
					ok = false;
					return;
				}
				ans[ti][i][j] = x;
			}
		}}();

		if (!ok)
		{
			ans[ti].length = 0;
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			foreach (ee; e)
			{
				ee.map!(to!string).join(" ").writeln;
			}
		}
	}
	stdout.flush;
	debug readln;
}


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

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

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

void main() {
  auto r = new InputReader;
  immutable n = r.next!int;
  immutable m = r.next!int;
  auto x = r.nextA!long (n);
  immutable x0 = x[0];
  long g;
  debug stderr.writeln(x);
  foreach (i; 1 .. n) {
    immutable dx = x[i] - x0;
    if (i == 1) {
      g = dx;
    } else {
      debug stderr.writeln(g, ' ', dx);
      g = gcd (g, dx);
    }
  }
  auto p = r.nextA!long (m);
  foreach (i; 0 .. m) {
    if (!(g % p[i])) {
      writeln ("YES");
      writeln (x[0], ' ', i + 1);
      return;
    }
  }
  writeln ("NO");
}

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!int;
	auto M = RD!int;
	auto x = RDR.ARR;
	auto p = RDR.ARR;

	long g = x[1] - x[0];
	foreach (i; 2..N)
	{
		g = gcd(g, x[i] - x[i-1]);
	}

	long ans;
	foreach (i; 0..M)
	{
		if (g % p[i] == 0)
		{
			ans = i+1;
			break;
		}
	}

	if (ans == 0)
		writeln("NO");
	else
	{
		writeln("YES");
		writeln(x[0], " ", ans);
	}
	stdout.flush();
	debug readln();
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.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;
    auto P = readln.split.map!(to!long).array;

    auto B = (N-1).iota.map!(i => A[i+1] - A[i]).array;
    auto G = B.reduce!((a, b) => gcd(a, b));

    foreach (i; 0..M) {
        if (G % P[i] == 0) {
            writeln("YES");
            writeln(A.front, " ", i + 1);
            return;
        }
    }

    writeln("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;
import std.numeric;

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

void main() {
  auto r = new InputReader;
  immutable n = r.next!int;
  immutable m = r.next!int;
  auto x = uninitializedArray!(long[]) (n);
  foreach (i; 0 .. n) x[i] = r.next!long;
  immutable x0 = x[0];
  long g;
  foreach (i; 1 .. n) {
    immutable dx = x[i] - x0;
    if (i == 1) {
      g = dx;
    } else {
      g = gcd (g, dx);
    }
  }
  auto p = uninitializedArray!(long[]) (n);
  foreach (i; 0 .. m) {
    p[i] = r.next!long;
    if (!(g % p[i])) {
      writeln ("YES");
      writeln (x[0], ' ', i + 1);
      return;
    }
  }
  writeln ("NO");
}

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

/*

Find gcd of given minutes.
If any p is divisor of the gcd, then YES.
Otherwise NO.

*/

void solve(){
	int n = read!int;
	int m = read!int;
	long[] xs = read!long(n);
	long[] ps = read!long(m);

	long d = xs[1] - xs[0];
	foreach(i; 0 .. n - 1) d = gcd(d, xs[i + 1] - xs[i]);

	bool f;
	int ans;
	foreach(int j, p; ps) if(d % p == 0) f = 1, ans = j;

	if(! f) writeln("NO");
	else writeln("YES"), writeln(xs[0], " ", ans + 1);
}

long gcd(long a, long b){
	if(a % b == 0) return b;
	if(a < b) return gcd(b, a);
	else return gcd(b, a % b);
}

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

/*

Find gcd of given minutes.
If any p is divisor of the gcd, then YES.
Otherwise NO.

*/

void solve(){
	int n = read!int;
	int m = read!int;
	long[] xs = read!long(n);
	long[] ps = read!long(m);

	long d = xs[0];
	foreach(x; xs) d = gcd(d, x);

	bool f;
	int ans;
	foreach(int j, p; ps) if(d % p == 0) f = 1, ans = j;

	if(! f) writeln("NO");
	else writeln("YES"), writeln(xs[0], " ", ans + 1);
}

long gcd(long a, long b){
	if(a % b == 0) return b;
	if(a < b) return gcd(b, a);
	else return gcd(b, a % b);
}


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

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

		if (m == n)
		{
			writeln (m);
			continue;
		}

		sort (a);
		a ~= a[0] + n;
		int [] c;
		c.reserve (m);
		foreach (j; 0..m)
		{
			c ~= a[j + 1] - a[j] - 1;
		}

		sort !(q{a > b}) (c);
		int res = m;
		foreach (i; 0..m)
		{
			res += min (c[i], i * 4 + (c[i] > i * 4 + 1));
		}

		writeln (res);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const L = readLong;
        const M = readInt;
        auto A = new long[M];
        foreach (i; 0 .. M) {
          A[i] = readLong;
        }
        A.sort;

        auto ds = new long[M];
        foreach (i; 0 .. M - 1) {
          ds[i] = A[i + 1] - A[i];
        }
        ds[M - 1] = L + A[0] - A[M - 1];
        ds.sort!"a > b";
        debug {
          writeln("ds = ", ds);
        }

        long ans;
        foreach (j; 0 .. M) {
          long d = ds[j] - 1;
          d -= 4 * j;
          if (d > 0) {
            ans += max(d - 1, 1);
          }
        }
        ans = L - ans;
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

		if (m == n)
		{
			writeln (m);
			continue;
		}

		sort (a);
		a ~= a[0] + n;
		int [] c;
		c.reserve (m);
		foreach (j; 0..m)
		{
			if (a[j + 1] - a[j] > 1)
			{
				c ~= a[j + 1] - a[j] - 1;
			}
		}

		sort (c);
		int res = m;
		int span = 0;
		bool half = false;

		int getC ()
		{
			int temp = c.front;
			if (c.length == 1 && half)
			{
				temp -= 1;
			}
			return temp;
		}

		while (!c.empty)
		{
			if (half)
			{
				res += span - 1;
				c.popBack ();
			}
			span += 2;
			half ^= true;
			while (!c.empty && getC () <= span)
			{
				res += getC ();
				c.popFront ();
			}
		}

		writeln (res);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        const M = readInt;
        auto C = new long[][](N, M);
        foreach (i; 0 .. N) {
          foreach (j; 0 .. M) {
            C[i][j] = readLong;
          }
        }

        auto fs = new long[N];
        foreach (i; 0 .. N) {
          foreach (j; 0 .. M) {
            fs[i] += j * C[i][j];
          }
        }
        debug {
          writeln("fs = ", fs);
        }
        const minF = fs.minElement;
        const maxF = fs.maxElement;

        int im = -1;
        foreach (i; 0 .. N) {
          if (maxF == fs[i]) {
            im = i;
            break;
          }
        }
        writeln(im + 1, " ", maxF - minF);
      }
    }
  } catch (EOFException e) {
  }
}


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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n, x;
  @Dim("n - 1") long[2][] edges;

  void solve(long tc = -1)
  {
    long degx = 0;
    foreach(edge; edges)
      {
        if (edge[0] == x || edge[1] == x)
          degx++;
      }
    if (degx <= 1)
      return writeln("Ayush");
    if (n % 2 == 0)
      return writeln("Ayush");
    writeln("Ashish");
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, x;
		readf !(" %s %s") (n, x);
		x -= 1;
		auto d = new int [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			d[u] += 1;
			d[v] += 1;
		}

		bool win = true;
		if (d[x] >= 2)
		{
			win = !(n & 1);
		}
		writeln (win ? "Ayush" : "Ashish");
	}
}

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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n, x;
  @Dim("n - 1") long[2][] edges;

  void solve(long tc = -1)
  {
    long degx = 0;
    foreach(edge; edges)
      {
        if (edge[0] == x || edge[1] == x)
          degx++;
      }
    if (degx == 1)
      return writeln("Ayush");
    if (n % 2 == 0)
      return writeln("Ayush");
    writeln("Ashish");
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}


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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = array (iota (n));
		foreach (k; 2..n + 1)
		{
			int hi = (n - 1) / k;
			a ~= 0;
			for (int i = hi; i >= 0; i--)
			{
				a[min ((i + 1) * k, $ - 1)] = a[i * k];
			}
			a = a[1..$];
		}
		a[] += 1;
		writefln ("%(%s %)", a);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = array (iota (n));
		a.reserve (2 * n);
		foreach (k; 2..n + 1)
		{
			int hi = (n - 1) / k;
			a.length++;
			for (int i = hi; i >= 0; i--)
			{
				a[min ((i + 1) * k, $ - 1)] = a[i * k];
			}
			a = a[1..$];
		}
		a[] += 1;
		writefln ("%(%s %)", a);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = array (iota (n));
		a.reserve (n * 2);
		foreach (k; 2..n + 1)
		{
			debug {writeln (a);}
			int hi = (n - 1) / k;
			a.length++;
			debug {writeln (a);}
			for (int i = hi; i >= 0; i--)
			{
				debug {writefln ("%s -> %s", i * k,
				                 min ((i + 1) * k,
				                      a.length - 1));}
				a[min ((i + 1) * k, $ - 1)] = a[i * k];
			}
			a = a[1..$];
		}
		a[] += 1;
		writefln ("%(%s %)", a);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n))
	{
		auto a = array (iota (n * 2));
		foreach (k; 1..n + 1)
		{
			for (int i = (n - 1) / k; i >= 0; i--)
			{
				a[min ((i + 1) * k, n)] = a[i * k];
			}
			a = a[1..$];
		}
		a[] += 1;
		writefln ("%(%s %)", a);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n))
	{
		auto a = array (iota (n * 2));
		foreach (k; 2..n + 1)
		{
			a = a[1..$];
			for (int i = (n - 1) / k * k; i >= 0; i -= k)
			{
				a[min (i + k, n)] = a[i];
			}
		}
		writefln ("%(%s %)", a[1..$]);
	}
}


void main() { runSolver(); }

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

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

      int[] pos = new int[](N + 1);
      foreach(int i, a; A) {
        pos[a] = i;
      }

      int[] ans;
      foreach(int n; 0..N) {
        // [A, [n, pos[n + 1]]].deb;
        if (pos[n + 1] != n) {
          ans ~= A[0..n];
          ans ~= A[n..pos[n + 1] + 1].reverse.array;
          ans ~= A[pos[n + 1] + 1..$];
          break;
        }
      }

      if (ans.empty) ans = A;
      ans.toAnswerString.writeln;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

import std.stdio, std.string, std.conv;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
void solution(ref File input, ref File output) {
    auto t = input.readln.chomp.to!int;
    while (t-- > 0) {
        auto _ = input.readln;
        auto source = input.readln.chomp
            .split(' ')
            .map!(to!int)
            .array;
        for (int i = 0; i < source.length; i++) {
            if (i + 1 != source[i])
            {
                for (int j = i + 1; j < source.length; j++)
                {
                    if (source[j] == i + 1) {
                        source[i .. j + 1].reverse;
                        goto end;
                    }
                }
            }
        }
        end:
        writeln(source.map!(to!string).join(' '));
    }
}
void main()
{
    File input, output;
    debug(1) {
        input = File("input.txt", "r");
        output = File("output.txt", "w");
    } else {
        input = stdin;
        output = stdout;
    }
    solution(input, output);
}

import std.stdio, std.string, std.conv;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
void solution(ref File input, ref File output) {
    auto t = input.readln.chomp.to!int;
    writeln(t);
    while (t-- > 0) {
        auto _ = input.readln;
        auto source = input.readln.chomp
            .split(' ')
            .map!(to!int)
            .array;
        for (int i = 0; i < source.length; i++) {
            if (i + 1 != source[i])
            {
                for (int j = i + 1; j < source.length; j++)
                {
                    if (source[j] == i + 1) {
                        source[i .. j + 1].reverse;
                        goto end;
                    }
                }
            }
        }
        end:
        writeln(source.map!(to!string).join(' '));
    }
}
void main()
{
    File input, output;
    debug(1) {
        input = File("input.txt", "r");
        output = File("output.txt", "w");
    } else {
        input = stdin;
        output = stdout;
    }
    solution(input, output);
}


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 = new long[](N);
    foreach (_; 0..M) {
        s = readln.split.map!(to!int);
        auto u = s[0] - 1;
        auto v = s[1] - 1;
        auto c = s[2].to!long;
        A[u] -= c;
        A[v] += c;
    }

    auto plus = N.iota.filter!(i => A[i] > 0).array;
    auto minus = N.iota.filter!(i => A[i] < 0).array;

    int cnt = 0;
    auto G = new Tuple!(int, long)[][](N);

    for (int i = 0, j = 0; i < plus.length && j < minus.length; ) {
        auto u = minus[j];
        auto v = plus[i];
        auto c = min(-A[u], A[v]);
        cnt += 1;
        G[u] ~= tuple(v, c);
        A[u] += c;
        A[v] -= c;
        if (A[u] == 0) ++j;
        if (A[v] == 0) ++i;
    }

    cnt.writeln;
    foreach (i; 0..N) foreach (e; G[i]) writeln(i+1, " ", e[0]+1, " ", e[1]);
}

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

void main ()
{
	int n;
	int m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		auto d = new long [n];
		foreach (j; 0..m)
		{
			int u;
			int v;
			long w;
			readf !(" %s %s %s") (u, v, w);
			u -= 1;
			v -= 1;
			d[u] += w;
			d[v] -= w;
		}

		int i = 0;
		int j = 0;
		Tuple !(int, int, long) [] answer;
		while (true)
		{
			while (i < n && d[i] <= 0)
			{
				i += 1;
			}
			while (j < n && d[j] >= 0)
			{
				j += 1;
			}
			if (i == n && j == n)
			{
				break;
			}

			auto cur = min (+d[i], -d[j]);
			answer ~= tuple (i + 1, j + 1, cur);
			d[i] -= cur;
			d[j] += cur;
		}

		writeln (answer.length);
		foreach (ref e; answer)
		{
			writefln !("%s %s %s") (e[0], e[1], e[2]);
		}
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      auto U = new int[M];
      auto V = new int[M];
      auto D = new long[M];
      foreach (i; 0 .. M) {
        U[i] = readInt() - 1;
        V[i] = readInt() - 1;
        D[i] = readLong();
      }

      auto fs = new long[N];
      foreach (i; 0 .. M) {
        fs[U[i]] -= D[i];
        fs[V[i]] += D[i];
      }

      int[] us, vs;
      foreach (u; 0 .. N) {
        if (fs[u] < 0) us ~= u;
        if (fs[u] > 0) vs ~= u;
      }
      const usLen = cast(int)(us.length);
      const vsLen = cast(int)(vs.length);
      auto fus = new long[usLen];
      auto fvs = new long[vsLen];
      foreach (j; 0 .. usLen) {
        fus[j] = -fs[us[j]];
      }
      foreach (k; 0 .. vsLen) {
        fvs[k] = fs[vs[k]];
      }

      alias Entry = Tuple!(int, "u", int, "v", long, "d");
      Entry[] ans;
      for (int j = 0, k = 0; j < usLen && k < vsLen; ) {
        const t = min(fus[j], fvs[k]);
        if (t > 0) {
          fus[j] -= t;
          fvs[k] -= t;
          ans ~= Entry(us[j], vs[k], t);
        }
        if (j < usLen && fus[j] == 0) {
          ++j;
        } else if (k < vsLen && fvs[k] == 0) {
          ++k;
        } else {
          assert(false);
        }
      }

      writeln(ans.length);
      foreach (ref e; ans) {
        writeln(e.u + 1, " ", e.v + 1, " ", e.d);
      }
    }
  } 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 s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto G = new long[int][](N);
    auto H = new long[int][](N);
    auto inD = new int[](N);
    auto outD = new int[](N);
    auto rbt = new RedBlackTree!int;

    bool edge_exists(int u, int v) {
        return (v in G[u]) && G[u][v] > 0;
    }

    void add_edge(int u, int v, long c) {
        if (c == 0) return;
        if (edge_exists(v, u)) {
            add_edge(v, u, -c);
        } else if (edge_exists(u, v)) {
            G[u][v] += c;
            H[v][u] += c;
            if (G[u][v] == 0) {
                inD[v] -= 1;
                outD[u] -= 1;
                if (inD[v] == 0) rbt.removeKey(v);
                if (outD[u] == 0) rbt.removeKey(u);
            } else if (G[u][v] < 0) {
                auto nc = -G[u][v];
                G[u][v] = 0;
                H[v][u] = 0;
                inD[v] -= 1;
                outD[u] -= 1;
                if (inD[v] == 0) rbt.removeKey(v);
                if (outD[u] == 0) rbt.removeKey(u);
                add_edge(v, u, nc);
            }
        } else {
            if (c < 0) {
                swap(u, v);
                c *= -1;
            }
            G[u][v] = c;
            H[v][u] = c;
            inD[v] += 1;
            outD[u] += 1;
            if (inD[v] > 0 && outD[v] > 0) rbt.insert(v);
            if (inD[u] > 0 && outD[u] > 0) rbt.insert(u);

        }
    }

    foreach (_; 0..M) {
        s = readln.split.map!(to!int);
        auto u = s[0] - 1;
        auto v = s[1] - 1;
        auto c = s[2].to!long;
        add_edge(u, v, c);
    }

    int cnt = 0;
    while (!rbt.empty) {
        auto u = rbt.front;
        auto from = H[u].byKey.front;
        auto to = G[u].byKey.front;
        auto from_cost = H[u][from];
        auto to_cost = G[u][to];
        auto cost = min(from_cost, to_cost);
        add_edge(from, u, -cost);
        add_edge(u, to, -cost);
        add_edge(from, to, cost);
    }

    N.iota.map!(i => G[i].keys.filter!(j => G[i][j] > 0).sum).sum.writeln;
    foreach (i; 0..N) foreach (j; G[i].keys) {
        if (G[i][j] > 0) writeln(i+1, " ", j+1, " ", G[i][j]);
    }
}