It is only a few days until Seollal (Korean Lunar New Year), and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a $$$n \times m$$$ grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell $$$(1, 1)$$$.Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells $$$a$$$ and $$$b$$$, then the two cells $$$a$$$ and $$$b$$$ are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells $$$a$$$ and $$$b$$$ is a sequence of free cells in which the first cell is $$$a$$$, the last cell is $$$b$$$, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell $$$(1, 1)$$$, and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not $$$(1, 1)$$$, and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.

Your program will be judged in multiple test cases. The first line contains the number of test cases $$$t$$$. ($$$1 \le t \le 100$$$). Afterward, $$$t$$$ test cases with the described format will be given. The first line of a test contains two integers $$$n, m$$$ ($$$2 \le n, m \le 20$$$), the size of the grid. In the next $$$n$$$ line of a test contains a string of length $$$m$$$, consisting of the following characters (without any whitespace):    O: A free cell.  X: A rock.  It is guaranteed that the first cell (cell $$$(1, 1)$$$) is free, and every free cell is reachable from $$$(1, 1)$$$.  If $$$t \geq 2$$$ is satisfied, then the size of the grid will satisfy $$$n \le 10, m \le 10$$$. In other words, if any grid with size $$$n > 10$$$ or $$$m > 10$$$ is given as an input, then it will be the only input on the test case ($$$t = 1$$$).

For each test case, print the following: If there are no possible mazes, print a single line NO. Otherwise, print a single line YES, followed by a grid of size $$$(2n-1) \times (2m-1)$$$ denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base.   For all $$$1 \le i \le n, 1 \le j \le m$$$, if the cell $$$(i, j)$$$ is free cell, print 'O' in the cell $$$(2i-1, 2j-1)$$$. Otherwise, print 'X' in the cell $$$(2i-1, 2j-1)$$$.  For all $$$1 \le i \le n, 1 \le j \le m-1$$$, if the neighboring cell $$$(i, j), (i, j+1)$$$ have wall blocking it, print ' ' in the cell $$$(2i-1, 2j)$$$. Otherwise, print any printable character except spaces in the cell $$$(2i-1, 2j)$$$. A printable character has an ASCII code in range $$$[32, 126]$$$: This includes spaces and alphanumeric characters.  For all $$$1 \le i \le n-1, 1 \le j \le m$$$, if the neighboring cell $$$(i, j), (i+1, j)$$$ have wall blocking it, print ' ' in the cell $$$(2i, 2j-1)$$$. Otherwise, print any printable character except spaces in the cell $$$(2i, 2j-1)$$$  For all $$$1 \le i \le n-1, 1 \le j \le m-1$$$, print any printable character in the cell $$$(2i, 2j)$$$.  Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly $$$2m-1$$$ characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.

4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO

YES
OOO
  O
OOO
NO
YES
OOOOO X
  O O
X O O X
  O
OOO X O
O O   O
O OOOOO
YES
OOOOOOOOOOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO

import std.algorithm;
import std.conv : to;
import std.container;
import std.numeric : gcd;
import std.range;
import std.stdio;
import std.typecons : Tuple, tuple;

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

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

void work() {
    int n0 = readInt;
    int n1 = readInt;
    string[] grid = new string[n0];
    for (int i = 0; i < n0; ++i) {
        grid[i] = readToken;
    }

    bool isBanned(int x, int y) {
        int s = x + y;
        return s > 0 && s % 2 == 0;
    }

    int id(int x, int y) {
        return x * n1 + y;
    }

    int n = n0 * n1, m = 0, demands = 0;
    auto edges = new Tuple!(int, int)[(n0 - 1) * n1 + n0 * (n1 - 1)];

    void addEdges(int i, int j) {
        static const int[] DELTA_X = [-1, 0, 0, 1];
        static const int[] DELTA_Y = [0, -1, 1, 0];
        for (int k = 0; k < 4; ++k) {
            int ii = i + DELTA_X[k];
            int jj = j + DELTA_Y[k];
            if (0 <= ii && ii < n0 && 0 <= jj && jj < n1 && grid[ii][jj] == 'O') {
                edges[m++] = tuple(id(i, j), id(ii, jj));
            }
        }
    }

    for (int i = 0; i < n0; ++i) {
        for (int j = 0; j < n1; ++j) {
            if (grid[i][j] == 'O' && isBanned(i, j)) {
                demands += 2;
                addEdges(i, j);
            }
        }
    }

    int[] parent = new int[n], count = new int[n], dist = new int[m],
        prev = new int[m], queue = new int[m];
    bool[] inside = new bool[m + 2], ok1 = new bool[m], ok2 = new bool[m];

    int findRoot(int u) {
        return parent[u] == -1 ? u : (parent[u] = findRoot(parent[u]));
    }

    void merge(int a, int b) {
        parent[findRoot(a)] = findRoot(b);
    }

    void debugPlan(int[] prev, int u) {
        auto result = new char[][n0 * 2 - 1];
        for (int i = 0; i < n0 * 2 - 1; ++i) {
            result[i] = new char[n1 * 2 - 1];
            fill(result[i], ' ');
        }
        for (int i = 0; i < n0; ++i) {
            for (int j = 0; j < n1; ++j) {
                result[i * 2][j * 2] = isBanned(i, j) ? cast(char)('0' + count[id(i, j)]) : '?';
            }
        }
        for (int i = 0; i < m; ++i) {
            if (inside[i]) {
                int s = min(edges[i][0], edges[i][1]);
                int s1 = max(edges[i][0], edges[i][1]);
                if (s + 1 == s1) {
                    result[s / n1 * 2][s % n1 * 2 + 1] = '-';
                }
                else {
                    result[s / n1 * 2 + 1][s % n1 * 2] = '|';
                }
            }
        }
        for (; ~u; u = prev[u]) {
            writeln(u, edges[u]);
            int s = min(edges[u][0], edges[u][1]);
            int s1 = max(edges[u][0], edges[u][1]);
            char symbol = inside[u] ? '#' : '%';
            if (s + 1 == s1) {
                result[s / n1 * 2][s % n1 * 2 + 1] = symbol;
            }
            else {
                result[s / n1 * 2 + 1][s % n1 * 2] = symbol;
            }
        }
        for (int i = 0; i < n0 * 2 - 1; ++i) {
            writeln(result[i]);
        }
        writeln();
    }

    bool augment() {
        fill(parent, -1), fill(count, 0);
        for (int i = 0; i < m; ++i) {
            if (inside[i]) {
                merge(edges[i][0], edges[i][1]), count[edges[i][0]]++;
            }
        }
        int rear = 0;
        fill(dist, -1);
        for (int i = 0; i < m; ++i) {
            ok1[i] = !inside[i] && findRoot(edges[i][0]) != findRoot(edges[i][1]);
            ok2[i] = !inside[i] && count[edges[i][0]] < 2;
            if (ok1[i]) {
                dist[i] = 0, prev[i] = -1, queue[rear++] = i;
                if (ok2[i]) {
                    inside[i] = true;
                    return true;
                }
            }
        }
        for (int head = 0; head < rear; ++head) {
            int u = queue[head];
            if (ok2[u]) {
                // debugPlan(prev, u);
                while (~u) {
                    inside[u] ^= 1, u = prev[u];
                }
                return true;
            }
            if (inside[u]) {
                fill(parent, -1);
                for (int i = 0; i < m; ++i) {
                    if (inside[i] && i != u) {
                        merge(edges[i][0], edges[i][1]);
                    }
                }
                for (int v = 0; v < m; ++v) {
                    if (!inside[v] && findRoot(edges[v][0]) != findRoot(edges[v][1])
                            && dist[v] == -1) {
                        dist[v] = dist[u] + 1, prev[v] = u, queue[rear++] = v;
                    }
                }
            }
            else {
                for (int v = 0; v < m; ++v) {
                    if (inside[v] && count[edges[u][0]] - (edges[u][0] == edges[v][0]) < 2
                            && dist[v] == -1) {
                        dist[v] = dist[u] + 1, prev[v] = u, queue[rear++] = v;
                    }
                }
            }
        }
        return false;
    }

    while (augment()) {
        demands--;
    }

    void makePlan() {
        addEdges(0, 0), fill(parent, -1);
        for (int t = 0; t < 2; ++t) {
            for (int i = 0; i < m; ++i) {
                bool connected = findRoot(edges[i][0]) == findRoot(edges[i][1]);
                if (t && !connected) {
                    inside[i] = true;
                }
                if (inside[i] && !connected) {
                    merge(edges[i][0], edges[i][1]);
                }
            }
        }
        auto result = new char[][n0 * 2 - 1];
        for (int i = 0; i < n0 * 2 - 1; ++i) {
            result[i] = new char[n1 * 2 - 1];
            fill(result[i], ' ');
        }
        for (int i = 0; i < n0; ++i) {
            for (int j = 0; j < n1; ++j) {
                result[i * 2][j * 2] = grid[i][j];
            }
        }
        for (int i = 0; i < m; ++i) {
            if (inside[i]) {
                int s = min(edges[i][0], edges[i][1]);
                int s1 = max(edges[i][0], edges[i][1]);
                if (s + 1 == s1) {
                    result[s / n1 * 2][s % n1 * 2 + 1] = '-';
                }
                else {
                    result[s / n1 * 2 + 1][s % n1 * 2] = '|';
                }
            }
        }
        for (int i = 0; i < n0 * 2 - 1; ++i) {
            writeln(result[i]);
        }
    }

    if (demands) {
        writeln("NO");
    }
    else {
        writeln("YES");
        makePlan();
    }
}

void main() {
    int T = readInt;
    while (T--) {
        work();
    }
}

import std.algorithm;
import std.conv : to;
import std.container;
import std.numeric : gcd;
import std.range;
import std.stdio;
import std.typecons : Tuple, tuple;

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

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

void work() {
    int n0 = readInt;
    int n1 = readInt;
    string[] grid = new string[n0];
    for (int i = 0; i < n0; ++i) {
        grid[i] = readToken;
    }

    bool isBanned(int x, int y) {
        int s = x + y;
        return s > 0 && s % 2 == 0;
    }

    int id(int x, int y) {
        return x * n1 + y;
    }

    int n = n0 * n1, m = 0, demands = 0;
    auto edges = new Tuple!(int, int)[(n0 - 1) * n1 + n0 * (n1 - 1)];

    void addEdges(int i, int j) {
        static const int[] DELTA_X = [-1, 0, 0, 1];
        static const int[] DELTA_Y = [0, -1, 1, 0];
        for (int k = 0; k < 4; ++k) {
            int ii = i + DELTA_X[k];
            int jj = j + DELTA_Y[k];
            if (0 <= ii && ii < n0 && 0 <= jj && jj < n1 && grid[ii][jj] == 'O') {
                edges[m++] = tuple(id(i, j), id(ii, jj));
            }
        }
    }

    for (int i = 0; i < n0; ++i) {
        for (int j = 0; j < n1; ++j) {
            if (grid[i][j] == 'O' && isBanned(i, j)) {
                demands += 2;
                addEdges(i, j);
            }
        }
    }

    int[] parent = new int[n], count = new int[n], dist = new int[m],
        prev = new int[m], queue = new int[m];
    bool[] inside = new bool[m + 2], ok1 = new bool[m], ok2 = new bool[m];

    int findRoot(int u) {
        return parent[u] == -1 ? u : (parent[u] = findRoot(parent[u]));
    }

    void merge(int a, int b) {
        parent[findRoot(a)] = findRoot(b);
    }

    bool augment() {
        fill(parent, -1), fill(count, 0);
        for (int i = 0; i < m; ++i) {
            if (inside[i]) {
                merge(edges[i][0], edges[i][1]), count[edges[i][0]]++;
            }
        }
        int rear = 0;
        fill(dist, -1);
        for (int i = 0; i < m; ++i) {
            ok1[i] = !inside[i] && findRoot(edges[i][0]) != findRoot(edges[i][1]);
            ok2[i] = !inside[i] && count[edges[i][0]] < 2;
            if (ok1[i]) {
                dist[i] = 0, prev[i] = -1, queue[rear++] = i;
                if (ok2[i]) {
                    inside[i] ^= 1;
                    return true;
                }
            }
        }
        for (int head = 0; head < rear; ++head) {
            int u = queue[head];
            if (ok2[u]) {
                while (~u) {
                    inside[u] ^= 1, u = prev[u];
                }
                return true;
            }
            if (inside[u]) {
                fill(parent, -1);
                for (int i = 0; i < m; ++i) {
                    if (inside[i] && i != u) {
                        merge(edges[i][0], edges[i][1]);
                    }
                }
                for (int v = 0; v < m; ++v) {
                    if (!inside[v] && findRoot(edges[v][0]) != findRoot(edges[v][1])
                            && dist[v] == -1) {
                        dist[v] = dist[u] + 1, prev[v] = u, queue[rear++] = v;
                    }
                }
            }
            else {
                for (int v = 0; v < m; ++v) {
                    if (inside[v] && count[edges[u][0]] - (edges[u][0]
                            && edges[v][0]) < 2 && dist[v] == -1) {
                        dist[v] = dist[u] + 1, prev[v] = u, queue[rear++] = v;
                    }
                }
            }
        }
        return false;
    }

    while (augment()) {
        demands--;
    }

    void makePlan() {
        addEdges(0, 0), fill(parent, -1);
        for (int t = 0; t < 2; ++t) {
            for (int i = 0; i < m; ++i) {
                bool connected = findRoot(edges[i][0]) == findRoot(edges[i][1]);
                if (t && !connected) {
                    inside[i] = true;
                }
                if (inside[i] && !connected) {
                    merge(edges[i][0], edges[i][1]);
                }
            }
        }
        auto result = new char[][n0 * 2 - 1];
        for (int i = 0; i < n0 * 2 - 1; ++i) {
            result[i] = new char[n1 * 2 - 1];
            fill(result[i], ' ');
        }
        for (int i = 0; i < n0; ++i) {
            for (int j = 0; j < n1; ++j) {
                result[i * 2][j * 2] = grid[i][j];
            }
        }
        for (int i = 0; i < m; ++i) {
            if (inside[i]) {
                int s = min(edges[i][0], edges[i][1]);
                int s1 = max(edges[i][0], edges[i][1]);
                if (s + 1 == s1) {
                    result[s / n1 * 2][s % n1 * 2 + 1] = '-';
                }
                else {
                    result[s / n1 * 2 + 1][s % n1 * 2] = '|';
                }
            }
        }
        for (int i = 0; i < n0 * 2 - 1; ++i) {
            writeln(result[i]);
        }
    }

    if (demands) {
        writeln("NO");
    }
    else {
        writeln("YES");
        makePlan();
    }
}

void main() {
    int T = readInt;
    while (T--) {
        work();
    }
}

import std.algorithm;
import std.conv : to;
import std.container;
import std.numeric : gcd;
import std.range;
import std.stdio;
import std.typecons : Tuple, tuple;

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

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

void work() {
    int n0 = readInt;
    int n1 = readInt;
    string[] grid = new string[n0];
    for (int i = 0; i < n0; ++i) {
        grid[i] = readToken;
    }
    int id(int x, int y) {
        return x * n1 + y;
    }

    bool isBanned(int v) {
        int s = v / n1 + v % n1;
        return s > 0 && (s % 2 == 0);
    }

    int n = n0 * n1, m = 0;
    alias Edge = Tuple!(int, int);
    auto edges = new Edge[(n0 - 1) * n1 + (n1 - 1) * n0];
    for (int i = 0; i < n0; ++i) {
        for (int j = !i; j < n1; ++j) {
            if (i + 1 < n0 && grid[i + 1][j] == 'O' && grid[i][j] == 'O') {
                edges[m++] = tuple(id(i, j), id(i + 1, j));
            }
            if (j + 1 < n1 && grid[i][j + 1] == 'O' && grid[i][j] == 'O') {
                edges[m++] = tuple(id(i, j), id(i, j + 1));
            }
        }
    }
    auto order = new int[m];
    auto inIntersection = new bool[m];
    auto exchGraph = new bool[][m];
    for (int i = 0; i < m; ++i) {
        exchGraph[i] = new bool[m];
    }
    auto dist = new int[m];
    auto prev = new int[m];
    auto queue = new int[m];

    auto treeHead = new int[n];
    auto treeTo = new int[m << 1];
    auto treeNext = new int[m << 1];
    auto treeDepth = new int[n];
    auto treeParent = new int[n];
    auto treeRoot = new int[n];

    void addTreeEdge(int i, int u, int v) {
        treeTo[i] = v, treeNext[i] = treeHead[u], treeHead[u] = i;
    }

    void dfs(int p, int u) {
        treeDepth[u] = p == -1 ? 0 : treeDepth[p] + 1;
        for (int iterator = treeHead[u]; ~iterator; iterator = treeNext[iterator]) {
            int v = treeTo[iterator];
            if (v != p) {
                treeParent[v] = iterator ^ 1;
                treeRoot[v] = treeRoot[u];
                dfs(u, v);
            }
        }
    }

    auto count = new int[n];

    void add(int v, int d) {
        if (isBanned(v)) {
            count[v] += d;
        }
    }

    bool found = true;
    int size = 0;
    while (found) {
        found = false;
        size = 0;
        for (int i = 0; i < m; ++i) {
            if (inIntersection[i]) {
                order[size++] = i;
            }
        }
        {
            int size1 = size;
            for (int i = 0; i < m; ++i) {
                if (!inIntersection[i]) {
                    order[size1++] = i;
                }
            }
        }
        for (int i = 0; i < size; ++i) {
            for (int j = size; j < m; ++j) {
                exchGraph[j][i] = false;
            }
        }
        // fwd - exchGraphical matroid
        fill(treeHead, -1);
        for (int i = 0; i < size; ++i) {
            auto e = edges[order[i]];
            addTreeEdge(i << 1, e[0], e[1]);
            addTreeEdge(i << 1 | 1, e[1], e[0]);
        }
        fill(treeDepth, -1);
        for (int i = 0; i < n; ++i) {
            if (treeDepth[i] == -1) {
                treeRoot[i] = i, dfs(-1, i);
            }
        }
        for (int j = size; j < m; ++j) {
            exchGraph[j][j] = false;
            auto f = edges[order[j]];
            int u = f[0], v = f[1];
            if (treeRoot[u] == treeRoot[v]) {
                while (treeDepth[u] != treeDepth[v]) {
                    if (treeDepth[u] > treeDepth[v]) {
                        exchGraph[j][treeParent[u] >> 1] = true;
                        u = treeTo[treeParent[u]];
                    }
                    else {
                        exchGraph[j][treeParent[v] >> 1] = true;
                        v = treeTo[treeParent[v]];
                    }
                }
            }
            else {
                exchGraph[j][j] = true;
            }
        }
        // bwd - choice matroid
        fill(count, 0);
        for (int i = 0; i < size; ++i) {
            auto e = edges[order[i]];
            add(e[0], 1), add(e[1], 1);
        }
        for (int i = 0; i < size; ++i) {
            auto e = edges[order[i]];
            add(e[0], -1), add(e[1], -1);
            for (int j = size; j < m; ++j) {
                auto f = edges[order[j]];
                exchGraph[i][j] = count[f[0]] < 2 && count[f[1]] < 2;
            }
            add(e[0], 1), add(e[1], 1);
        }
        {
            int j = size;
            while (j < m) {
                auto f = edges[order[j]];
                if (exchGraph[j][j] && count[f[0]] < 2 && count[f[1]] < 2) {
                    break;
                }
                j++;
            }
            if (j < m) {
                inIntersection[order[j]] = true, found = true;
                continue;
            }
        }
        fill(dist, -1);
        int rear = 0;
        for (int j = size; j < m; ++j) {
            auto f = edges[order[j]];
            if (count[f[0]] < 2 && count[f[1]] < 2) {
                dist[j] = 0, prev[j] = j, queue[rear++] = j;
            }
        }
        for (int head = 0; head < rear; ++head) {
            int u = queue[head];
            if (u >= size && exchGraph[u][u]) {
                int j = u;
                while (prev[j] != j) {
                    inIntersection[order[j]] ^= 1;
                    j = prev[j];
                }
                inIntersection[order[j]] ^= 1;
                found = true;
                break;
            }
            if (u < size) {
                for (int v = size; v < m; ++v) {
                    if (exchGraph[u][v] && dist[v] == -1) {
                        dist[v] = dist[u] + 1, prev[v] = u, queue[rear++] = v;
                    }
                }
            }
            else {
                for (int v = 0; v < size; ++v) {
                    if (exchGraph[u][v] && dist[v] == -1) {
                        dist[v] = dist[u] + 1, prev[v] = u, queue[rear++] = v;
                    }
                }
            }
        }
    }
    for (int x = 0; x < n0; ++x) {
        for (int y = 0; y < n1; ++y) {
            size -= 2 * (grid[x][y] == 'O' && isBanned(id(x, y)));
        }
    }
    if (size != 0) {
        writeln("NO");
    }
    else {
        for (int i = 0; i < n; ++i) {
            treeParent[i] = i;
        }

        int findRoot(int u) {
            if (treeParent[u] != u) {
                treeParent[u] = findRoot(treeParent[u]);
            }
            return treeParent[u];
        }

        for (int i = 0; i < size; ++i) {
            auto e = edges[order[i]];
            treeParent[findRoot(e[0])] = findRoot(e[1]);
        }

        auto result = new char[][2 * n0 - 1];
        for (int i = 0; i < 2 * n0 - 1; ++i) {
            result[i] = new char[2 * n1 - 1];
            fill(result[i], ' ');
            if (~i & 1) {
                for (int j = 0; j < n1; ++j) {
                    result[i][2 * j] = grid[i >> 1][j];
                }
            }
        }

        for (int t = 0; t < 1; ++t) {
            for (int i = 0; i < m; ++i) {
                auto e = edges[i];
                if (t && !inIntersection[i] && findRoot(e[0]) != findRoot(e[1])) {
                    inIntersection[i] = true;
                }
                if (inIntersection[i]) {
                    treeParent[findRoot(e[0])] = findRoot(e[1]);
                    int x = e[0] / n1;
                    int y = e[0] % n1;
                    if (e[0] + 1 == e[1]) {
                        result[x * 2][y * 2 + 1] = '-';
                    }
                    else {
                        result[x * 2 + 1][y * 2] = '|';
                    }
                }
            }
        }
        if (grid[1][0] == 'O' && findRoot(0) != findRoot(n1)) {
            treeParent[findRoot(0)] = findRoot(n1), result[1][0] = '|';
        }
        if (grid[0][1] == 'O' && findRoot(0) != findRoot(1)) {
            treeParent[findRoot(0)] = findRoot(1), result[0][1] = '-';
        }

        writeln("YES");
        for (int i = 0; i < 2 * n0 - 1; ++i) {
            writeln(result[i]);
        }
    }
}

void main() {
    int T = readInt;
    while (T--) {
        work();
    }
}


John Doe has found the beautiful permutation formula.Let's take permutation p = p1, p2, ..., pn. Let's define transformation f of this permutation: where k (k > 1) is an integer, the transformation parameter, r is such maximum integer that rk ≤ n. If rk = n, then elements prk + 1, prk + 2 and so on are omitted. In other words, the described transformation of permutation p cyclically shifts to the left each consecutive block of length k and the last block with the length equal to the remainder after dividing n by k. John Doe thinks that permutation f(f( ... f(p = [1, 2, ..., n], 2) ... , n - 1), n) is beautiful. Unfortunately, he cannot quickly find the beautiful permutation he's interested in. That's why he asked you to help him.Your task is to find a beautiful permutation for the given n. For clarifications, see the notes to the third sample.

A single line contains integer n (2 ≤ n ≤ 106).

Print n distinct space-separated integers from 1 to n — a beautiful permutation of size n.

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) > 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))
	{
		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..$]);
	}
}


We say an infinite sequence $$$a_{0}, a_{1}, a_2, \ldots$$$ is non-increasing if and only if for all $$$i\ge 0$$$, $$$a_i \ge a_{i+1}$$$.There is an infinite right and down grid. The upper-left cell has coordinates $$$(0,0)$$$. Rows are numbered $$$0$$$ to infinity from top to bottom, columns are numbered from $$$0$$$ to infinity from left to right.There is also a non-increasing infinite sequence $$$a_{0}, a_{1}, a_2, \ldots$$$. You are given $$$a_0$$$, $$$a_1$$$, $$$\ldots$$$, $$$a_n$$$; for all $$$i>n$$$, $$$a_i=0$$$. For every pair of $$$x$$$, $$$y$$$, the cell with coordinates $$$(x,y)$$$ (which is located at the intersection of $$$x$$$-th row and $$$y$$$-th column) is white if $$$y<a_x$$$ and black otherwise.Initially there is one doll named Jina on $$$(0,0)$$$. You can do the following operation.  Select one doll on $$$(x,y)$$$. Remove it and place a doll on $$$(x,y+1)$$$ and place a doll on $$$(x+1,y)$$$. Note that multiple dolls can be present at a cell at the same time; in one operation, you remove only one. Your goal is to make all white cells contain $$$0$$$ dolls.What's the minimum number of operations needed to achieve the goal? Print the answer modulo $$$10^9+7$$$.

The first line of input contains one integer $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$). The second line of input contains $$$n+1$$$ integers $$$a_0,a_1,\ldots,a_n$$$ ($$$0\le a_i\le 2\cdot 10^5$$$). It is guaranteed that the sequence $$$a$$$ is non-increasing.

Print one integer — the answer to the problem, modulo $$$10^9+7$$$.

NoteConsider the first example. In the given grid, cells $$$(0,0),(0,1),(1,0),(1,1)$$$ are white, and all other cells are black. Let us use triples to describe the grid: triple $$$(x,y,z)$$$ means that there are $$$z$$$ dolls placed on cell $$$(x,y)$$$. Initially the state of the grid is $$$(0,0,1)$$$.One of the optimal sequence of operations is as follows:  Do the operation with $$$(0,0)$$$. Now the state of the grid is $$$(1,0,1),(0,1,1)$$$.  Do the operation with $$$(0,1)$$$. Now the state of the grid is $$$(1,0,1),(1,1,1),(0,2,1)$$$.  Do the operation with $$$(1,0)$$$. Now the state of the grid is $$$(1,1,2),(0,2,1),(2,0,1)$$$.  Do the operation with $$$(1,1)$$$. Now the state of the grid is $$$(1,1,1),(0,2,1),(2,0,1),(1,2,1),(2,1,1)$$$.  Do the operation with $$$(1,1)$$$. Now the state of the grid is $$$(0,2,1),(2,0,1),(1,2,2),(2,1,2)$$$. Now all white cells contain $$$0$$$ dolls, so we have achieved the goal with $$$5$$$ operations.

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

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

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

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

struct ModInt(uint M_) {
  import std.conv : to;
  alias M = M_;
  uint x;
  this(ModInt a) { x = a.x; }
  this(uint x_) { x = x_ % M; }
  this(ulong x_) { x = cast(uint)(x_ % M); }
  this(int x_) { x = ((x_ %= cast(int)(M)) < 0) ? (x_ + cast(int)(M)) : x_; }
  this(long x_) { x = cast(uint)(((x_ %= cast(long)(M)) < 0) ? (x_ + cast(long)(M)) : x_); }
  ref ModInt opAssign(T)(inout(T) a) if (is(T == uint) || is(T == ulong) || is(T == int) || is(T == long)) { return this = ModInt(a); }
  ref ModInt opOpAssign(string op, T)(T a) {
    static if (is(T == ModInt)) {
      static if (op == "+") { x = ((x += a.x) >= M) ? (x - M) : x; }
      else static if (op == "-") { x = ((x -= a.x) >= M) ? (x + M) : x; }
      else static if (op == "*") { x = cast(uint)((cast(ulong)(x) * a.x) % M); }
      else static if (op == "/") { this *= a.inv(); }
      else static assert(false);
      return this;
    } else static if (op == "^^") {
      if (a < 0) return this = inv()^^(-a);
      ModInt b = this, c = 1U;
      for (long e = a; e; e >>= 1) { if (e & 1) c *= b; b *= b; }
      return this = c;
    } else {
      return mixin("this " ~ op ~ "= ModInt(a)");
    }
  }
  ModInt inv() const {
    uint a = M, b = x; int y = 0, z = 1;
    for (; b; ) { const q = a / b; const c = a - q * b; a = b; b = c; const w = y - cast(int)(q) * z; y = z; z = w; }
    assert(a == 1); return ModInt(y);
  }
  ModInt opUnary(string op)() const {
    static if (op == "+") { return this; }
    else static if (op == "-") { ModInt a; a.x = x ? (M - x) : 0U; return a; }
    else static assert(false);
  }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op, T)(T a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  bool opCast(T: bool)() const { return (x != 0U); }
  string toString() const { return x.to!string; }
}

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

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

void main() {
  prepare;

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

      Mint ans;
      foreach (i; 0 .. N) {
        /*
        foreach (j; 0 .. A[i]) {
          ans += binom(i + j, i);
        }
        */
        ans += binom(i + A[i], i + 1);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Two large companies "Cecsi" and "Poca Pola" are fighting against each other for a long time. In order to overcome their competitor, "Poca Pola" started a super secret project, for which it has total $$$n$$$ vacancies in all of their offices. After many tests and interviews $$$n$$$ candidates were selected and the only thing left was their employment.Because all candidates have the same skills, it doesn't matter where each of them will work. That is why the company decided to distribute candidates between workplaces so that the total distance between home and workplace over all candidates is minimal.It is well known that Earth is round, so it can be described as a circle, and all $$$m$$$ cities on Earth can be described as points on this circle. All cities are enumerated from $$$1$$$ to $$$m$$$ so that for each $$$i$$$ ($$$1 \le i \le m - 1$$$) cities with indexes $$$i$$$ and $$$i + 1$$$ are neighbors and cities with indexes $$$1$$$ and $$$m$$$ are neighbors as well. People can move only along the circle. The distance between any two cities equals to minimal number of transitions between neighboring cities you have to perform to get from one city to another. In particular, the distance between the city and itself equals $$$0$$$.The "Poca Pola" vacancies are located at offices in cities $$$a_1, a_2, \ldots, a_n$$$. The candidates live in cities $$$b_1, b_2, \ldots, b_n$$$. It is possible that some vacancies are located in the same cities and some candidates live in the same cities. The "Poca Pola" managers are too busy with super secret project, so you were asked to help "Poca Pola" to distribute candidates between workplaces, so that the sum of the distance between home and workplace over all candidates is minimum possible.

The first line contains two integers $$$m$$$ and $$$n$$$ ($$$1 \le m \le 10^9$$$, $$$1 \le n \le 200\,000$$$) — the number of cities on Earth and the number of vacancies. The second line contains $$$n$$$ integers $$$a_1, a_2, a_3, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the cities where vacancies are located. The third line contains $$$n$$$ integers $$$b_1, b_2, b_3, \ldots, b_n$$$ ($$$1 \le b_i \le m$$$) — the cities where the candidates live.

The first line should contain the minimum total distance between home and workplace over all candidates. The second line should contain $$$n$$$ different integers from $$$1$$$ to $$$n$$$. The $$$i$$$-th of them should be the index of candidate that should work at $$$i$$$-th workplace.

NoteIn the first example, the distance between each candidate and his workplace equals to $$$1$$$ (from $$$1$$$ to $$$10$$$, from $$$4$$$ to $$$5$$$ and from $$$6$$$ to $$$5$$$).In the second example:  The second candidate works at first workplace, the distance between cities $$$3$$$ and $$$1$$$ equals to $$$2$$$.  The third candidate works at second workplace, the distance between cities $$$6$$$ and $$$4$$$ equals to $$$2$$$.  The first candidate works at third workplace, the distance between cities $$$8$$$ and $$$8$$$ equals to $$$0$$$.

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

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

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

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

long M;
int N;
long[] A, B;

void main() {
  try {
    for (; ; ) {
      M = readLong();
      N = readInt();
      A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong() % M;
      }
      B = new long[N];
      foreach (j; 0 .. N) {
        B[j] = readLong() % M;
      }

      auto as = new Tuple!(long, int)[N];
      auto bs = new Tuple!(long, int)[N];
      foreach (i; 0 .. N) {
        as[i] = tuple(A[i], i);
      }
      sort(as);
      foreach (j; 0 .. N) {
        bs[j] = tuple(B[j], j);
        for (; bs[j][0] < as[0][0] - M / 2; bs[j][0] += M) {}
        for (; bs[j][0] >= as[0][0] - M / 2 + M; bs[j][0] -= M) {}
      }
      sort(bs);
      bs.length = 2 * N;
      foreach (j; 0 .. N) {
        bs[j + N] = bs[j];
        bs[j + N][0] += M;
      }
      debug {
        // writeln("as[*][0] = ", as.map!"a[0]");
        // writeln("bs[*][0] = ", bs.map!"a[0]");
      }

      // exact 0: B - A
      Tuple!(int, long)[] events;
      foreach (i; 0 .. N) {
        /*
          as[i]
          paired with bs[i], bs[i + 1], ..., bs[i + N - 1]
          + -> -
        */
        const j = bs.lowerBound(tuple(as[i][0], -1));
        debug {
          // writeln("i = ", i, ": ", j);
        }
        events ~= tuple(0, as[i][0]);
        events ~= tuple(min(max(j - i, 0), N + 1), -2 * as[i][0]);
      }
      foreach (j; 0 .. N) {
        /*
          bs[j]
          paired with as[j], as[j - 1], ..., as[0]
          - -> +

          k = j + 1

          bs[j + N]
          paired with as[N - 1], as[N - 2], ..., as[j + 1], as[j]
          - -> +
        */
        const i0 = as.lowerBound(tuple(bs[j][0], N)) - 1;
        const i1 = as.lowerBound(tuple(bs[j + N][0], N)) - 1;
        debug {
          // writeln("j = ", j, ": ", i0, " ", i1);
        }
        events ~= tuple(0, -bs[j][0]);
        events ~= tuple(min(max(j - i0, 0), j + 1), 2 * bs[j][0]);
        events ~= tuple(j + 1, -bs[j][0] - bs[j + N][0]);
        events ~= tuple(min(max(j + N - i1, j + 1), N + 1), 2 * bs[j + N][0]);
      }
      sort(events);
      events ~= tuple(N + 1, 0L);
      debug {
        // writeln("events = ", events);
      }

      long ans = M * N;
      int km;
      long now;
      int pos;
      foreach (k; 0 .. N + 1) {
        for (; events[pos][0] <= k; ++pos) {
          now += events[pos][1];
        }
        debug {
          // writeln("k = ", k, ": ", now);
          long sum;
          foreach (i; 0 .. N) {
            sum += abs(as[i][0] - bs[i + k][0]);
          }
          assert(sum == now);
        }
        if (chmin(ans, now)) {
          km = k;
        }
      }

      auto ansId = new int[N];
      foreach (i; 0 .. N) {
        ansId[as[i][1]] = bs[i + km][1];
      }

      writeln(ans);
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ansId[i] + 1);
      }
      writeln();

      debug {
        auto perm = iota(N).array;
        long brt = M * N;
        do {
          long cost;
          foreach (i; 0 .. N) {
            long d = abs(A[i] - B[perm[i]]);
            if (d > M - d) {
              d = M - d;
            }
            cost += d;
          }
          chmin(brt, cost);
        } while (perm.nextPermutation);
        // writeln("brt = ", brt);
        assert(brt == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

long M;
int N;
long[] A, B;

void main() {
  try {
    for (; ; ) {
      M = readLong();
      N = readInt();
      A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong() % M;
      }
      B = new long[N];
      foreach (j; 0 .. N) {
        B[j] = readLong() % M;
      }

      auto as = new Tuple!(long, int)[N];
      auto bs = new Tuple!(long, int)[N];
      foreach (i; 0 .. N) {
        as[i] = tuple(A[i], i);
      }
      foreach (j; 0 .. N) {
        bs[j] = tuple(B[j], j);
        for (; 2 * bs[j][0] >= M; bs[j][0] -= M) {}
      }
      sort(as);
      sort(bs);
      bs.length = 2 * N;
      foreach (j; 0 .. N) {
        bs[j + N] = bs[j];
        bs[j + N][0] += M;
      }
      debug {
        writeln("as[*][0] = ", as.map!"a[0]");
        writeln("bs[*][0] = ", bs.map!"a[0]");
      }

      // exact 0: B - A
      Tuple!(int, long)[] events;
      foreach (i; 0 .. N) {
        /*
          as[i]
          paired with bs[i], bs[i + 1], ..., bs[i + N - 1]
          + -> -
        */
        const j = bs.lowerBound(tuple(as[i][0], -1));
        debug {
          writeln("i = ", i, ": ", j);
        }
        events ~= tuple(0, as[i][0]);
        events ~= tuple(min(max(j - i, 0), N + 1), -2 * as[i][0]);
      }
      foreach (j; 0 .. N) {
        /*
          bs[j]
          paired with as[j], as[j - 1], ..., as[0]
          - -> +

          k = j + 1

          bs[j + N]
          paired with as[N - 1], as[N - 2], ..., as[j + 1], as[j]
          - -> +
        */
        const i0 = as.lowerBound(tuple(bs[j][0], N)) - 1;
        const i1 = as.lowerBound(tuple(bs[j + N][0], N)) - 1;
        debug {
          writeln("j = ", j, ": ", i0, " ", i1);
        }
        events ~= tuple(0, -bs[j][0]);
        events ~= tuple(min(max(j - i0, 0), j + 1), 2 * bs[j][0]);
        events ~= tuple(j + 1, -bs[j][0] - bs[j + N][0]);
        events ~= tuple(min(max(j + N - i1, j + 1), N + 1), 2 * bs[j + N][0]);
      }
      sort(events);
      events ~= tuple(N + 1, 0L);
      debug {
        writeln("events = ", events);
      }

      long ans = M * N;
      int km;
      long now;
      int pos;
      foreach (k; 0 .. N + 1) {
        for (; events[pos][0] <= k; ++pos) {
          now += events[pos][1];
        }
        debug {
          writeln("k = ", k, ": ", now);
        }
        if (chmin(ans, now)) {
          km = k;
        }
      }
      writeln(ans);
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(bs[i + km][1] + 1);
      }
      writeln();

      debug {
        auto perm = iota(N).array;
        long brt = M * N;
        do {
          long cost;
          foreach (i; 0 .. N) {
            long d = abs(A[i] - B[perm[i]]);
            if (d > M - d) {
              d = M - d;
            }
            cost += d;
          }
          chmin(brt, cost);
        } while (perm.nextPermutation);
        writeln("brt = ", brt);
        assert(brt == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

long M;
int N;
long[] A, B;

void main() {
  try {
    for (; ; ) {
      M = readLong();
      N = readInt();
      A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong() % M;
      }
      B = new long[N];
      foreach (j; 0 .. N) {
        B[j] = readLong() % M;
      }

      auto as = new Tuple!(long, int)[N];
      auto bs = new Tuple!(long, int)[N];
      foreach (i; 0 .. N) {
        as[i] = tuple(A[i], i);
      }
      sort(as);
      foreach (j; 0 .. N) {
        bs[j] = tuple(B[j], j);
        for (; bs[j][0] < as[0][0] - M / 2; bs[j][0] += M) {}
        for (; bs[j][0] >= as[0][0] - M / 2 + M; bs[j][0] -= M) {}
      }
      sort(bs);
      bs.length = 2 * N;
      foreach (j; 0 .. N) {
        bs[j + N] = bs[j];
        bs[j + N][0] += M;
      }
      debug {
        writeln("as[*][0] = ", as.map!"a[0]");
        writeln("bs[*][0] = ", bs.map!"a[0]");
      }

      // exact 0: B - A
      Tuple!(int, long)[] events;
      foreach (i; 0 .. N) {
        /*
          as[i]
          paired with bs[i], bs[i + 1], ..., bs[i + N - 1]
          + -> -
        */
        const j = bs.lowerBound(tuple(as[i][0], -1));
        debug {
          writeln("i = ", i, ": ", j);
        }
        events ~= tuple(0, as[i][0]);
        events ~= tuple(min(max(j - i, 0), N + 1), -2 * as[i][0]);
      }
      foreach (j; 0 .. N) {
        /*
          bs[j]
          paired with as[j], as[j - 1], ..., as[0]
          - -> +

          k = j + 1

          bs[j + N]
          paired with as[N - 1], as[N - 2], ..., as[j + 1], as[j]
          - -> +
        */
        const i0 = as.lowerBound(tuple(bs[j][0], N)) - 1;
        const i1 = as.lowerBound(tuple(bs[j + N][0], N)) - 1;
        debug {
          writeln("j = ", j, ": ", i0, " ", i1);
        }
        events ~= tuple(0, -bs[j][0]);
        events ~= tuple(min(max(j - i0, 0), j + 1), 2 * bs[j][0]);
        events ~= tuple(j + 1, -bs[j][0] - bs[j + N][0]);
        events ~= tuple(min(max(j + N - i1, j + 1), N + 1), 2 * bs[j + N][0]);
      }
      sort(events);
      events ~= tuple(N + 1, 0L);
      debug {
        writeln("events = ", events);
      }

      long ans = M * N;
      int km;
      long now;
      int pos;
      foreach (k; 0 .. N + 1) {
        for (; events[pos][0] <= k; ++pos) {
          now += events[pos][1];
        }
        debug {
          writeln("k = ", k, ": ", now);
        }
        if (chmin(ans, now)) {
          km = k;
        }
      }
      writeln(ans);
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(bs[i + km][1] + 1);
      }
      writeln();

      debug {
        auto perm = iota(N).array;
        long brt = M * N;
        do {
          long cost;
          foreach (i; 0 .. N) {
            long d = abs(A[i] - B[perm[i]]);
            if (d > M - d) {
              d = M - d;
            }
            cost += d;
          }
          chmin(brt, cost);
        } while (perm.nextPermutation);
        writeln("brt = ", brt);
        assert(brt == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

long M;
int N;
long[] A, B;

void main() {
  try {
    for (; ; ) {
      M = readLong();
      N = readInt();
      A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong() % M;
      }
      B = new long[N];
      foreach (j; 0 .. N) {
        B[j] = readLong() % M;
      }

      auto as = new Tuple!(long, int)[N];
      auto bs = new Tuple!(long, int)[N];
      foreach (i; 0 .. N) {
        as[i] = tuple(A[i], i);
      }
      foreach (j; 0 .. N) {
        bs[j] = tuple(B[j], j);
        for (; 2 * bs[j][0] >= M; bs[j][0] -= M) {}
      }
      sort(as);
      sort(bs);
      bs.length = 2 * N;
      foreach (j; 0 .. N) {
        bs[j + N] = bs[j];
        bs[j + N][0] += M;
      }
      debug {
        writeln("as[*][0] = ", as.map!"a[0]");
        writeln("bs[*][0] = ", bs.map!"a[0]");
      }

      Tuple!(int, long)[] events;
      foreach (i; 0 .. N) {
        /*
          as[i]
          paired with bs[i], bs[i + 1], ..., bs[i + N - 1]
          + -> -
        */
        const j = bs.lowerBound(as[i]);
        debug {
          writeln("i = ", i, ": ", j);
        }
        events ~= tuple(0, as[i][0]);
        events ~= tuple(min(max(j - i, 0), N), -2 * as[i][0]);
      }
      foreach (j; 0 .. N) {
        /*
          bs[j]
          paired with as[j], as[j - 1], ..., as[0]
          - -> +

          k = j + 1

          bs[j + N]
          paired with as[N - 1], as[N - 2], ..., as[j + 1]
          - -> +
        */
        const i0 = as.lowerBound(bs[j]) - 1;
        const i1 = as.lowerBound(bs[j + N]) - 1;
        debug {
          writeln("j = ", j, ": ", i0, " ", i1);
        }
        events ~= tuple(0, -bs[j][0]);
        events ~= tuple(min(max(j - i0, 0), j + 1), 2 * bs[j][0]);
        events ~= tuple(j + 1, -bs[j][0] - bs[j + N][0]);
        events ~= tuple(min(max(j + N - i1, j + 1), N), 2 * bs[j + N][0]);
      }
      sort(events);
      events ~= tuple(N, 0L);
      debug {
        writeln("events = ", events);
      }

      long ans = M * N;
      int km;
      long now;
      int pos;
      foreach (k; 0 .. N) {
        for (; events[pos][0] <= k; ++pos) {
          now += events[pos][1];
        }
        debug {
          writeln("k = ", k, ": ", now);
        }
        if (chmin(ans, now)) {
          km = k;
        }
      }
      writeln(ans);
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(bs[i + km][1] + 1);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

long M;
int N;
long[] A, B;

void main() {
  try {
    for (; ; ) {
      M = readLong();
      N = readInt();
      A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong() % M;
      }
      B = new long[N];
      foreach (j; 0 .. N) {
        B[j] = readLong() % M;
      }

      auto as = new Tuple!(long, int)[N];
      auto bs = new Tuple!(long, int)[N];
      foreach (i; 0 .. N) {
        as[i] = tuple(A[i], i);
      }
      foreach (j; 0 .. N) {
        bs[j] = tuple(B[j], j);
        for (; 2 * bs[j][0] >= M; bs[j][0] -= M) {}
      }
      sort(as);
      sort(bs);
      bs.length = 2 * N;
      foreach (j; 0 .. N) {
        bs[j + N] = bs[j];
        bs[j + N][0] += M;
      }
      debug {
        writeln("as[*][0] = ", as.map!"a[0]");
        writeln("bs[*][0] = ", bs.map!"a[0]");
      }

      Tuple!(int, long)[] events;
      foreach (i; 0 .. N) {
        /*
          as[i]
          paired with bs[i], bs[i + 1], ..., bs[i + N - 1]
          + -> -
        */
        const j = bs.lowerBound(as[i]);
        debug {
          writeln("i = ", i, ": ", j);
        }
        events ~= tuple(0, as[i][0]);
        events ~= tuple(min(max(j - i, 0), N + 1), -2 * as[i][0]);
      }
      foreach (j; 0 .. N) {
        /*
          bs[j]
          paired with as[j], as[j - 1], ..., as[0]
          - -> +

          k = j + 1

          bs[j + N]
          paired with as[N - 1], as[N - 2], ..., as[j + 1], as[j]
          - -> +
        */
        const i0 = as.lowerBound(bs[j]) - 1;
        const i1 = as.lowerBound(bs[j + N]) - 1;
        debug {
          writeln("j = ", j, ": ", i0, " ", i1);
        }
        events ~= tuple(0, -bs[j][0]);
        events ~= tuple(min(max(j - i0, 0), j + 1), 2 * bs[j][0]);
        events ~= tuple(j + 1, -bs[j][0] - bs[j + N][0]);
        events ~= tuple(min(max(j + N - i1, j + 1), N + 1), 2 * bs[j + N][0]);
      }
      sort(events);
      events ~= tuple(N + 1, 0L);
      debug {
        writeln("events = ", events);
      }

      long ans = M * N;
      int km;
      long now;
      int pos;
      foreach (k; 0 .. N + 1) {
        for (; events[pos][0] <= k; ++pos) {
          now += events[pos][1];
        }
        debug {
          writeln("k = ", k, ": ", now);
        }
        if (chmin(ans, now)) {
          km = k;
        }
      }
      writeln(ans);
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(bs[i + km][1] + 1);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$. You have to choose two integers $$$l,r$$$ ($$$1 \le l \le r \le n$$$) and reverse the subsegment $$$[l,r]$$$ of the permutation. The permutation will become $$$p_1,p_2, \dots, p_{l-1},p_r,p_{r-1}, \dots, p_l,p_{r+1},p_{r+2}, \dots ,p_n$$$.Find the lexicographically smallest permutation that can be obtained by performing exactly one reverse operation on the initial permutation.Note that for two distinct permutations of equal length $$$a$$$ and $$$b$$$, $$$a$$$ is lexicographically smaller than $$$b$$$ if at the first position they differ, $$$a$$$ has the smaller element.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 500$$$) — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the elements of the permutation.

For each test case print the lexicographically smallest permutation you can obtain.

NoteIn the first test case, the permutation has length $$$1$$$, so the only possible segment is $$$[1,1]$$$. The resulting permutation is $$$[1]$$$.In the second test case, we can obtain the identity permutation by reversing the segment $$$[1,2]$$$. The resulting permutation is $$$[1,2,3]$$$.In the third test case, the best possible segment is $$$[2,3]$$$. The resulting permutation is $$$[1,2,4,3]$$$.In the fourth test case, there is no lexicographically smaller permutation, so we can leave it unchanged by choosing the segment $$$[1,1]$$$. The resulting permutation is $$$[1,2,3,4,5]$$$.

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

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


There are $$$n$$$ people in this world, conveniently numbered $$$1$$$ through $$$n$$$. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let $$$d(a,b)$$$ denote the debt of $$$a$$$ towards $$$b$$$, or $$$0$$$ if there is no such debt.Sometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money. When this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done:  Let $$$d(a,b) > 0$$$ and $$$d(c,d) > 0$$$ such that $$$a \neq c$$$ or $$$b \neq d$$$. We can decrease the $$$d(a,b)$$$ and $$$d(c,d)$$$ by $$$z$$$ and increase $$$d(c,b)$$$ and $$$d(a,d)$$$ by $$$z$$$, where $$$0 < z \leq \min(d(a,b),d(c,d))$$$.  Let $$$d(a,a) > 0$$$. We can set $$$d(a,a)$$$ to $$$0$$$. The total debt is defined as the sum of all debts:$$$$$$\Sigma_d = \sum_{a,b} d(a,b)$$$$$$Your goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the number of non-zero debts, only the total debt.

The first line contains two space separated integers $$$n$$$ ($$$1 \leq n \leq 10^5$$$) and $$$m$$$ ($$$0 \leq m \leq 3\cdot 10^5$$$), representing the number of people and the number of debts, respectively. $$$m$$$ lines follow, each of which contains three space separated integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), $$$d_i$$$ ($$$1 \leq d_i \leq 10^9$$$), meaning that the person $$$u_i$$$ borrowed $$$d_i$$$ burles from person $$$v_i$$$.

On the first line print an integer $$$m'$$$ ($$$0 \leq m' \leq 3\cdot 10^5$$$), representing the number of debts after the consolidation. It can be shown that an answer always exists with this additional constraint. After that print $$$m'$$$ lines, $$$i$$$-th of which contains three space separated integers $$$u_i, v_i, d_i$$$, meaning that the person $$$u_i$$$ owes the person $$$v_i$$$ exactly $$$d_i$$$ burles. The output must satisfy $$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$ and $$$0 < d_i \leq 10^{18}$$$. For each pair $$$i \neq j$$$, it should hold that $$$u_i \neq u_j$$$ or $$$v_i \neq v_j$$$. In other words, each pair of people can be included at most once in the output.

NoteIn the first example the optimal sequence of operations can be the following:  Perform an operation of the first type with $$$a = 1$$$, $$$b = 2$$$, $$$c = 2$$$, $$$d = 3$$$ and $$$z = 5$$$. The resulting debts are: $$$d(1, 2) = 5$$$, $$$d(2, 2) = 5$$$, $$$d(1, 3) = 5$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 2$$$. The resulting debts are: $$$d(1, 2) = 5$$$, $$$d(1, 3) = 5$$$, all other debts are $$$0$$$. In the second example the optimal sequence of operations can be the following:  Perform an operation of the first type with $$$a = 1$$$, $$$b = 2$$$, $$$c = 3$$$, $$$d = 1$$$ and $$$z = 10$$$. The resulting debts are: $$$d(3, 2) = 10$$$, $$$d(2, 3) = 15$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the first type with $$$a = 2$$$, $$$b = 3$$$, $$$c = 3$$$, $$$d = 2$$$ and $$$z = 10$$$. The resulting debts are: $$$d(2, 2) = 10$$$, $$$d(3, 3) = 10$$$, $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 2$$$. The resulting debts are: $$$d(3, 3) = 10$$$, $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 3$$$. The resulting debts are: $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 1$$$. The resulting debts are: $$$d(2, 3) = 5$$$, all other debts are $$$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.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]);
    }
}


A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.You are given a binary string $$$s$$$ of length $$$n$$$. Construct two balanced bracket sequences $$$a$$$ and $$$b$$$ of length $$$n$$$ such that for all $$$1\le i\le n$$$:   if $$$s_i=1$$$, then $$$a_i=b_i$$$  if $$$s_i=0$$$, then $$$a_i\ne b_i$$$ If it is impossible, you should report about it.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ is even). The next line contains a string $$$s$$$ of length $$$n$$$, consisting of characters 0 and 1. The sum of $$$n$$$ across all test cases does not exceed $$$2\cdot 10^5$$$.

If such two balanced bracked sequences exist, output "YES" on the first line, otherwise output "NO". You can print each letter in any case (upper or lower). If the answer is "YES", output the balanced bracket sequences $$$a$$$ and $$$b$$$ satisfying the conditions on the next two lines. If there are multiple solutions, you may print any.

NoteIn the first test case, $$$a=$$$"()()()" and $$$b=$$$"((()))". The characters are equal in positions $$$1$$$, $$$3$$$, $$$4$$$, and $$$6$$$, which are the exact same positions where $$$s_i=1$$$.In the second test case, $$$a=$$$"()()((()))" and $$$b=$$$"(())()()()". The characters are equal in positions $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$, $$$8$$$, $$$10$$$, which are the exact same positions where $$$s_i=1$$$.In the third test case, there is no solution.

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

string FMT_F = "%.10f";

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

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

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

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

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

		long cnt0, cnt1;
		foreach (i; 0..n)
		{
			if (s[i] == '0')
				++cnt0;
			else
				++cnt1;
		}

		long c0, c1;
		foreach (i; 0..n)
		{
			if (s[i] == '0')
			{
				ans[ti][0] ~= c0 % 2 ? ')' : '(';
				++c0;
			}
			else
			{
				ans[ti][0] ~= c1 < cnt1/2 ? '(' : ')';
				++c1;
			}
		}

		foreach (i; 0..n)
		{
			if (s[i] == '1')
				ans[ti][1] ~= ans[ti][0][i];
			else
				ans[ti][1] ~= ans[ti][0][i] == '(' ? ')' : '(';
		}

		bool ok = true;
		long cnt;
		foreach (i; 0..n)
		{
			if (ans[ti][1][i] == '(')
				++cnt;
			else
				--cnt;
			if (cnt < 0)
			{
				ok = false;
				break;
			}
		}
		if (cnt != 0)
			ok = false;
		if (!ok)
			ans[ti].length = 0;
	}

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

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

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

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

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

bool isValid(char[] cs) {
  int now;
  foreach (c; cs) {
    if (c == '(') {
      ++now;
    } else if (c == ')') {
      if (--now < 0) {
        return false;
      }
    } else {
      assert(false);
    }
  }
  return (now == 0);
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const S = readToken();

        auto as = new char[N];
        auto bs = new char[N];

        const cnt1 = cast(int)(S.count('1'));
        int pos0, pos1;
        foreach (i; 0 .. N) {
          if (S[i] == '0') {
            if (pos0 % 2 == 0) {
              as[i] = '(';
              bs[i] = ')';
            } else {
              as[i] = ')';
              bs[i] = '(';
            }
            ++pos0;
          } else {
            if (pos1 < cnt1 / 2) {
              as[i] = bs[i] = '(';
            } else {
              as[i] = bs[i] = ')';
            }
            ++pos1;
          }
        }
        debug {
          writeln("as = ", as);
          writeln("bs = ", bs);
        }

        bool ok = true;
        ok = ok && isValid(as);
        ok = ok && isValid(bs);
        if (ok) {
          writeln("YES");
          writeln(as);
          writeln(bs);
        } 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(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

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

		foreach (i; 0..n)
		{
			if (s[i] == '1')
				ans[ti] ~= i % 2 ? ')' : '(';
			else
				ans[ti] ~= i % 2 ? '(' : ')';
		}

		bool ok = true;
		long cnt;
		foreach (i; 0..n)
		{
			if (ans[ti][i] == '(')
				++cnt;
			else
				--cnt;
			if (cnt < 0)
			{
				ok = false;
				break;
			}
		}
		if (cnt != 0)
			ok = false;
		if (!ok)
			ans[ti].length = 0;
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			foreach (i; 0..e.length)
				write(i % 2 ? ")" : "(");
			writeln;
			writeln(e);
		}
	}
	stdout.flush;
	debug readln;
}


One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t.

The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.

In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.

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

void main() {
    int n; readf("%d\n", &n);
    int[] ls = new int[n];
    int[] rs = new int[n];
    for (int i = 0; i < n; i++) {
        readf("%d %d\n", &ls[i], &rs[i]);
    }
    int t = int.max;
    for (int l = 0; l <= 1; l++) {
        for (int r = 0; r <= 1; r++) {
            int u = 0;
            for (int i = 0; i < n; i++) {
                u += (l == ls[i]);
                u += (r == rs[i]);
            }
            t = min(t, u);
        }
    }
    t.writeln;
}