Monocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health $$$h_C$$$ and attack $$$d_C$$$; the monster initially has health $$$h_M$$$ and attack $$$d_M$$$. The fight consists of several steps:  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i. e. $$$0$$$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to $$$h_C$$$ and attack equal to $$$d_C$$$. He wants to slay a monster with health equal to $$$h_M$$$ and attack equal to $$$d_M$$$. Before the fight, Monocarp can spend up to $$$k$$$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $$$w$$$, and each armor upgrade increases the character's health by $$$a$$$.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. Each test case consists of three lines: The first line contains two integers $$$h_C$$$ and $$$d_C$$$ ($$$1 \le h_C \le 10^{15}$$$; $$$1 \le d_C \le 10^9$$$) — the character's health and attack; The second line contains two integers $$$h_M$$$ and $$$d_M$$$ ($$$1 \le h_M \le 10^{15}$$$; $$$1 \le d_M \le 10^9$$$) — the monster's health and attack; The third line contains three integers $$$k$$$, $$$w$$$ and $$$a$$$ ($$$0 \le k \le 2 \cdot 10^5$$$; $$$0 \le w \le 10^4$$$; $$$0 \le a \le 10^{10}$$$) — the maximum number of coins that Monocarp can spend, the amount added to the character's attack with each weapon upgrade, and the amount added to the character's health with each armor upgrade, respectively. The sum of $$$k$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print YES if it is possible to slay the monster by optimally choosing the upgrades. Otherwise, print NO.

NoteIn the first example, Monocarp can spend one coin to upgrade weapon (damage will be equal to $$$5$$$), then health during battle will change as follows: $$$(h_C, h_M) = (25, 9) \rightarrow (25, 4) \rightarrow (5, 4) \rightarrow (5, -1)$$$. The battle ended with Monocarp's victory.In the second example, Monocarp has no way to defeat the monster.In the third example, Monocarp has no coins, so he can't buy upgrades. However, the initial characteristics are enough for Monocarp to win.In the fourth example, Monocarp has $$$4$$$ coins. To defeat the monster, he has to spend $$$2$$$ coins to upgrade weapon and $$$2$$$ coins to upgrade armor.

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        if ((hm / dc == 0) || ((hm / dc == 1) && (hm % dc == 0)))
            return true;
        if ((hm / dc) < (hc / dm))
            return true;
        else if ((hm / dc) == (hc / dm))
        {
            if ((hm % dc) == 0)
                return true;
            else if ((hc % dm) == 0)
                return false;
            else
                return true;
        }
        else {
            if ((hm / dc - hc / dm == 1) && (hm % dc == 0) && (hc % dm != 0))
                return true;
            else
                return false;
        }
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        auto s = readln.split.to!(long[]);
        hc = s[0];
        dc = s[1];
        s = readln.split.to!(long[]);
        hm = s[0];
        dm = s[1];
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = fight(hc, dc, hm, dm);
        if (flag) {
                writeln("YES");
                continue;
            }
        for (int i = 0; i <= k; i++) {
            long new_hc = i*a + hc;
            long new_dc = (k-i)*w + dc;
            flag = fight(new_hc, new_dc, hm, dm);
            if (flag) {
                writeln("YES");
                break;
            }
        }
        if (!flag)
            writeln("NO");
    }
}

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        long reqMoves = hm / dc + (hm % dc != 0);
        long recoil = (reqMoves-1) * dm;

        if(hc > recoil){
            return true;
        }else{
            return false;
        }
    }
    bool fight2(long hc, long dc, long hm, long dm) {
        if ((hm / dc == 0) || ((hm / dc == 1) && (hm % dc == 0)))
            return true;
        if ((hm / dc) < (hc / dm))
            return true;
        else if ((hm / dc) == (hc / dm))
        {
            if ((hm % dc) == 0)
                return true;
            else if ((hc % dm) == 0)
                return false;
            else
                return true;
        }
        else {
            if ((hm / dc - hc / dm == 1) && (hm % dc == 0) && (hc % dm != 0))
                return true;
            else
                return false;
        }
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        auto s = readln.split.to!(long[]);
        hc = s[0];
        dc = s[1];
        s = readln.split.to!(long[]);
        hm = s[0];
        dm = s[1];
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = false;

        for (int i = 0; i <= k; ++i) {
            long new_hc = i*a + hc;
            long new_dc = (k-i)*w + dc;
            flag = fight2(new_hc, new_dc, hm, dm);
            if (flag) {
                break;
            }
        }
        if (flag)
            writeln("YES");
        else
            writeln("NO");
    }
}

bool canDestroy(long hc, long dc, long hm, long dm){
    long reqMoves = hm / dc + (hm % dc != 0);
    long recoil = (reqMoves-1) * dm;
    if(hc > recoil){
        return 1;
    }else{
        return 0;
    }
}

void solve(){
    long hc = scan;
    long dc = scan;

    long hm = scan;
    long dm = scan;

    int k = scan!int;
    long w = scan;
    long a = scan;

    for(int x = 0; x <= k; ++x){
        long nhc = hc + x * a;
        long ndc = dc + (k - x) * w;
        if(canDestroy(nhc, ndc, hm, dm)){
            writeln("YES");
            return;
        }
    }
    writeln("NO");
}

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

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

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        long reqMoves = hm / dc + (hm % dc != 0);
    long recoil = (reqMoves-1) * dm;
    if(hc > recoil){
        return true;
    }else{
        return false;
    }
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        scanf("%ld %ld", &hc, &dc);
        getchar();
        scanf("%ld %ld", &hm, &dm);
        getchar();
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = false;

        for (int i = 0; i <= k; ++i) {
            long new_hc = i*a + hc;
            long new_dc = (k-i)*w + dc;
            flag = fight(new_hc, new_dc, hm, dm);
            if (flag) {
                break;
            }
        }
        if (flag)
            writeln("YES");
        else
            writeln("NO");
    }
}

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        long reqMoves = hm / dc + (hm % dc != 0);
    long recoil = (reqMoves-1) * dm;
    if(hc > recoil){
        return true;
    }else{
        return false;
    }
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        scanf("%ld %ld", &hc, &dc);
        getchar();
        scanf("%ld %ld", &hm, &dm);
        getchar();
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = false;

        for (int i = 0; i <= k; i++) {
            long new_hc = i*a + hc;
            long new_dc = (k-i)*w + dc;
            flag = fight(new_hc, new_dc, hm, dm);
            if (flag) {
                break;
            }
        }
        if (flag)
            writeln("YES");
        else
            writeln("NO");
    }
}

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        long reqMoves = hm / dc + (hm % dc != 0);
    long recoil = (reqMoves-1) * dm;
    if(hc > recoil){
        return true;
    }else{
        return false;
    }
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        scanf("%ld %ld", &hc, &dc);
        getchar();
        scanf("%ld %ld", &hm, &dm);
        getchar();
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = fight(hc, dc, hm, dm);
        if (flag) {
                writeln("YES");
                continue;
            }
        for (int i = 0; i <= k; i++) {
            long new_hc = i*a + hc;
            long new_dc = (k-i)*w + dc;
            flag = fight(new_hc, new_dc, hm, dm);
            if (flag) {
                writeln("YES");
                break;
            }
        }
        if (!flag)
            writeln("NO");
    }
}

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        if ((hm / dc == 0) || ((hm / dc == 1) && (hm % dc == 0)))
            return true;
        if ((hm / dc) < (hc / dm))
            return true;
        else if ((hm / dc) == (hc / dm))
        {
            if ((hm % dc) == 0)
                return true;
            else if ((hc % dm) == 0)
                return false;
            else
                return true;
        }
        else {
            if ((hm / dc - hc / dm == 1) && (hm % dc == 0) && (hc % dm != 0))
                return true;
            else
                return false;
        }
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        scanf("%ld %ld", &hc, &dc);
        getchar();
        scanf("%ld %ld", &hm, &dm);
        getchar();
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = fight(hc, dc, hm, dm);
        if (flag) {
                writeln("YES");
                continue;
            }
        for (int i = 0; i <= k; i++) {
            long new_hc = i*a + hc;
            long new_dc = (k-i)*w + dc;
            flag = fight(new_hc, new_dc, hm, dm);
            if (flag) {
                writeln("YES");
                break;
            }
        }
        if (!flag)
            writeln("NO");
    }
}

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        if ((hm / dc) < (hc / dm))
            return true;
        else if ((hm / dc == 0) || ((hm / dc == 1) && (hm % dc == 0)))
            return true;
        else if ((hm / dc) == (hc / dm))
        {
            if ((hm % dc) == 0)
                return true;
            else if ((hc % dm) == 0)
                return false;
            else
                return true;
        }
        else {
            if ((hm / dc - hc / dm == 1) && (hm % dc == 0))
                return true;
            else
                return false;
        }
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        scanf("%ld %ld", &hc, &dc);
        getchar();
        scanf("%ld %ld", &hm, &dm);
        getchar();
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = fight(hc, dc, hm, dm);
        if (flag) {
                writeln("YES");
                continue;
            }
        for (int i = 0; i <= k; i++) {
            auto new_hc = i*a + hc;
            auto new_dc = (k-i)*w + dc;
            flag = fight(new_hc, new_dc, hm, dm);
            if (flag) {
                writeln("YES");
                break;
            }
        }
        if (!flag)
            writeln("NO");
    }
}

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        if ((hm / dc) < (hc / dm))
            return true;
        else if ((hm / dc) == (hc / dm))
        {
            if ((hm % dc) == 0)
                return true;
            else if ((hc % dm) == 0)
                return false;
            else
                return true;
        }
        else
            return false;
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        scanf("%ld %ld", &hc, &dc);
        getchar();
        scanf("%ld %ld", &hm, &dm);
        getchar();
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = fight(hc, dc, hm, dm);
        if (flag) {
                writeln("YES");
                continue;
            }
        for (int i = 0; i <= k; i++) {
            auto new_hc = i*a + hc;
            auto new_dc = (k-i)*w + dc;
            flag = fight(new_hc, new_dc, hm, dm);
            if (flag) {
                writeln("YES");
                break;
            }
        }
        if (!flag)
            writeln("NO");
    }
}

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        if ((hm / dc) <= (hc / dm))
            return true;
        else
            return false;
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        scanf("%ld %ld", &hc, &dc);
        getchar();
        scanf("%ld %ld", &hm, &dm);
        getchar();
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = fight(hc, dc, hm, dm);
        if (flag) {
                writeln("YES");
                continue;
            }
        for (int i = 0; i <= k; i++) {
            auto new_hc = i*a + hc;
            auto new_dc = (k-i)*w + dc;
            flag = fight(new_hc, new_dc, hm, dm);
            if (flag) {
                writeln("YES");
                break;
            }
        }
        if (!flag)
            writeln("NO");
    }
}

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        if ((hm / dc) <= (hc / dm))
            return true;
        else
            return false;
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        scanf("%ld %ld", &hc, &dc);
        getchar();
        scanf("%ld %ld", &hm, &dm);
        getchar();
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = fight(hc, dc, hm, dm);
        if (flag) {
                writeln("YES");
                continue;
            }
        for (int i = 0; i < k; i++) {
            auto new_hc = i*a + hc;
            auto new_dc = (k-i)*w + dc;
            flag = fight(new_hc, new_dc, hm, dm);
            if (flag) {
                writeln("YES");
                break;
            }
        }
        if (!flag)
            writeln("NO");
    }
}

import std;

void main()
{

    bool fight(long hc, long dc, long hm, long dm) {
        if ((hm / dc) >= (hc / dm))
            return true;
        else
            return false;
    }

    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        long hc, dc, hm, dm;
        scanf("%ld %ld", &hc, &dc);
        getchar();
        scanf("%ld %ld", &hm, &dm);
        getchar();
        long k, a, w;
        scanf("%ld %ld %ld", &k, &w, &a);
        getchar();
        bool flag = false;
        for (int i = 0; i < k; i++) {
            auto new_hc = i*a + hc;
            auto new_dc = (k-i)*w + dc;
            flag = fight(new_hc, new_dc, hm, dm);
            if (flag) {
                writeln("YES");
                break;
            }
        }
        if (!flag)
            writeln("NO");
    }
}


Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.

The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.

If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).

NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Dsu(int maxn) {
    int[maxn] p, sz;

    int get(int x) {
        return x == p[x] ? x : (p[x] = get(p[x]));
    }

    void merge(int x, int y) {
        x = get(x);
        y = get(y);
        if (x != y) {
            p[x] = y;
            sz[y] += sz[x];
        }
    }
}

int n, m;
Dsu!150_000 dsu;

void main() {
    while (read(n, m)) {
        iota(n).copy(dsu.p[ ]);
        dsu.sz[0 .. n] = 1;
        foreach (i; 0 .. m) {
            int x, y;
            read(x, y);
            x--;
            y--;
            dsu.merge(x, y);
        }
        long total = m << 1;
        foreach (i; 0 .. n)
            if (dsu.p[i] == i)
                total -= dsu.sz[i] * cast(long)(dsu.sz[i] - 1);
        writeln(total ? "NO" : "YES");
    }
}

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

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

      auto uf = new int[N];
      uf[] = -1;
      foreach (i; 0 .. M) {
        uf.connect(A[i], B[i]);
      }

      long m;
      foreach (r; 0 .. N) {
        if (uf[r] < 0) {
          const sz = -uf[r];
          m += 1L * sz * (sz - 1) / 2;
        }
      }

      writeln((m == M) ? "YES" : "NO");
    }
  } 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;

alias Tuple!(int, "a", int, "b") Edge;

int N, M;
int[][] adj;
bool[] used;
bool[Edge] cnt;

long dfs(int n) {
    used[n] = true;
    int ret = 1;

    foreach (m; adj[n]) {
        cnt[Edge(min(n, m), max(n, m))] = true;
        if (!used[m]) ret += dfs(m);
    }

    return ret;
}

void main() {
    auto s = readln.split.map!(to!int);
    N = s[0];
    M = s[1];
    adj = new int[][](N);
    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        adj[s[0]-1] ~= s[1]-1;
        adj[s[1]-1] ~= s[0]-1;
    }

    used = new bool[](N);
    foreach (i; 0..N) {
        if (!used[i]) {
            cnt.clear;
            long r = dfs(i);
            if (cnt.keys.length != r * (r-1) / 2) {
                writeln("NO");
                return;
            }
        }
    }

    writeln("YES") ;
}

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;

alias Tuple!(int, "a", int, "b") Edge;

int N, M;
int[][] adj;
bool[] used;
bool[Edge] cnt;

int dfs(int n) {
    used[n] = true;
    int ret = 1;

    foreach (m; adj[n]) {
        cnt[Edge(min(n, m), max(n, m))] = true;
        if (!used[m]) ret += dfs(m);
    }

    return ret;
}

void main() {
    auto s = readln.split.map!(to!int);
    N = s[0];
    M = s[1];
    adj = new int[][](N);
    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        adj[s[0]-1] ~= s[1]-1;
        adj[s[1]-1] ~= s[0]-1;
    }

    used = new bool[](N);
    foreach (i; 0..N) {
        if (!used[i]) {
            cnt.clear;
            int r = dfs(i);
            if (cnt.keys.length != r * (r-1) / 2) {
                writeln("NO");
                return;
            }
        }
    }

    writeln("YES") ;
}


Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.You are given a string $$$s$$$, you have to delete minimum number of characters from this string so that it becomes good.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.

In the first line, print one integer $$$k$$$ ($$$0 \le k \le n$$$) — the minimum number of characters you have to delete from $$$s$$$ to make it good. In the second line, print the resulting string $$$s$$$. If it is empty, you may leave the second line blank, or not print it at all.

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

    dchar[] T;

    foreach (i; 0..N) {
        if (T.empty) {
            T ~= S[i];
        } else if (T.back == S[i] && T.length % 2 == 1) {

        } else {
            T ~= S[i];
        }
    }

    int rest = T.length.to!int;
    int ans = N - rest;
    if (rest % 2 == 1) {
        ans += 1;
        T = T[0..$-1];
    }

    ans.writeln;
    T.writeln;
}

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

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

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

	int n = read.to!int;
	string s = readln.chomp;

	char[] ans;
	int i = 0, j = 1;
	while(j < n) if(s[i] != s[j]) ans ~= s[i], ans ~= s[j], i = j + 1, j = i + 1; else j += 1;

	(n - ans.length).writeln;
	ans.writeln;
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

void main() {
    GC.disable();

    int n;
    readf(" %s\n", n);

    auto  s = readln().strip().dup;
    if (s.length == 0) { writefln("%s\n%s", 0, s); return ; }

    char [] ans;
    foreach(i; 0 .. s.length) {

      if (ans.length == 0) {
        ans ~= s[i];
      } else {
        if ( ans.length % 2 ==0 || ans[$-1] != s[i]) ans ~= s[i];
      }
    }

    if (ans.length % 2 == 1) {
      ans = ans [0 .. $ - 1];
    }

    writefln("%s\n%s", s.length - ans.length, ans);

}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto N = RD!int;
	auto a = RD!string;

	string ans;
	ans ~= a[0];
	long cnt;
	char last = a[0];
	foreach (i; 1..N)
	{
		if ((i-cnt) % 2 == 1)
		{
			if (a[i] == last)
			{
				++cnt;
				continue;
			}
		}
		last = a[i];
		ans ~= a[i];
	}
	if (ans.length % 2 == 1)
	{
		ans.popBack;
		++cnt;
	}

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


You are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 106) — the number of segments and the value of k. The next n lines contain two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109) each — the endpoints of the i-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.

First line contains integer m — the smallest number of segments. Next m lines contain two integers aj, bj (aj ≤ bj) — the ends of j-th segment in the answer. The segments should be listed in the order from left to right.

import std.algorithm;
import std.stdio;
import std.typecons;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		int [] a;
		foreach (i; 0..n)
		{
			int p, q;
			readf (" %s %s", &p, &q);
			a ~= p * 2 + 0;
			a ~= q * 2 + 1;
		}
		sort (a);

		int b = 0;
		int start;
		int [2] [] ans;
		foreach (e; a)
		{
			int d = (e & 1) ? -1 : +1;
			int x = e >> 1;
			b += d;
			if (b == k && d == +1)
			{
				start = x;
			}
			if (b == k - 1 && d == -1)
			{
				ans ~= [start, x];
			}
		}

		writefln ("%s\n%(%(%s %)\n%)", ans.length, ans);
	}
}

import std.algorithm;
import std.stdio;
import std.typecons;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		alias Event = Tuple !(int, q{x}, int, q{d});
		Event [] a;
		foreach (i; 0..n)
		{
			int p, q;
			readf (" %s %s", &p, &q);
			a ~= Event (p, -1);
			a ~= Event (q, +1);
		}
		sort !(q{a < b}, SwapStrategy.stable) (a);

		int b = 0;
		int start;
		int [2] [] ans;
		foreach (e; a)
		{
			b -= e.d;
			if (b == k && e.d == -1)
			{
				start = e.x;
			}
			if (b == k - 1 && e.d == +1)
			{
				ans ~= [start, e.x];
			}
		}

		writefln ("%s\n%(%(%s %)\n%)", ans.length, ans);
	}
}

import std.algorithm;
import std.stdio;
import std.typecons;

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		alias Event = Tuple !(int, q{x}, int, q{d});
		Event [] a;
		foreach (i; 0..n)
		{
			int p, q;
			readf (" %s %s", &p, &q);
			a ~= Event (p, -1);
			a ~= Event (q, +1);
		}
		sort (a);

		int b = 0;
		int start;
		int [2] [] ans;
		foreach (e; a)
		{
			b -= e.d;
			if (b == k && e.d == -1)
			{
				start = e.x;
			}
			if (b == k - 1 && e.d == +1)
			{
				ans ~= [start, e.x];
			}
		}

		writefln ("%s\n%(%(%s %)\n%)", ans.length, ans);
	}
}

module main;

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

alias Action = Tuple! (int, "coord", bool, "isClose");
alias Segment = Tuple! (int, "left", int, "right");

int main() {

    int n, k;

    readf(" %d %d", &n, &k);
    readln();

    Action[] actions;

    foreach (int i; 0..n) {
        auto temp = readln().strip().split().map! (to! (int)).array();

        actions ~= Action (temp[0], false);
        actions ~= Action (temp[1], true);
    }

    sort(actions);

    debug {writeln(actions);};

    int currentCountOfIntersections;
    int[] opens;
    Segment[] result;
    foreach (int i; 0..actions.length)
        if (!(actions[i].isClose)) {
            opens.assumeSafeAppend();
            opens ~= actions[i].coord;
            currentCountOfIntersections++;
        } else {
            if (currentCountOfIntersections == k)
                result ~= Segment (opens.back, actions[i].coord);

            opens.popBack();
            currentCountOfIntersections--;
        }

    writeln(result.length);
    foreach (int i; 0..result.length)
        writeln(result[i][0], ' ', result[i][1]);

	return 0;
}

module main;

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

int main() {

    auto s = readln().strip();

    char[] stack;
    string open = "({[<";
    string close = ")}]>";

    int result;

    bool flag = true;
    foreach (int i; 0..s.length)
        if (canFind(open, s[i])) {
            stack.assumeSafeAppend();
            stack ~= s[i];
        } else {
            if (stack.length == 0 || canFind(stack.back.to! (string), close)) {
                flag = false;
                break;
            }

            if (s[i] == ')' && stack.back != '(' || s[i] == '}' && stack.back != '{' || s[i] == ']' &&
                stack.back != '[' || s[i] == '>' && stack.back != '<')
                    result++;

            stack.popBack();
        }

    writeln((flag && stack.length == 0) ? result.to! (string) : "Impossible");

	return 0;
}


Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n × m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a × b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.

The first line contains two integers n and m (1 ≤ n, m ≤ 50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1 ≤ a, b ≤ 50). Note that Vasya can choose for building an a × b rectangle as well a b × a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m.

Print the minimum number of trees that needs to be chopped off to select a land lot a × b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a ≤ n and b ≤ m, or a ≤ m и b ≤ n.

NoteIn the second example the upper left square is (1,1) and the lower right is (3,2).

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

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

int a, b, n, m;
int[][] mat;

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                n = cin.readInt;
                m = cin.readInt;
                mat = new int[][](n, m);
                for (int i = 0; i < n; i++) {
                        for (int j = 0; j < m; j++) {
                                mat[i][j] = cin.readInt;
                        }
                }
                a = cin.readInt;
                b = cin.readInt;
                if (a == b) writeln(colWise());
                else writeln(min(colWise(), rowWise()));
        }
}

int colWise() {
        int minn = 99999999;
        for (int i = 0; i < n - b + 1; i++) {
                for (int j = 0; j < m - a + 1; j++) {
                        int trees = 0;
                        for (int dx = 0; dx < b; dx++) {
                                for (int dy = 0; dy < a; dy++) {
                                        if (mat[i + dx][j + dy]) trees++;
                                }
                        }
                        minn = min(minn, trees);
                }
        }
        return minn;
}

int rowWise() {
        int minn = 99999999;
        for (int i = 0; i < n - a + 1; i++) {
                for (int j = 0; j < m - b + 1; j++) {
                        int trees = 0;
                        for (int dx = 0; dx < a; dx++) {
                                for (int dy = 0; dy < b; dy++) {
                                        if (mat[i + dx][j + dy]) trees++;
                                }
                        }
                        minn = min(minn, trees);
                }
        }
        return minn;
}

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

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

int n, m;
int[][] mat;

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                n = cin.readInt;
                m = cin.readInt;
                mat = new int[][](n, m);
                for (int i = 0; i < n; i++) {
                        for (int j = 0; j < m; j++) {
                                mat[i][j] = cin.readInt;
                        }
                }
                int a, b;
                a = cin.readInt;
                b = cin.readInt;
                writeln(min(solve(a, b), solve(b, a)));
        }
}

int solve(int a, int b) {
        int minn = 99999999;
        for (int i = 0; i < n - b + 1; i++) {
                for (int j = 0; j < m - a + 1; j++) {
                        int trees = 0;
                        for (int dx = 0; dx < b; dx++) {
                                for (int dy = 0; dy < a; dy++) {
                                        if (mat[i + dx][j + dy]) trees++;
                                }
                        }
                        minn = min(minn, trees);
                }
        }
        return minn;
}


Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs:  some dwarf in one of the chosen lines is located in the rightmost cell of his row;  some dwarf in the chosen lines is located in the cell with the candy. The point of the game is to transport all the dwarves to the candy cells.Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.

The first line of the input contains two integers n and m (1 ≤ n ≤ 1000; 2 ≤ m ≤ 1000).  Next n lines each contain m characters — the game field for the "Candy Martix 2: Reload". Character "*" represents an empty cell of the field, character "G" represents a dwarf and character "S" represents a candy. The matrix doesn't contain other characters. It is guaranteed that each line contains exactly one character "G" and one character "S".

In a single line print a single integer — either the minimum number of moves needed to achieve the aim of the game, or -1, if the aim cannot be achieved on the given game field.

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

void main() {
    int H, W; scanf("%d %d\n", &H, &W);
    auto F = new string[H];
    foreach (i; 0 .. H) {
        F[i] = readln.chomp;
    }

    auto G = new int[H],
         S = new int[H];
    foreach (i; 0 .. H) {
        int g = cast(int)F[i].countUntil('G'),
            s = cast(int)F[i].countUntil('S');
        if (g > s) { writeln(-1); return; }
        G[i] = g;
        S[i] = s;
    }

    const INF = int.max / 2;

    int ans = 0;
    auto done = new bool[H];
    bool step() {
        int M = INF;
        foreach (i; 0 .. H) {
            if (G[i] == S[i]) continue;
            int g = G[i],
                s = S[i];
            M = min(M, s - g);
        }
        if (M < INF) {
            ans++;
            foreach (i; 0 .. H) {
                if (G[i] == S[i]) continue;
                G[i] += M;
            }
        }
        return M < INF;
    }

    while (step()) {}

    writeln(ans);

}


In this problem you will write a simple generator of Brainfuck (https://en.wikipedia.org/wiki/Brainfuck) calculators.You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of evaluating this expression.We use a fairly standard Brainfuck interpreter for checking the programs: 30000 memory cells. memory cells store integers from 0 to 255 with unsigned 8-bit wraparound. console input (, command) is not supported, but it's not needed for this problem.

The only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive. The calculations result is guaranteed to be an integer between 0 and 255, inclusive (results of intermediary calculations might be outside of these boundaries).

Output a Brainfuck program which, when executed, will print the result of evaluating this expression. The program must be at most 5000000 characters long (including the non-command characters), and its execution must be complete in at most 50000000 steps.

NoteYou can download the source code of the Brainfuck interpreter by the link http://assets.codeforces.com/rounds/784/bf.cpp. We use this code to interpret outputs.

import core.bitop;
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.regex;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		int v = 0;
		auto t = splitter !(Yes.keepSeparators) (s, regex ("[+-]"));
		v = t.front.to !(int);
		t.popFront ();
		while (!t.empty)
		{
			string op = t.front;
			t.popFront ();
			int w = t.front.to !(int);
			t.popFront ();
			if (op == "+")
			{
				v += w;
			}
			else
			{
				v -= w;
			}
		}
		if (v >= 100)
		{
			writefln ("%-(%s%).>", "+".repeat ((v / 100) + 48));
			v %= 100;
		}
		if (v >= 10)
		{
			writefln ("%-(%s%).>", "+".repeat ((v / 10) + 48));
			v %= 10;
		}
		if (v >= 0)
		{
			writefln ("%-(%s%).>", "+".repeat ((v / 1) + 48));
		}
//		writefln ("%-(%s%).>", "+".repeat (10));
	}
}

import core.bitop;
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.regex;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		int v = 0;
		auto t = splitter !(Yes.keepSeparators) (s, regex ("[+-]"));
		v = t.front.to !(int);
		t.popFront ();
		while (!t.empty)
		{
			string op = t.front;
			t.popFront ();
			int w = t.front.to !(int);
			t.popFront ();
			if (op == "+")
			{
				v += w;
			}
			else
			{
				v -= w;
			}
		}
		if (v >= 100)
		{
			writefln ("%-(%s%).>", "+".repeat ((v / 100) + 48));
			v %= 100;
		}
		if (v >= 10)
		{
			writefln ("%-(%s%).>", "+".repeat ((v / 10) + 48));
			v %= 10;
		}
		if (v >= 0)
		{
			writefln ("%-(%s%).>", "+".repeat ((v / 1) + 48));
		}
		writefln ("%-(%s%).>", "+".repeat (10));
	}
}

import core.bitop;
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.regex;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		int v = 0;
		auto t = splitter !(Yes.keepSeparators) (s, regex ("[+-]"));
		v = t.front.to !(int);
		t.popFront ();
		while (!t.empty)
		{
			string op = t.front;
			t.popFront ();
			int w = t.front.to !(int);
			t.popFront ();
			if (op == "+")
			{
				v += w;
			}
			else
			{
				v -= w;
			}
		}
		writefln ("%-(%s%).", "+".repeat (v));
	}
}


Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.

The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.

Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.

NoteIn the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.

import std.stdio;
import std.array;
import std.conv;
import std.algorithm;
int[]get()
{
	string[]s=split(readln());
	int[]r;
	for(int i=0;i<s.length;i++)r~=to!int(s[i]);
	return r;
}
void main()
{
	int num;
	readf("%d\n",&num);
	int[]a=get();
	int ans=0;
	int now=0;
	for(;;)
	{
		for(int i=0;i<num;i++)
		{
			if(now>=a[i])
			{
				a[i]=1000000000;
				now++;
			}
		}
		if(now==num)break;
		ans++;
		for(int i=num-1;i>=0;i--)
		{
			if(now>=a[i])
			{
				a[i]=1000000000;
				now++;
			}
		}
		if(now==num)break;
		ans++;
	}
	writeln(ans);
	readln();
}


You have an $$$n \times n$$$ chessboard and $$$k$$$ rooks. Rows of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from top to bottom and columns of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from left to right. The cell $$$(x, y)$$$ is the cell on the intersection of row $$$x$$$ and collumn $$$y$$$ for $$$1 \leq x \leq n$$$ and $$$1 \leq y \leq n$$$.The arrangement of rooks on this board is called good, if no rook is beaten by another rook.A rook beats all the rooks that shares the same row or collumn with it.The good arrangement of rooks on this board is called not stable, if it is possible to move one rook to the adjacent cell so arrangement becomes not good. Otherwise, the good arrangement is stable. Here, adjacent cells are the cells that share a side.  Such arrangement of $$$3$$$ rooks on the $$$4 \times 4$$$ chessboard is good, but it is not stable: the rook from $$$(1, 1)$$$ can be moved to the adjacent cell $$$(2, 1)$$$ and rooks on cells $$$(2, 1)$$$ and $$$(2, 4)$$$ will beat each other. Please, find any stable arrangement of $$$k$$$ rooks on the $$$n \times n$$$ chessboard or report that there is no such arrangement.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq k \leq n \leq 40$$$) — the size of the chessboard and the number of rooks.

If there is a stable arrangement of $$$k$$$ rooks on the $$$n \times n$$$ chessboard, output $$$n$$$ lines of symbols . and R. The $$$j$$$-th symbol of the $$$i$$$-th line should be equals R if and only if there is a rook on the cell $$$(i, j)$$$ in your arrangement. If there are multiple solutions, you may output any of them. If there is no stable arrangement, output $$$-1$$$.

NoteIn the first test case, you should find stable arrangement of $$$2$$$ rooks on the $$$3 \times 3$$$ chessboard. Placing them in cells $$$(3, 1)$$$ and $$$(1, 3)$$$ gives stable arrangement.In the second test case it can be shown that it is impossbile to place $$$3$$$ rooks on the $$$3 \times 3$$$ chessboard to get stable arrangement.

import std.algorithm, std.range, std.stdio, std.numeric, std.array, std.exception,
       std.container, std.typecons, std.conv, std.random, std.bigint;

void read(S...)(ref S args) {
  auto input = readln.split;
  enforce(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

void main() {
  int T;
  read(T);
  while (T--) {
    int n, k;
    read(n, k);
    if (k * 2 - 1 > n) {
      writeln(-1);
      continue;
    }

    auto board = new char[][](n, n);
    foreach (ref c; board) c[] = '.';

    foreach (i; 0 .. k) {
      board[i * 2][i * 2] = 'R';
    }

    foreach (c; board) writeln(c);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (k > (n+1)/2) continue;
		ans[ti].length = n;
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				if (i/2 < k && i % 2 != 1)
				{
					if (i == j)
						ans[ti][i] ~= "R";
					else
						ans[ti][i] ~= ".";
				}
				else
					ans[ti][i] ~= ".";
			}
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln(-1);
		else
		{
			foreach (ee; e)
				writeln(ee);
		}
	}
	stdout.flush;
	debug readln;
}

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s "(n); return n; }();
        immutable k = (){ uint k; readf!"%s\n"(k); return k; }();

        auto r = iota(0, n, 2).take(k);

        if (r.length < k) {
            writeln("-1");
            continue;
        }

        foreach (i; 0 .. n) {
            foreach (j; 0 .. n)
                if (!r.empty && r.front == i && r.front == j) {
                    write('R');
                    r.popFront();
                } else
                    write('.');
            writeln();
        }
    }
}
// ""

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

string solve (int n, int k)
{
	int c = 0;
	auto board = new char [] [] (n, n);
	foreach (ref line; board)
	{
		line[] = '.';
	}
	while (k > 0 && c < n)
	{
		board[c][c] = 'R';
		k -= 1;
		c += 2;
	}
	if (k == 0)
	{
		return format !("%-(%s\n%)") (board);
	}
	else
	{
		return "-1";
	}
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		writeln (solve (n, k));
	}
}


There is a rectangular grid of size $$$n \times m$$$. Each cell has a number written on it; the number on the cell ($$$i, j$$$) is $$$a_{i, j}$$$. Your task is to calculate the number of paths from the upper-left cell ($$$1, 1$$$) to the bottom-right cell ($$$n, m$$$) meeting the following constraints:  You can move to the right or to the bottom only. Formally, from the cell ($$$i, j$$$) you may move to the cell ($$$i, j + 1$$$) or to the cell ($$$i + 1, j$$$). The target cell can't be outside of the grid.  The xor of all the numbers on the path from the cell ($$$1, 1$$$) to the cell ($$$n, m$$$) must be equal to $$$k$$$ (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and "xor" in Pascal). Find the number of such paths in the given grid.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 20$$$, $$$0 \le k \le 10^{18}$$$) — the height and the width of the grid, and the number $$$k$$$. The next $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line is $$$a_{i, j}$$$ ($$$0 \le a_{i, j} \le 10^{18}$$$).

Print one integer — the number of paths from ($$$1, 1$$$) to ($$$n, m$$$) with xor sum equal to $$$k$$$.

NoteAll the paths from the first example:   $$$(1, 1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (3, 2) \rightarrow (3, 3)$$$;  $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (3, 3)$$$;  $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (3, 2) \rightarrow (3, 3)$$$. All the paths from the second example:   $$$(1, 1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (3, 2) \rightarrow (3, 3) \rightarrow (3, 4)$$$;  $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (3, 2) \rightarrow (3, 3) \rightarrow (3, 4)$$$;  $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (2, 4) \rightarrow (3, 4)$$$;  $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (3, 3) \rightarrow (3, 4)$$$;  $$$(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3) \rightarrow (3, 3) \rightarrow (3, 4)$$$.

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

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

    long[][] arr;
    foreach (_; 0 .. n) arr ~= readln.chomp.split.map!(to!long).array;

    long [long][][2] res = new long [long][][] (2, n);
    void go(long cval, int x, int y, int stepsLeft, immutable int dir, immutable int turn) {
        cval ^= arr[x][y];
        --stepsLeft;

        if (stepsLeft == 0) {
            debug { writeln(x, ' ', y, ' ', cval); }
            res[turn][x][cval] += 1;
            return;
        }

        if (x + dir >= 0 && x + dir < n) go(cval, x + dir, y, stepsLeft, dir, turn);
        if (y + dir >= 0 && y + dir < m) go(cval, x, y + dir, stepsLeft, dir, turn);
    }

    go(0, 0, 0, n, 1, 0);
    go(0, n-1, m-1, m, -1, 1);

    long ans = 0L;
    foreach (rw; 0 .. n) {
        foreach (el, val; res[0][rw]) {
            el ^= arr[rw][n-1 - rw];
            debug { el.writeln; }
            ans += val * res[1][rw].get(el ^ k , 0L);
        }
    }

    ans.writeln;
}

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

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

    long[][] arr;
    foreach (_; 0 .. n) arr ~= readln.chomp.split.map!(to!long).array;

    auto res = new int [long][][] (n, m);

    res[0][0][arr[0][0]] = 1;

    debug { arr.writeln; }

    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            long cure = arr[i][j];

            auto compute = (ref int [long] sq) => sq.each!((k, v) => res[i][j][k ^ cure] += v);

            if (i > 0) compute(res[i-1][j]);
            if (j > 0) compute(res[i][j-1]);
        }
    }

    debug { res.writeln; }

    res[n-1][m-1].get(k, 0).writeln;
}

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

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

    long[][] arr;
    foreach (_; 0 .. n) arr ~= readln.chomp.split.map!(to!long).array;

    long [long][][2] res = new long [long][][] (2, n);
    void go(long cval, int x, int y, int stepsLeft, immutable int dir, immutable int turn) {
        cval ^= arr[x][y];
        --stepsLeft;

        if (stepsLeft == 0) {
            debug { writeln(x, ' ', y, ' ', cval); }
            res[turn][x][cval] += 1;
            return;
        }

        if (x + dir >= 0 && x + dir < n) go(cval, x + dir, y, stepsLeft, dir, turn);
        if (y + dir >= 0 && y + dir < m) go(cval, x, y + dir, stepsLeft, dir, turn);
    }

    go(0, 0, 0, n, 1, 0);
    go(0, n-1, m-1, m, -1, 1);

    long ans = 0L;
    foreach (rw; 0 .. n) {
        foreach (el, val; res[0][rw]) {
            el ^= arr[n-1 - rw][rw];
            debug { el.writeln; }
            ans += val * res[1][rw].get(el ^ k , 0L);
        }
    }

    ans.writeln;
}


Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.Monocarp went around the building and counted $$$n$$$ windows. Now he is wondering, how many apartments of each type the building may have.Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has $$$n$$$ windows. If there are multiple answers, you can print any of them.Here are some examples:  if Monocarp has counted $$$30$$$ windows, there could have been $$$2$$$ three-room apartments, $$$2$$$ five-room apartments and $$$2$$$ seven-room apartments, since $$$2 \cdot 3 + 2 \cdot 5 + 2 \cdot 7 = 30$$$;  if Monocarp has counted $$$67$$$ windows, there could have been $$$7$$$ three-room apartments, $$$5$$$ five-room apartments and $$$3$$$ seven-room apartments, since $$$7 \cdot 3 + 5 \cdot 5 + 3 \cdot 7 = 67$$$;  if Monocarp has counted $$$4$$$ windows, he should have mistaken since no building with the aforementioned layout can have $$$4$$$ windows.

Th first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of windows in the building.

For each test case, if a building with the new layout and the given number of windows just can't exist, print $$$-1$$$. Otherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.

import std.stdio;
import std.conv;
import std.string;

void main()
{
    auto t = stdin.readln.strip.to!int;
testcase:
    while (t-- > 0) {
        // a * 3 + b * 5 + c * 7 = n
        auto n = stdin.readln.strip.to!int;
        int result = 0;
        for (int a = 0; a * 3 <= n; ++a) {
            for (int b = 0; a * 3 + b * 5 <= n; ++b) {
                for (int c = 0; a * 3 + b * 5 + c * 7 <= n; ++c) {
                    if (a * 3 + b * 5 + c * 7 == n) {
                        writeln(a, ' ', b, ' ', c);
                        continue testcase;
                    }
                }
            }
        }
        writeln("-1");
    }
}

// Vicfred
// https://codeforces.com/contest/1430/problem/A
// brute force
import std.stdio;

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

    int n;
    while(t--) {
        readf("%s\n", &n);
        bool found = false;
        for(int x = 0; 3*x <= n; x += 1) {
            if(found)
                break;
            for(int y = 0; 5*y <= n; y += 1) {
                int z = (n - 3*x - 5*y)/7;
                if(z >= 0 && (3*x + 5*y + 7*z == n)) {
                    writefln("%s %s %s", x, y, z);
                    found = true;
                    break;
                }
            }
        }
        if(!found)
            "-1".writeln;
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		(){
		foreach (i; 0..n)
		{
			auto n1 = n - i * 3;
			if (n1 < 0) break;
			foreach (j; 0..n)
			{
				auto n2 = n1 - j * 5;
				if (n2 < 0) break;
				foreach (k; 0..n)
				{
					auto n3 = n2 - k * 7;
					if (n3 < 0) break;
					else if (n3 == 0)
					{
						ans[ti] = [i, j, k];
						return;
					}
				}
			}
		}}();
	}

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

// Vicfred
// https://codeforces.com/contest/1430/problem/A
// brute force
import std.stdio;

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

    int n;
    while(t--) {
        readf("%s\n", &n);
        bool found = false;
        for(int x = 0; 3*x <= n; x += 1) {
            if(found)
                break;
            for(int y = 0; 5*y <= n; y += 1) {
                int z = (n - 3*x - 5*y)/7;
                if(z >= 0 && (3*x + 5*y + 7*z == n)) {
                    writefln("%s %s %s", x, y, z);
                    found = true;
                }
            }
        }
        if(!found)
            "-1".writeln;
    }
}


Suppose you had an array $$$A$$$ of $$$n$$$ elements, each of which is $$$0$$$ or $$$1$$$.Let us define a function $$$f(k,A)$$$ which returns another array $$$B$$$, the result of sorting the first $$$k$$$ elements of $$$A$$$ in non-decreasing order. For example, $$$f(4,[0,1,1,0,0,1,0]) = [0,0,1,1,0,1,0]$$$. Note that the first $$$4$$$ elements were sorted.Now consider the arrays $$$B_1, B_2,\ldots, B_n$$$ generated by $$$f(1,A), f(2,A),\ldots,f(n,A)$$$. Let $$$C$$$ be the array obtained by taking the element-wise sum of $$$B_1, B_2,\ldots, B_n$$$.For example, let $$$A=[0,1,0,1]$$$. Then we have $$$B_1=[0,1,0,1]$$$, $$$B_2=[0,1,0,1]$$$, $$$B_3=[0,0,1,1]$$$, $$$B_4=[0,0,1,1]$$$. Then $$$C=B_1+B_2+B_3+B_4=[0,1,0,1]+[0,1,0,1]+[0,0,1,1]+[0,0,1,1]=[0,2,2,4]$$$.You are given $$$C$$$. Determine a binary array $$$A$$$ that would give $$$C$$$ when processed as above. It is guaranteed that an array $$$A$$$ exists for given $$$C$$$ in the input.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — the number of test cases. Each test case has two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$0 \leq c_i \leq n$$$). It is guaranteed that a valid array $$$A$$$ exists for the given $$$C$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single line containing $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$). If there are multiple answers, you may output any of them.

NoteHere's the explanation for the first test case. Given that $$$A=[1,1,0,1]$$$, we can construct each $$$B_i$$$:   $$$B_1=[\color{blue}{1},1,0,1]$$$;  $$$B_2=[\color{blue}{1},\color{blue}{1},0,1]$$$;  $$$B_3=[\color{blue}{0},\color{blue}{1},\color{blue}{1},1]$$$;  $$$B_4=[\color{blue}{0},\color{blue}{1},\color{blue}{1},\color{blue}{1}]$$$  And then, we can sum up each column above to get $$$C=[1+1+0+0,1+1+1+1,0+0+1+1,1+1+1+1]=[2,4,2,4]$$$.

import std;

void main(){
	auto t=readln.strip.to!int;
	foreach(_;0..t){
		readln;
		auto c=readln.strip.split.to!(int[]);
		auto a=c.map!(x=>x?1:0).array~1;
		foreach(i,x;c) a[x+i*!a[i]]=0;
		a[0..$-1].map!text.join(" ").writeln;
	}
}

import std;

void main(){
	auto t=readln.strip.to!int;
	foreach(_;0..t){
		auto n=readln.strip.to!int;
		auto c=readln.strip.split.to!(int[]);
		auto a=c.map!(x=>x?1:0).array~1;
		foreach(i,x;c) a[x+i*!a[i]]=0;
		a[0..n].map!text.join(" ").writeln;
	}
}

import std;

void main(){
	auto t=readln.strip.to!int;
	foreach(_;0..t){
		auto n=readln.strip.to!int;
		auto c=readln.strip.split.to!(int[]);
		auto a=(-1).repeat(n).array;
		auto j=0, iz=n.repeat(n).array, z=0;
		iz[0]=c[0];
		while(j<n&&c[j]==0) a[j++]=0;
		if(j<n) a[j++]=1;
		foreach(i;j-1..n){
			if(a[i]==0) iz[++z]=i;
			int p=c[i]-i*a[i]+min(i,iz[i]);
			while(j<p) a[j++]=1;
			if(j<n) a[j++]=0;
		}
		a.map!text.join(" ").writeln;
	}
}

import std;

void main(){
	int t=readln.strip.to!int;
	foreach(_;0..t){
		auto n=readln.strip.to!int;
		auto c=readln.strip.split.to!(int[]);
		auto a=(-1).repeat(n).array;
		int z=0,j=0;
		auto iz=0.repeat(n).array;
		iz[0]=c[0];
		while(j<n&&c[j]==0) a[j++]=0;
		if(j<n) a[j++]=1;
		foreach(i;j-1..n){
			if(a[i]==0) iz[++z]=i;
			int p=c[i]-i*a[i]+min(i,iz[i]);
			while(j<p) a[j++]=1;
			if(j<n) a[j++]=0;
		}
		a.map!text.join(" ").writeln;
	}
}


You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.

Print one integer — the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.

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

immutable long MOD = 998244353 ;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto B = readln.split.map!(to!long).array;
    B.sort!"a > b";

    foreach (i; 0..N) {
        long tmp = 1L * (i + 1) * (N - i);
        A[i] = A[i] * tmp;
    }
    A.sort();

    long ans = 0;

    foreach (i; 0..N) {
        (ans += A[i] % MOD * B[i] % MOD) %= MOD;
    }

    ans.writeln;
}

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

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

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

	int n = read.to!int;
	long[] as;
	foreach(i; 0 .. n) as ~= read.to!long;
	print!1("as:", as);

	long[] bs;
	foreach(i; 0 .. n) bs ~= read.to!long;
	print!1("bs:", bs);

	long[] cs;
	foreach(i; 0 .. n){
		long k = i + 1; k *= n - i;
		cs ~= k * as[i];
	}
	print!1("cs:", cs);

	cs.sort();
	bs.sort();

	print!1("cs:", cs);
	print!1("bs:", bs);

	long ans;
	foreach(i; 0 .. n) ans += (bs[i] * (cs[n - 1 - i] % mod)) % mod, ans %= mod;

	ans.writeln;
}

const long mod = 998244353;

/*
s = sum(r; 0 .. n) sum(l; 0 .. r) sum(i; l .. r + 1) a[i] b[i]

how many times the term a[i] b[i] appears?
= how many pair (l, r) exist such that l <= i and i <= r ?
= (i + 1)(n - i).

s = sum(i; 0 .. n) (i + 1)(n - i) a[i] b[i].

let k[i] = (i + 1)(n - i) a[i].
arrange smaller b[i] for smaller k[i].

*/

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

long MOD = 998244353;

void main() {
    GC.disable();

    //

    uint n;
    readf(" %s", n);
    auto a = new long [n];
    foreach(i; 0 .. n) readf(" %s", a[i]);
    auto b = new long [n];
    foreach(i; 0 .. n) readf(" %s", b[i]);

    sort!"a>b"(b);

    long[] vv;
    foreach(i; 0..n) {
      // a
      long t = i+1;
      long mul =  ( t*(n - t + 1) ); // % MOD;
      mul = (mul *a[i]);// % MOD;
      vv ~= mul;
    }

    sort!"a<b"(vv);

    long tt = 0;

    foreach(i; 0 .. n) {
      tt += ( (vv[i]%MOD) * b[i] ) % MOD;
      tt = (tt % MOD);
    }

    writeln(tt);

    //

}

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

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

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

	int n = read.to!int;
	long[] as;
	foreach(i; 0 .. n) as ~= read.to!long;
	print!1("as:", as);

	long[] bs;
	foreach(i; 0 .. n) bs ~= read.to!long;
	print!1("bs:", bs);

	long[] cs;
	foreach(i; 0 .. n) cs ~= (i + 1) * (n - i) * as[i];
	print!1("cs:", cs);

	cs.sort();
	bs.sort();

	print!1("cs:", cs);
	print!1("bs:", bs);

	long ans;
	foreach(i; 0 .. n) ans += (bs[i] * (cs[n - 1 - i] % mod)) % mod, ans %= mod;

	ans.writeln;
}

const long mod = 998244353;

/*
s = sum(r; 0 .. n) sum(l; 0 .. r) sum(i; l .. r + 1) a[i] b[i]

how many times the term a[i] b[i] appears?
= how many pair (l, r) exist such that l <= i and i <= r ?
= (i + 1)(n - i).

s = sum(i; 0 .. n) (i + 1)(n - i) a[i] b[i].

let k[i] = (i + 1)(n - i) a[i].
arrange smaller b[i] for smaller k[i].

*/

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

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

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

	int n = read.to!int;
	long[] as;
	foreach(i; 0 .. n) as ~= read.to!long;
	print!1("as:", as);

	long[] bs;
	foreach(i; 0 .. n) bs ~= read.to!long;
	print!1("bs:", bs);

	long[] cs;
	foreach(i; 0 .. n) cs ~= (i + 1) * (n - i) * as[i];
	print!1("cs:", cs);

	cs.sort();
	bs.sort();

	print!1("cs:", cs);
	print!1("bs:", bs);

	long ans;
	foreach(i; 0 .. n) ans += (bs[i] * cs[n - 1 - i]) % mod, ans %= mod;

	ans.writeln;
}

const long mod = 998244353;

/*
s = sum(r; 0 .. n) sum(l; 0 .. r) sum(i; l .. r + 1) a[i] b[i]

how many times the term a[i] b[i] appears?
= how many pair (l, r) exist such that l <= i and i <= r ?
= (i + 1)(n - i).

s = sum(i; 0 .. n) (i + 1)(n - i) a[i] b[i].

let k[i] = (i + 1)(n - i) a[i].
arrange smaller b[i] for smaller k[i].

*/

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

long MOD = 998244353;

void main() {
    GC.disable();

    //

    uint n;
    readf(" %s", n);
    auto a = new long [n];
    foreach(i; 0 .. n) readf(" %s", a[i]);
    auto b = new long [n];
    foreach(i; 0 .. n) readf(" %s", b[i]);

    sort!"a>b"(b);

    long[] vv;
    foreach(i; 0..n) {
      // a
      long t = i+1;
      long mul =  ( t*(n - t + 1) ); // % MOD;
      mul = (mul *a[i]);// % MOD;
      vv ~= mul;
    }

    sort!"a>b"(vv);

    long tt = 0;

    foreach(i; 0 .. n) {
      tt += (vv[i] * b[i] ) % MOD;
      tt = (tt % MOD);
    }

    writeln(tt);

    //

}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

long MOD = 998244353;

void main() {
    GC.disable();

    //

    uint n;
    readf(" %s", n);
    auto a = new long [n];
    foreach(i; 0 .. n) readf(" %s", a[i]);
    auto b = new long [n];
    foreach(i; 0 .. n) readf(" %s", b[i]);

    sort!"a>b"(b);

    long[] vv;
    foreach(i; 0..n) {
      // a
      long t = i+1;
      long mul =  ( t*(n - t + 1) ); // % MOD;
      mul = (mul *a[i]);// % MOD;
      vv ~= mul;
    }

    sort!"a<b"(vv);

    long tt = 0;

    foreach(i; 0 .. n) {
      tt += (vv[i] * b[i] ) % MOD;
      tt = (tt % MOD);
    }

    writeln(tt);

    //

}


You are given a rooted tree consisting of $$$n$$$ vertices. Vertices are numbered from $$$1$$$ to $$$n$$$. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of ancestors $$$b$$$ containing $$$n$$$ numbers: $$$b_i$$$ is an ancestor of the vertex with the number $$$i$$$. The ancestor of a vertex $$$u$$$ is a vertex that is the next vertex on a simple path from $$$u$$$ to the root. For example, on the simple path from $$$5$$$ to $$$3$$$ (the root), the next vertex would be $$$1$$$, so the ancestor of $$$5$$$ is $$$1$$$.The root has no ancestor, so for it, the value of $$$b_i$$$ is $$$i$$$ (the root is the only vertex for which $$$b_i=i$$$).For example, if $$$n=5$$$ and $$$b=[3, 1, 3, 3, 1]$$$, then the tree looks like this.    An example of a rooted tree for $$$n=5$$$, the root of the tree is a vertex number $$$3$$$. You are given an array $$$p$$$ — a permutation of the vertices of the tree. If it is possible, assign any positive integer weights on the edges, so that the vertices sorted by distance from the root would form the given permutation $$$p$$$.In other words, for a given permutation of vertices $$$p$$$, it is necessary to choose such edge weights so that the condition $$$dist[p_i]<dist[p_{i+1}]$$$ is true for each $$$i$$$ from $$$1$$$ to $$$n-1$$$. $$$dist[u]$$$ is a sum of the weights of the edges on the path from the root to $$$u$$$. In particular, $$$dist[u]=0$$$ if the vertex $$$u$$$ is the root of the tree.For example, assume that $$$p=[3, 1, 2, 5, 4]$$$. In this case, the following edge weights satisfy this permutation:  the edge ($$$3, 4$$$) has a weight of $$$102$$$;  the edge ($$$3, 1$$$) has weight of $$$1$$$;  the edge ($$$1, 2$$$) has a weight of $$$10$$$;  the edge ($$$1, 5$$$) has a weight of $$$100$$$. The array of distances from the root looks like: $$$dist=[1,11,0,102,101]$$$. The vertices sorted by increasing the distance from the root form the given permutation $$$p$$$.Print the required edge weights or determine that there is no suitable way to assign weights. If there are several solutions, then print any of them.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input data sets in the test. Each test case consists of three lines. The first of them contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). It is the number of vertices in the tree. The second line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le n$$$). It is guaranteed that the $$$b$$$ array encodes some rooted tree. The third line contains the given permutation $$$p$$$: $$$n$$$ of different integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.

For each set of input data print the answer on a separate line. If the solution exists, print an array of $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$, where $$$w_i$$$ is the weight of the edge that leads from $$$b_i$$$ to $$$i$$$. For the root there is no such edge, so use the value $$$w_i=0$$$. For all other vertices, the values of $$$w_i$$$ must satisfy the inequality $$$1 \le w_i \le 10^9$$$. There can be equal numbers among $$$w_i$$$ values, but all sums of weights of edges from the root to vertices must be different and satisfy the given permutation. If there are several solutions, output any of them. If no solution exists, output -1.

NoteThe first set of input data of the example is analyzed in the main part of the statement.In the second set of input data of the example, it is impossible to assign the positive weights to obtain a given permutation of vertices.

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;

int calc_weight(int node, int[] b, int[] ans, int[] cumulative)
{
  int w = 0;
  while (b[node] != node) {
    if (cumulative[node] != 0)
      return w + cumulative[node];
    w += ans[node];
    node = b[node];
  }
  return w;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto b = readln.splitter.map!(x => x.to!int - 1).array;
    auto p = readln.splitter.map!(x => x.to!int - 1).array;
    bool[int][] adj = new bool[int][](n);
    int root = -1;
    foreach (i ; 0 .. cast(int)b.length) {
      if (b[i] == i) {
        root = i;
        continue;
      }
      adj[i][b[i]] = true;
      adj[b[i]][i] = true;
    }
    if (p[0] != root) {
      writeln(-1);
      continue;
    }
//    writefln("root=%d, adj=%s", root, adj);
    bool good = true;
    int[] ans = new int[](n);
    int[] cumulative = new int[](n);
    int w = n + 1;
    foreach_reverse (node ; p) {
      if (node == root)
        break;
      if (adj[node].length != 1) {
//        writefln("bad node %d", node);
        good = false;
        break;
      }
      int ancestor = adj[node].keys[0];
      adj[ancestor].remove(node);
//      writefln("remove %d from %d, adj=%s", node, ancestor, adj);
      ans[node] = w--;
    }

    int prev_w = 0;
    foreach (i ; 1 .. cast(int)p.length) {
      w = calc_weight(p[i], b, ans, cumulative);
      if (w <= prev_w) {
        ans[p[i]] += prev_w - w + 1;
        w += prev_w - w + 1;
        cumulative[p[i]] = w;
      }
      prev_w = w;
    }

    if (good)
      writefln("%(%s %)", ans);
    else
      writeln(-1);
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = readln.splitter.map !(to !(int)).array;
		b[] -= 1;
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;

		auto dist = new int [n];
		foreach (int i, ref v; p)
		{
			dist[v] = i;
		}

		auto vis = new bool [n];
		auto a = new int [n];
		bool ok = (b[p[0]] == p[0]);
		foreach (int i, ref v; p)
		{
			if (i == 0)
			{
				ok &= (b[v] == v);
			}
			else
			{
				ok &= vis[b[v]];
			}
			vis[v] = true;
			a[v] = dist[v] - dist[b[v]];
		}

		if (ok)
		{
			writefln !("%(%s %)") (a);
		}
		else
		{
			writeln (-1);
		}
	}
}