Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean. The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.

The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days. The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other. The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.

Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.

NoteIn the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1  2, and Grisha would go on the route 3  1  2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3  1  2. Grisha would see the text at 3 stations.In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1  2  3, and Grisha would go on the route 2  3 and would see the text at both stations.

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;

void main() {
    auto S = readln.split.map!(to!int);
    auto N = S[0];
    auto Q = S[1];
    auto edges = new int[][](N);
    auto P = readln.split.map!(to!int).array;
    foreach (i; 0..N-1) {
        edges[i + 1] ~= P[i] - 1;
        edges[P[i] - 1] ~= i + 1;
    }

    auto depth = new int[](N);
    auto dp = new int[][](20, N);

    void dfs(int n, int p, int d) {
        dp[0][n] = p;
        depth[n] = d;
        foreach (m; edges[n]) if (m != p) dfs(m, n, d+1);
    }

    dfs(0, -1, 0);

    foreach (k; 0..19)
        foreach (n; 0..N)
            dp[k+1][n] = (dp[k][n] == -1) ? -1 : dp[k][dp[k][n]];

    int[int][int] mem;

    int lca(int a, int b) {
        if (depth[a] < depth[b]) swap(a, b);
        if (a in mem && b in mem[a]) return mem[a][b];

        auto orig_a = a;
        auto orig_b = b;

        while (depth[a] > depth[b]) {
            int K = 19;
            foreach (k; iota(K, -1, -1)) {
                if ((1L << k) <= depth[a] - depth[b]) {
                    a = dp[k][a];
                    K = k;
                }
            }
        }

        if (a == b) return mem[a][b] = a;

        while (dp[0][a] != dp[0][b]) {
            int K = 19;
            foreach (k; iota(K, -1, -1)) {
                if (dp[k][a] != dp[k][b]) {
                    a = dp[k][a];
                    b = dp[k][b];
                    K = k;
                }
            }
        }

        return mem[a][b] = dp[0][a];
    }

    int dist(int a, int b, int ab) {
        return depth[a] + depth[b] - depth[ab] * 2;
    }

    foreach(_; 0..Q) {
        auto q = readln.split.map!(to!int).array;
        q.sort();
        int ans = 0;
        do {
            int s = q[0] - 1, t = q[1] - 1, f = q[2] - 1;
            int st = lca(s, t);
            int tf = lca(t, f);
            int fs = lca(f, s);
            int sft;
            if (depth[st] >= depth[tf] && depth[st] >= depth[fs]) sft = st;
            else if (depth[tf] >= depth[st] && depth[tf] >= depth[fs]) sft = tf;
            else sft = fs;
            ans = max(ans, dist(f, sft, lca(f, sft)) + 1);
        } while (nextPermutation(q));
        ans.writeln;
    }
}

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

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

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

    auto g = new int[][] (n+1);

    foreach (i, e; p.enumerate(2)) {
        g[i] ~= e;
        g[e] ~= i;
    }

    debug { g.each!writeln; }

    immutable int MX_LVL = log2(n).to!int + 1;
    auto lca = new int[][] (MX_LVL, n+1);
    auto h = new int[] (n+1);

    void calcLcaArr (int n) {
        void dfs (int v, int fr) {
            if (fr != 0) {
                lca[0][v] = fr;
                h[v] = h[fr] + 1;
            }
            foreach (u; g[v]) {
                if (u == fr) { continue; }

                dfs(u, v);
            }
        }

        foreach (lvl; 0 .. MX_LVL) { lca[lvl][] = 0; }
        lca[0][1] = 1;
        h[1] = 0;

        dfs(1, 0);

        foreach (lvl; 1 .. MX_LVL) {
            foreach (v; 1 .. n+1) {
                lca[lvl][v] = lca[lvl-1][lca[lvl-1][v]];
            }
        }
    }

    calcLcaArr(n);

    int getLca (int a, int b) {
        if (h[a] < h[b]) { swap(a, b); }

        foreach_reverse (lvl; 0 .. MX_LVL) {
            if (h[a] - (1 << lvl) < h[b]) { continue; }

            a = lca[lvl][a];
        }

        if (a == b) {
            return a;
        }

        foreach_reverse (lvl; 0 .. MX_LVL) {
            if (lca[lvl][a] != lca[lvl][b]) {
                a = lca[lvl][a];
                b = lca[lvl][b];
            }
        }

        return lca[0][a];
    }

    debug {
        h.writeln;
        lca.each!writeln;

        writeln([getLca (1, 1), getLca(1, 2), getLca(2, 1), getLca(2, 2), getLca(2, 3)]
                .map!(to!string).join(" "));

    }

    int dst(int a, int b) {
        int vlca = getLca(a, b);
        return h[a] - h[vlca] + h[b] - h[vlca] + 1;
    }

    while (q--) {
        auto arr = readln.chomp.split.map!(to!int).array;

        int ans = 0;
        foreach (t; 0 .. 3) {
            int[] starts;
            foreach (i; 0 .. 3) { if (i != t) { starts ~= arr[i]; } }

            int cur = (dst(starts[0], arr[t]) + dst(starts[1], arr[t]) - dst(starts[0], starts[1])) / 2 + 1;

            ans = max(ans, cur);
        }

        ans.writeln;
    }
}

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

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

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

    auto g = new int[][] (n+1);

    foreach (i, e; p.enumerate(2)) {
        g[i] ~= e;
        g[e] ~= i;
    }

    debug { g.each!writeln; }

    immutable int MX_LVL = log2(n).to!int + 1;
    auto lca = new int[][] (MX_LVL, n+1);
    auto h = new int[] (n+1);

    void calcLcaArr (int n) {
        void dfs (int v, int fr) {
            if (fr != 0) {
                lca[0][v] = fr;
                h[v] = h[fr] + 1;
            }
            foreach (u; g[v]) {
                if (u == fr) { continue; }

                dfs(u, v);
            }
        }

        foreach (lvl; 0 .. MX_LVL) { lca[lvl][] = 0; }
        lca[0][1] = 1;
        h[1] = 0;

        dfs(1, 0);

        foreach (lvl; 1 .. MX_LVL) {
            foreach (v; 1 .. n+1) {
                lca[lvl][v] = lca[lvl-1][lca[lvl-1][v]];
            }
        }
    }

    calcLcaArr(n);

    int getLca (int a, int b) {
        if (h[a] < h[b]) { swap(a, b); }

        foreach_reverse (lvl; 0 .. MX_LVL) {
            if (h[a] - (1 << lvl) < h[b]) { continue; }

            a = lca[lvl][a];
        }

        if (a == b) {
            return a;
        }

        foreach_reverse (lvl; 0 .. MX_LVL) {
            if (lca[lvl][a] != lca[lvl][b]) {
                a = lca[lvl][a];
                b = lca[lvl][b];
            }
        }

        return lca[0][a];
    }

    debug {
        h.writeln;
        lca.each!writeln;

        writeln([getLca (1, 1), getLca(1, 2), getLca(2, 1), getLca(2, 2), getLca(2, 3)]
                .map!(to!string).join(" "));

    }

    while (q--) {
        auto arr = readln.chomp.split.map!(to!int).array;

        int ans = 0;
        foreach (t; 0 .. 3) {
            int[] starts;
            foreach (i; 0 .. 3) { if (i != t) { starts ~= arr[i]; } }

            int lca1 = getLca(starts[0], starts[1]);
            int lca2 = getLca(starts[0], arr[t]);
            int lca3 = getLca(starts[1], arr[t]);

            int cur = 0;
            if (h[lca1] >= h[lca2] && h[lca1] >= h[lca3]) {
                int all = getLca(lca1, arr[t]);
                cur = h[lca1] - h[all] + h[arr[t]] - h[all];
            } else {
                cur = h[arr[t]] - max(h[lca2], h[lca3]);
            }

            ans = max(ans, cur + 1);
        }

        ans.writeln;
    }
}

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

void main() {
    auto S = readln.split.map!(to!int);
    auto N = S[0];
    auto Q = S[1];
    auto edges = new int[][](N);
    auto P = readln.split.map!(to!int).array;
    foreach (i; 0..N-1) {
        edges[i + 1] ~= P[i] - 1;
        edges[P[i] - 1] ~= i + 1;
    }

    auto depth = new int[](N);
    auto dp = new int[][](20, N);

    void dfs(int n, int p, int d) {
        dp[0][n] = p;
        depth[n] = d;
        foreach (m; edges[n]) if (m != p) dfs(m, n, d+1);
    }

    dfs(0, -1, 0);

    foreach (k; 0..19)
        foreach (n; 0..N)
            dp[k+1][n] = (dp[k][n] == -1) ? -1 : dp[k][dp[k][n]];

    int[int][int] mem;

    int lca(int a, int b) {
        if (depth[a] < depth[b]) swap(a, b);
        if (a in mem && b in mem[a]) return mem[a][b];

        auto orig_a = a;
        auto orig_b = b;

        while (depth[a] > depth[b]) {
            int K = 19;
            foreach (k; iota(K, -1, -1)) {
                if ((1L << k) <= depth[a] - depth[b]) {
                    a = dp[k][a];
                    K = k;
                }
            }
        }

        if (a == b) return mem[a][b] = a;

        while (dp[0][a] != dp[0][b]) {
            int K = 19;
            foreach (k; iota(K, -1, -1)) {
                if (dp[k][a] != dp[k][b]) {
                    a = dp[k][a];
                    b = dp[k][b];
                    K = k;
                }
            }
        }

        return mem[a][b] = dp[0][a];
    }

    int dist(int a, int b, int ab) {
        return depth[a] + depth[b] - depth[ab] * 2;
    }

    foreach(_; 0..Q) {
        auto q = readln.split.map!(to!int).array;
        q.sort();
        int ans = 0;
        do {
            int s = q[0] - 1, t = q[1] - 1, f = q[2] - 1;
            int st = lca(s, t);
            int sf = lca(s, f);
            int tf = lca(t, f);
            int d1 = dist(s, t, st);
            int d2 = dist(s, f, sf);
            int d3 = dist(t, f, tf);
            int stf1 = d1 < d2 ? st : sf;
            int d4 = dist(stf1, f, lca(stf1, f));
            int stf2 = d1 < d3 ? st : tf;
            int d5 = dist(stf2, f, lca(stf2, f));
            int d = min(d4, d5) + 1;
            ans = max(ans, d);
        } while (nextPermutation(q));
        ans.writeln;
    }
}

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

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

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

    auto g = new int[][] (n+1);

    foreach (i, e; p.enumerate(2)) {
        g[i] ~= e;
        g[e] ~= i;
    }

    debug { g.each!writeln; }

    immutable int MX_LVL = log2(n).to!int + 1;
    auto lca = new int[][] (MX_LVL, n+1);
    auto h = new int[] (n+1);

    void calcLcaArr (int n) {
        void dfs (int v, int fr) {
            if (fr != 0) {
                lca[0][v] = fr;
                h[v] = h[fr] + 1;
            }
            foreach (u; g[v]) {
                if (u == fr) { continue; }

                dfs(u, v);
            }
        }

        foreach (lvl; 0 .. MX_LVL) { lca[lvl][] = 0; }
        lca[0][1] = 1;
        h[1] = 0;

        dfs(1, 0);

        foreach (lvl; 1 .. MX_LVL) {
            foreach (v; 1 .. n+1) {
                lca[lvl][v] = lca[lvl-1][lca[lvl-1][v]];
            }
        }
    }

    calcLcaArr(n);

    int getLca (int a, int b) {
        if (h[a] < h[b]) { swap(a, b); }

        foreach_reverse (lvl; 0 .. MX_LVL) {
            if (h[a] - (1 << lvl) < h[b]) { continue; }

            a = lca[lvl][a];
        }

        if (a == b) {
            return a;
        }

        foreach_reverse (lvl; 0 .. MX_LVL) {
            if (lca[lvl][a] != lca[lvl][b]) {
                a = lca[lvl][a];
                b = lca[lvl][b];
            }
        }

        return lca[0][a];
    }

    debug {
        h.writeln;
        lca.each!writeln;

        writeln([getLca (1, 1), getLca(1, 2), getLca(2, 1), getLca(2, 2), getLca(2, 3)]
                .map!(to!string).join(" "));

    }

    while (q--) {
        auto arr = readln.chomp.split.map!(to!int).array;

        int ans = 0;
        foreach (t; 0 .. 3) {
            int[] starts;
            foreach (i; 0 .. 3) { if (i != t) { starts ~= arr[i]; } }

            int lca1 = getLca(starts[0], starts[1]);
            int lca2 = getLca(starts[0], arr[t]);
            int lca3 = getLca(starts[1], arr[t]);

            int cur = 0;
            if (h[lca1] >= h[lca2] && h[lca1] >= h[lca3]) {
                int all = getLca(lca1, arr[t]);
                cur = h[lca1] - h[all] + h[t] - h[all];
            } else {
                cur = h[t] - max(h[lca2], h[lca3]);
            }

            debug { writeln(starts, ' ', lca1, ' ', lca2, ' ', lca3, ' ', cur); }

            ans = max(ans, cur + 1);
        }

        ans.writeln;
    }
}


Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form:  You are given two positive integers $$$u$$$ and $$$v$$$, find any pair of integers (not necessarily positive) $$$x$$$, $$$y$$$, such that: $$$$$$\frac{x}{u} + \frac{y}{v} = \frac{x + y}{u + v}.$$$$$$  The solution $$$x = 0$$$, $$$y = 0$$$ is forbidden, so you should find any solution with $$$(x, y) \neq (0, 0)$$$. Please help Ivan to solve some equations of this form.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The next lines contain descriptions of test cases. The only line of each test case contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq 10^9$$$) — the parameters of the equation.

For each test case print two integers $$$x$$$, $$$y$$$ — a possible solution to the equation. It should be satisfied that $$$-10^{18} \leq x, y \leq 10^{18}$$$ and $$$(x, y) \neq (0, 0)$$$. We can show that an answer always exists. If there are multiple possible solutions you can print any.

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

void solve(){
    long u = scan;
    long v = scan;
    long y = v * v;
    long x = - (u * u);
    writeln(x, " ", y);
}

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

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


Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland — Uzhlyandia.It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia.Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor — calculate the number of good paths.

The first line contains two integers n, m (1 ≤ n, m ≤ 106) — the number of cities and roads in Uzhlyandia, respectively. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) that mean that there is road between cities u and v. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself.

Print out the only integer — the number of good paths in Uzhlyandia.

NoteIn first sample test case the good paths are:   2 → 1 → 3 → 1 → 4 → 1 → 5,  2 → 1 → 3 → 1 → 5 → 1 → 4,  2 → 1 → 4 → 1 → 5 → 1 → 3,  3 → 1 → 2 → 1 → 4 → 1 → 5,  3 → 1 → 2 → 1 → 5 → 1 → 4,  4 → 1 → 2 → 1 → 3 → 1 → 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same:   2 → 1 → 4 → 1 → 3 → 1 → 5,  2 → 1 → 5 → 1 → 3 → 1 → 4,  2 → 1 → 5 → 1 → 4 → 1 → 3,  3 → 1 → 4 → 1 → 2 → 1 → 5,  3 → 1 → 5 → 1 → 2 → 1 → 4,  4 → 1 → 3 → 1 → 2 → 1 → 5,  and all the paths in the other direction. Thus, the answer is 6.In the second test case, Igor simply can not walk by all the roads.In the third case, Igor walks once over every road.

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

void main ()
{
	int n;
	int m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto e = new int [2] [m];
		auto d = new int [n];
		auto c = n.iota.array;
		auto r = new int [n];
		auto x = new int [n];
		long loops = 0;

		int root (int v)
		{
			if (c[v] != v)
			{
				c[v] = root (c[v]);
			}
			return c[v];
		}

		bool unite (int u, int v)
		{
			u = root (u);
			v = root (v);
			if (u == v)
			{
				return false;
			}
			if (r[u] < r[v])
			{
				swap (u, v);
			}
			c[v] = u;
			if (r[u] == r[v])
			{
				r[u] += 1;
			}
			return true;
		}

		int num = 0;
		x[] = 1;
		foreach (j; 0..m)
		{
			readf (" %s %s", &e[j][0], &e[j][1]);
			e[j][] -= 1;
			x[e[j][0]] = 0;
			x[e[j][1]] = 0;
			if (e[j][0] == e[j][1])
			{
				loops += 1;
			}
			else
			{
				d[e[j][0]] += 1;
				d[e[j][1]] += 1;
			}
			num += unite (e[j][0], e[j][1]);
		}
		num += sum (x);

		if (m < 2 || num != n - 1)
		{
			writeln (0);
			continue;
		}
		long res = 0;
		foreach (i; 0..n)
		{
			long cur = d[i];
			cur *= d[i] - 1;
			cur /= 2;
			res += cur;
		}
		res += loops * (loops - 1) / 2;
		res += loops * (m - loops);
		writeln (res);
	}
}

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

void main ()
{
	int n;
	int m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto e = new int [2] [m];
		auto d = new int [n];
		auto c = n.iota.array;
		auto r = new int [n];
		long loops = 0;

		int root (int v)
		{
			if (c[v] != v)
			{
				c[v] = root (c[v]);
			}
			return c[v];
		}

		bool unite (int u, int v)
		{
			u = root (u);
			v = root (v);
			if (u == v)
			{
				return false;
			}
			if (r[u] < r[v])
			{
				swap (u, v);
			}
			c[v] = u;
			if (r[u] == r[v])
			{
				r[u] += 1;
			}
			return true;
		}

		int num = 0;
		foreach (j; 0..m)
		{
			readf (" %s %s", &e[j][0], &e[j][1]);
			e[j][] -= 1;
			if (e[j][0] == e[j][1])
			{
				loops += 1;
			}
			else
			{
				d[e[j][0]] += 1;
				d[e[j][1]] += 1;
			}
			num += unite (e[j][0], e[j][1]);
		}

		if (m < 2 || num != n - 1)
		{
			writeln (0);
			continue;
		}
		long res = 0;
		foreach (i; 0..n)
		{
			long cur = d[i];
			cur *= d[i] - 1;
			cur /= 2;
			res += cur;
		}
		res += loops * (loops - 1) / 2;
		res += loops * (m - loops);
		writeln (res);
	}
}


Monocarp has forgotten the password to his mobile phone. The password consists of $$$4$$$ digits from $$$0$$$ to $$$9$$$ (note that it can start with the digit $$$0$$$).Monocarp remembers that his password had exactly two different digits, and each of these digits appeared exactly two times in the password. Monocarp also remembers some digits which were definitely not used in the password.You have to calculate the number of different sequences of $$$4$$$ digits that could be the password for Monocarp's mobile phone (i. e. these sequences should meet all constraints on Monocarp's password).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 8$$$) — the number of digits for which Monocarp remembers that they were not used in the password. The second line contains $$$n$$$ different integers $$$a_1, a_2, \dots a_n$$$ ($$$0 \le a_i \le 9$$$) representing the digits that were not used in the password. Note that the digits $$$a_1, a_2, \dots, a_n$$$ are given in ascending order.

For each testcase, print one integer — the number of different $$$4$$$-digit sequences that meet the constraints.

NoteIn the first example, all possible passwords are: "3377", "3737", "3773", "7337", "7373", "7733".

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

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

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

void solve() {
    int n = read!int;
    auto a = readarray!int;
    if (n == 8)
        writeln(6);
    else if (n == 7)
        writeln(3*6);
    else
        writeln(6 * (10 - n)*(9 - n) / 2);
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = readln.splitter.map!(to!int).array;
    bool[int] banned;
    foreach (x ; a)
      banned[x] = true;
    int ans = 0;
    foreach (d1 ; 0 .. 10)
      foreach (d2 ; 0 .. 10)
        foreach (d3 ; 0 .. 10)
          foreach (d4 ; 0 .. 10) {
             int[int] digits;
             int[4] code = [d1, d2, d3, d4];
             bool good = true;
             foreach (x ; code) {
               if (x in banned)
                 good = false;
               digits[x]++;
             }
             if (digits.length != 2 || digits.values != [2, 2])
               good = false;
             if (good)
               ans++;
          }
    writeln(ans);
  }
}

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

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

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

void solve() {
    int N = read!int;
    auto A = readarray!int;
    long ans = (10 - N) * (10 - N - 1) / 2 * 6;
    writeln(ans);
}


You are given $$$n$$$ words of equal length $$$m$$$, consisting of lowercase Latin alphabet letters. The $$$i$$$-th word is denoted $$$s_i$$$.In one move you can choose any position in any single word and change the letter at that position to the previous or next letter in alphabetical order. For example:  you can change 'e' to 'd' or to 'f';  'a' can only be changed to 'b';  'z' can only be changed to 'y'. The difference between two words is the minimum number of moves required to make them equal. For example, the difference between "best" and "cost" is $$$1 + 10 + 0 + 0 = 11$$$.Find the minimum difference of $$$s_i$$$ and $$$s_j$$$ such that $$$(i < j)$$$. In other words, find the minimum difference over all possible pairs of the $$$n$$$ words.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains $$$2$$$ integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 50$$$, $$$1 \leq m \leq 8$$$) — the number of strings and their length respectively. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$m$$$, consisting of lowercase Latin letters.

For each test case, print a single integer — the minimum difference over all possible pairs of the given strings.

6

2 4

best

cost

6 3

abb

zba

bef

cdu

ooo

zzz

2 7

aaabbbc

bbaezfe

3 2

ab

ab

ab

2 8

aaaaaaaa

zzzzzzzz

3 1

a

u

y

NoteFor the second test case, one can show that the best pair is ("abb","bef"), which has difference equal to $$$8$$$, which can be obtained in the following way: change the first character of the first string to 'b' in one move, change the second character of the second string to 'b' in $$$3$$$ moves and change the third character of the second string to 'b' in $$$4$$$ moves, thus making in total $$$1 + 3 + 4 = 8$$$ moves.For the third test case, there is only one possible pair and it can be shown that the minimum amount of moves necessary to make the strings equal is $$$35$$$.For the fourth test case, there is a pair of strings which is already equal, so the answer is $$$0$$$.

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

int[] rtln(T)() { return to!(T[])(strip(readln).split(" ")); }

void main() {
    int t, n, m;
    readf("%d\n", t);
    while(t--) {
		char[][] a;
        readf("%d %d\n", n, m);
		while (n--)
			a ~= strip(readln).dup;
    int min;
    for (int p = 0; p < m; p++) {
      int tempTemp = (a[0][p] + '0') - (a[1][p] + '0');
      if (tempTemp < 0) tempTemp = -tempTemp;
        min += tempTemp;
    }
    if (min < 0)
      min = -min;
		for (int i = 0; i < a.length; i++) {
      for (int j = 0; j < a.length; j++) {
        if (j == i)
          continue;
        int temp = 0;
        for (int p = 0; p < m; p++) {
          int tempTemp = (a[i][p] + '0') - (a[j][p] + '0');
          if (tempTemp < 0)
            tempTemp = -tempTemp;
          temp += tempTemp;
        }
        if (temp < min)
          min = temp;
      }
    }
    writeln(min);
  }
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto M = scan!int;
      auto S = scan!string(N);

      long ans = long.max;
      foreach(i; 0..N - 1) foreach(j; i+1..N) {
        long tans;
        foreach(k; 0..M) {
          tans += (S[i][k] - S[j][k]).abs;
        }

        ans = min(ans, tans);
      }

      return ans;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

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

alias dist = (s, t) => zip (s.byChar, t.byChar).map !(q{abs (a[0] - a[1])}).sum;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		string [] s;
		foreach (i; 0..n)
		{
			s ~= readln.strip;
		}
		int res = int.max;
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				res = min (res, dist (s[i], s[j]));
			}
		}
		writeln (res);
	}
}


Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.There are two types of spells: fire spell of power $$$x$$$ deals $$$x$$$ damage to the monster, and lightning spell of power $$$y$$$ deals $$$y$$$ damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.For example, suppose that Polycarp knows three spells: a fire spell of power $$$5$$$, a lightning spell of power $$$1$$$, and a lightning spell of power $$$8$$$. There are $$$6$$$ ways to choose the order in which he casts the spells:  first, second, third. This order deals $$$5 + 1 + 2 \cdot 8 = 22$$$ damage;  first, third, second. This order deals $$$5 + 8 + 2 \cdot 1 = 15$$$ damage;  second, first, third. This order deals $$$1 + 2 \cdot 5 + 8 = 19$$$ damage;  second, third, first. This order deals $$$1 + 2 \cdot 8 + 2 \cdot 5 = 27$$$ damage;  third, first, second. This order deals $$$8 + 2 \cdot 5 + 1 = 19$$$ damage;  third, second, first. This order deals $$$8 + 2 \cdot 1 + 2 \cdot 5 = 20$$$ damage. Initially, Polycarp knows $$$0$$$ spells. His spell set changes $$$n$$$ times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of changes to the spell set. Each of the next $$$n$$$ lines contains two integers $$$tp$$$ and $$$d$$$ ($$$0 \le tp_i \le 1$$$; $$$-10^9 \le d \le 10^9$$$; $$$d_i \neq 0$$$) — the description of the change. If $$$tp_i$$$ if equal to $$$0$$$, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell. If $$$d_i > 0$$$, then Polycarp learns a spell of power $$$d_i$$$. Otherwise, Polycarp forgets a spell with power $$$-d_i$$$, and it is guaranteed that he knew that spell before the change. It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).

After each change, print the maximum damage Polycarp can deal with his current set of spells.

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

class Node
{
	int power;
	int type;
	int size;
	int zaps;
	long total;
	Node left, right;

	this ()
	{
	}

	this (int power_, int type_)
	{
		power = power_;
		type = type_;
		left = term;
		right = term;
		recalc ();
	}

	void recalc ()
	{
		size = left.size + right.size + (this != term);
		zaps = left.zaps + right.zaps + type;
		total = left.total + right.total + power;
	}
}

alias Pair = Tuple !(Node, Node);

Pair tSplitPower (Node t, int power)
{
	if (t == term)
	{
		return Pair (term, term);
	}
	if (power < t.power)
	{
		auto temp = tSplitPower (t.right, power);
		t.right = temp[0];
		t.recalc ();
		return Pair (t, temp[1]);
	}
	else
	{
		auto temp = tSplitPower (t.left, power);
		t.left = temp[1];
		t.recalc ();
		return Pair (temp[0], t);
	}
}

Pair tSplitSize (Node t, int size)
{
	if (t is term)
	{
		return Pair (term, term);
	}
	if (size >= t.left.size + 1)
	{
		auto temp = tSplitSize (t.right, size - (t.left.size + 1));
		t.right = temp[0];
		t.recalc ();
		return Pair (t, temp[1]);
	}
	else
	{
		auto temp = tSplitSize (t.left, size);
		t.left = temp[1];
		t.recalc ();
		return Pair (temp[0], t);
	}
}

Node tMerge (Node l, Node r)
{
	if (l is term)
	{
		return r;
	}
	if (r is term)
	{
		return l;
	}
	if (uniform (0, l.size + r.size) < l.size)
	{
		l.right = tMerge (l.right, r);
		l.recalc ();
		return l;
	}
	else
	{
		r.left = tMerge (l, r.left);
		r.recalc ();
		return r;
	}
}

Node term;

Node leftMost (Node v)
{
	while (v.left != term)
	{
		v = v.left;
	}
	return v;
}

Node rightMost (Node v)
{
	while (v.right != term)
	{
		v = v.right;
	}
	return v;
}

void display (Node v)
{
	if (v == term)
	{
		return;
	}
	write ("(");
	display (v.left);
	write (v.power, ":", v.type, ":", v.size, ":", v.zaps, ":", v.total);
	display (v.right);
	write (")");
}

void main ()
{
	term = new Node ();
	term.left = term;
	term.right = term;

	int q;
	while (readf !(" %s") (q) > 0)
	{
		auto root = new Node (0, 0);
		foreach (i; 0..q)
		{
			int type, power;
			readf !(" %s %s") (type, power);
			if (power > 0)
			{
				auto pair = tSplitPower (root, +power);
				auto elem = new Node (power, type);
				auto temp = tMerge (pair[0], elem);
				root = tMerge (temp, pair[1]);
			}
			else
			{
				auto lo = tSplitPower (root, -power);
				auto hi = tSplitPower (lo[1], -power - 1);
				root = tMerge (lo[0], hi[1]);
			}
			auto zaps = root.zaps;
			long res = root.total;
			auto pair = tSplitSize (root, zaps);
			res += pair[0].total;
			if (zaps > 0 && pair[0].zaps == zaps)
			{
				res += leftMost (pair[1]).power -
				    rightMost (pair[0]).power;
			}
			root = tMerge (pair[0], pair[1]);
			writeln (res);
		}
	}
}


There are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole string. Your task is to find a sequence of operations after which one of the strings consists only of a letters and the other consists only of b letters. The number of operations should be minimized.

The first line contains a string s (1 ≤ |s| ≤ 2·105). The second line contains a string t (1 ≤ |t| ≤ 2·105). Here |s| and |t| denote the lengths of s and t, respectively. It is guaranteed that at least one of the strings contains at least one a letter and at least one of the strings contains at least one b letter.

The first line should contain a single integer n (0 ≤ n ≤ 5·105) — the number of operations. Each of the next n lines should contain two space-separated integers ai, bi — the lengths of prefixes of s and t to swap, respectively. If there are multiple possible solutions, you can print any of them. It's guaranteed that a solution with given constraints exists.

NoteIn the first example, you can solve the problem in two operations:  Swap the prefix of the first string with length 1 and the prefix of the second string with length 0. After this swap, you'll have strings ab and bbb.  Swap the prefix of the first string with length 1 and the prefix of the second string with length 3. After this swap, you'll have strings bbbb and a. In the second example, the strings are already appropriate, so no operations are needed.

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

auto separators (string s, char start) {
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
		if (cur != c) {
			res ~= i + 1;
			cur = c;
		}
	return res;
}

auto solveSingle (string s, string t)
{
	int [2] [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front + q.front) {
		res ~= [p.front, q.front];
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

auto solve (string s, string t) {
	auto res = solveSingle (s, t);
	auto p = separators (s, 'a') ~ 0, q = separators (t, 'b') ~ 0;
	reverse (p);
	reverse (q);
	auto balance = (p.length.to!int - q.length.to!int) / 2;
	foreach (i; 0..2) foreach (j; 0..2) {
		int u = abs (balance) + i;
		int v = j;
		if (balance < 0) swap (u, v);
		if (u < 0 || p.length <= u || v < 0 || q.length <= v) continue;
		auto s2 = t[0..q[v]] ~ s[p[u]..$], t2 = s[0..p[u]] ~ t[q[v]..$];
		int [2] [] temp = [[p[u], q[v]]];
		temp ~= solveSingle (s2, t2);
		if (res.length > temp.length) res = temp;
	}
	return res;
}

void main () {
	auto s = readln.strip, t = readln.strip;
	auto res1 = solve (s, t), res2 = solve (t, s);
	if (res1.length > res2.length) {
		swap (res1, res2);
		res1.each !((ref a) => swap (a[0], a[1]));
	}
	writeln (res1.length);
	foreach (line; res1) writefln ("%(%s %)", line);
}

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

alias Record = Tuple !(int, q{a}, int, q{b});

int [] separators (string s, char start)
{
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
	{
		if (cur != c)
		{
			res ~= i + 1;
			cur = c;
		}
	}
	debug {writeln (res);}
	return res;
}

Record [] solve (string s, string t)
{
	Record [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front > 0 || q.front > 0)
	{
		res ~= Record (p.front, q.front);
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

Record [] solveStrategyLayer (string s, string t)
{
	Record [] res = solve (s, t);
	auto p = separators (s, 'a').chain (0.only).retro.array;
	auto q = separators (t, 'b').chain (0.only).retro.array;
	int balance = p.length.to!int - q.length.to!int;
	balance /= 2;
	foreach (i; 0..4)
	{
		foreach (j; 0..2)
		{
			int u = abs (balance) - 2 + i;
			int v = j;
			if (balance < 0)
			{
				swap (u, v);
			}
			if (u < 0 || p.length <= u || v < 0 || q.length <= v)
			{
				continue;
			}
			auto s2 = t[0..q[v]] ~ s[p[u]..$];
			auto t2 = s[0..p[u]] ~ t[q[v]..$];
			Record [] temp = [Record (p[u], q[v])];
			temp ~= solve (s2, t2);
			if (res.length > temp.length)
			{
				res = temp;
			}
		}
	}
	return res;
}

void main ()
{
	string s, t;
	while ((s = readln.strip) != "")
	{
		t = readln.strip;
		auto res1 = solveStrategyLayer (s, t);
		auto res2 = solveStrategyLayer (t, s);
		if (res1.length > res2.length)
		{
			swap (res1, res2);
			res1.each !((ref a) => swap (a[0], a[1]));
		}
		writeln (res1.length);
		foreach (ref line; res1)
		{
			writefln ("%s %s", line.a, line.b);
		}
	}
}

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

auto separators (string s, char start) {
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
		if (cur != c) {
			res ~= i + 1;
			cur = c;
		}
	return res;
}

auto solveSingle (string s, string t)
{
	int [2] [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front + q.front) {
		res ~= [p.front, q.front];
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

auto solve (string s, string t) {
	auto res = solveSingle (s, t);
	auto p = separators (s, 'a') ~ 0, q = separators (t, 'b') ~ 0;
	reverse (p);
	reverse (q);
	auto balance = (p.length.to!int - q.length.to!int) / 2;
	foreach (i; 0..3) foreach (j; 0..2) {
		int u = abs (balance) + i;
		int v = j;
		if (balance < 0) swap (u, v);
		if (u < 0 || p.length <= u || v < 0 || q.length <= v) continue;
		auto s2 = t[0..q[v]] ~ s[p[u]..$], t2 = s[0..p[u]] ~ t[q[v]..$];
		int [2] [] temp = [[p[u], q[v]]];
		temp ~= solveSingle (s2, t2);
		if (res.length > temp.length) res = temp;
	}
	return res;
}

void main () {
	auto s = readln.strip, t = readln.strip;
	auto res1 = solve (s, t), res2 = solve (t, s);
	if (res1.length > res2.length) {
		swap (res1, res2);
		res1.each !((ref a) => swap (a[0], a[1]));
	}
	writeln (res1.length);
	foreach (line; res1) writefln ("%(%s %)", line);
}

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

auto separators (string s, char start) {
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
		if (cur != c) {
			res ~= i + 1;
			cur = c;
		}
	return res;
}

auto solveSingle (string s, string t)
{
	int [2] [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front + q.front) {
		res ~= [p.front, q.front];
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

auto solve (string s, string t) {
	auto res = solveSingle (s, t);
	auto p = separators (s, 'a') ~ 0, q = separators (t, 'b') ~ 0;
	reverse (p);
	reverse (q);
	auto balance = (p.length.to!int - q.length.to!int) / 2;
	foreach (i; 0..3) foreach (j; 0..1) {
		int u = abs (balance) + i;
		int v = j;
		if (balance < 0) swap (u, v);
		if (u < 0 || p.length <= u || v < 0 || q.length <= v) continue;
		auto s2 = t[0..q[v]] ~ s[p[u]..$], t2 = s[0..p[u]] ~ t[q[v]..$];
		int [2] [] temp = [[p[u], q[v]]];
		temp ~= solveSingle (s2, t2);
		if (res.length > temp.length) res = temp;
	}
	return res;
}

void main () {
	auto s = readln.strip, t = readln.strip;
	auto res1 = solve (s, t), res2 = solve (t, s);
	if (res1.length > res2.length) {
		swap (res1, res2);
		res1.each !((ref a) => swap (a[0], a[1]));
	}
	writeln (res1.length);
	foreach (line; res1) writefln ("%(%s %)", line);
}

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

auto separators (string s, char start) {
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
		if (cur != c) {
			res ~= i + 1;
			cur = c;
		}
	return res;
}

auto solveSingle (string s, string t)
{
	int [2] [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front + q.front) {
		res ~= [p.front, q.front];
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

auto solve (string s, string t) {
	auto res = solveSingle (s, t);
	auto p = separators (s, 'a') ~ 0, q = separators (t, 'b') ~ 0;
	reverse (p);
	reverse (q);
	auto balance = (p.length.to!int - q.length.to!int) / 2;
	foreach (i; 0..2) foreach (j; 0..1) {
		int u = abs (balance) - 2 + i;
		int v = j;
		if (balance < 0) swap (u, v);
		if (u < 0 || p.length <= u || v < 0 || q.length <= v) continue;
		auto s2 = t[0..q[v]] ~ s[p[u]..$], t2 = s[0..p[u]] ~ t[q[v]..$];
		int [2] [] temp = [[p[u], q[v]]];
		temp ~= solveSingle (s2, t2);
		if (res.length > temp.length) res = temp;
	}
	return res;
}

void main () {
	auto s = readln.strip, t = readln.strip;
	auto res1 = solve (s, t), res2 = solve (t, s);
	if (res1.length > res2.length) {
		swap (res1, res2);
		res1.each !((ref a) => swap (a[0], a[1]));
	}
	writeln (res1.length);
	foreach (line; res1) writefln ("%(%s %)", line);
}

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

auto separators (string s, char start) {
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
		if (cur != c) {
			res ~= i + 1;
			cur = c;
		}
	return res;
}

auto solveSingle (string s, string t)
{
	int [2] [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front + q.front) {
		res ~= [p.front, q.front];
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

auto solve (string s, string t) {
	auto res = solveSingle (s, t);
	auto p = separators (s, 'a') ~ 0, q = separators (t, 'b') ~ 0;
	reverse (p);
	reverse (q);
	auto balance = (p.length.to!int - q.length.to!int) / 2;
	foreach (i; 0..2) foreach (j; 0..1) {
		int u = abs (balance) + i;
		int v = j;
		if (balance < 0) swap (u, v);
		if (u < 0 || p.length <= u || v < 0 || q.length <= v) continue;
		auto s2 = t[0..q[v]] ~ s[p[u]..$], t2 = s[0..p[u]] ~ t[q[v]..$];
		int [2] [] temp = [[p[u], q[v]]];
		temp ~= solveSingle (s2, t2);
		if (res.length > temp.length) res = temp;
	}
	return res;
}

void main () {
	auto s = readln.strip, t = readln.strip;
	auto res1 = solve (s, t), res2 = solve (t, s);
	if (res1.length > res2.length) {
		swap (res1, res2);
		res1.each !((ref a) => swap (a[0], a[1]));
	}
	writeln (res1.length);
	foreach (line; res1) writefln ("%(%s %)", line);
}

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

int [] separators (string s, char start)
{
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
	{
		if (cur != c)
		{
			res ~= i + 1;
			cur = c;
		}
	}
	debug {writeln (res);}
	return res;
}

int [2] [] solve (string s, string t)
{
	int [2] [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front > 0 || q.front > 0)
	{
		res ~= [p.front, q.front];
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

void main ()
{
	string s, t;
	while ((s = readln.strip) != "")
	{
		t = readln.strip;
		auto res1 = solve (s, t);
		auto res2 = solve (t, s);
		if (res1.length > res2.length)
		{
			swap (res1, res2);
			res1.each !((ref a) => swap (a[0], a[1]));
		}
		writeln (res1.length);
		foreach (ref line; res1)
		{
			writefln ("%(%s %)", line[]);
		}
	}
}

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

alias Record = Tuple !(int, q{a}, int, q{b});

int [] separators (string s, char start)
{
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
	{
		if (cur != c)
		{
			res ~= i + 1;
			cur = c;
		}
	}
	debug {writeln (res);}
	return res;
}

Record [] solve (string s, string t)
{
	Record [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front > 0 || q.front > 0)
	{
		res ~= Record (p.front, q.front);
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

Record [] solveStrategyLayer (string s, string t)
{
	Record [] res = solve (s, t);
	auto p = separators (s, 'a').chain (0.only).retro.array;
	auto q = separators (t, 'b').chain (0.only).retro.array;
	int balance = p.length.to!int - q.length.to!int;
	foreach (i; 0..4)
	{
		foreach (j; 0..3)
		{
			int u = abs (balance) - 2 + i;
			int v = j;
			if (balance < 0)
			{
				swap (u, v);
			}
			if (u < 0 || p.length <= u || v < 0 || q.length <= v)
			{
				continue;
			}
			auto s2 = t[0..q[v]] ~ s[p[u]..$];
			auto t2 = s[0..p[u]] ~ t[q[v]..$];
			Record [] temp = [Record (p[u], q[v])];
			temp ~= solve (s2, t2);
			if (res.length > temp.length)
			{
				res = temp;
			}
		}
	}
	return res;
}

void main ()
{
	string s, t;
	while ((s = readln.strip) != "")
	{
		t = readln.strip;
		auto res1 = solveStrategyLayer (s, t);
		auto res2 = solveStrategyLayer (t, s);
		if (res1.length > res2.length)
		{
			swap (res1, res2);
			res1.each !((ref a) => swap (a[0], a[1]));
		}
		writeln (res1.length);
		foreach (ref line; res1)
		{
			writefln ("%s %s", line.a, line.b);
		}
	}
}

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

int [] separators (string s, char start)
{
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
	{
		if (cur != c)
		{
			res ~= i + 1;
			cur = c;
		}
	}
	debug {writeln (res);}
	return res;
}

int [2] [] solve (string s, string t)
{
	int [2] [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front > 0 || q.front > 0)
	{
		res ~= [p.front, q.front];
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

int [2] [] solveStrategyLayer (string s, string t)
{
	int [2] [] res = solve (s, t);
	auto p = separators (s, 'a').chain (0.only).retro.array;
	auto q = separators (t, 'b').chain (0.only).retro.array;
	int balance = p.length.to!int - q.length.to!int;
	foreach (i; 0..4)
	{
		foreach (j; 0..2)
		{
			int u = abs (balance) - 1 + i;
			int v = j;
			if (balance < 0)
			{
				swap (u, v);
			}
			if (u < 0 || p.length <= u || v < 0 || q.length <= v)
			{
				continue;
			}
			auto s2 = t[0..q[v]] ~ s[p[u]..$];
			auto t2 = s[0..p[u]] ~ t[q[v]..$];
			int [2] [] temp = [[p[u], q[v]]];
			temp ~= solve (s2, t2);
			if (res.length > temp.length)
			{
				res = temp;
			}
		}
	}
	return res;
}

void main ()
{
	string s, t;
	while ((s = readln.strip) != "")
	{
		t = readln.strip;
		auto res1 = solveStrategyLayer (s, t);
		auto res2 = solveStrategyLayer (t, s);
		if (res1.length > res2.length)
		{
			swap (res1, res2);
			res1.each !((ref a) => swap (a[0], a[1]));
		}
		writeln (res1.length);
		foreach (ref line; res1)
		{
			writefln ("%(%s %)", line[]);
		}
	}
}

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

auto separators (string s, char start) {
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
		if (cur != c) {
			res ~= i + 1;
			cur = c;
		}
	return res;
}

auto solveSingle (string s, string t)
{
	int [2] [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front + q.front) {
		res ~= [p.front, q.front];
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

auto solve (string s, string t) {
	auto res = solveSingle (s, t);
	auto p = separators (s, 'a') ~ 0, q = separators (t, 'b') ~ 0;
	reverse (p);
	reverse (q);
	auto balance = (p.length.to!int - q.length.to!int) / 2;
	foreach (i; 0..2) foreach (j; 0..2) {
		int u = abs (balance) - 1 + i;
		int v = j;
		if (balance < 0) swap (u, v);
		if (u < 0 || p.length <= u || v < 0 || q.length <= v) continue;
		auto s2 = t[0..q[v]] ~ s[p[u]..$], t2 = s[0..p[u]] ~ t[q[v]..$];
		int [2] [] temp = [[p[u], q[v]]];
		temp ~= solveSingle (s2, t2);
		if (res.length > temp.length) res = temp;
	}
	return res;
}

void main () {
	auto s = readln.strip, t = readln.strip;
	auto res1 = solve (s, t), res2 = solve (t, s);
	if (res1.length > res2.length) {
		swap (res1, res2);
		res1.each !((ref a) => swap (a[0], a[1]));
	}
	writeln (res1.length);
	foreach (line; res1) writefln ("%(%s %)", line);
}

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

alias Record = Tuple !(int, q{a}, int, q{b});

int [] separators (string s, char start)
{
	int [] res;
	char cur = start;
	foreach_reverse (int i, char c; s)
	{
		if (cur != c)
		{
			res ~= i + 1;
			cur = c;
		}
	}
	debug {writeln (res);}
	return res;
}

Record [] solve (string s, string t)
{
	Record [] res;
	auto p = separators (s, 'a').chain (0.only.cycle);
	auto q = separators (t, 'b').chain (0.only.cycle);
	while (p.front > 0 || q.front > 0)
	{
		res ~= Record (p.front, q.front);
		p.popFront ();
		q.popFront ();
		swap (p, q);
	}
	return res;
}

Record [] solveStrategyLayer (string s, string t)
{
	Record [] res = solve (s, t);
	auto p = separators (s, 'a').chain (0.only).retro.array;
	auto q = separators (t, 'b').chain (0.only).retro.array;
	int balance = p.length.to!int - q.length.to!int;
	foreach (i; 0..6)
	{
		foreach (j; 0..2)
		{
			int u = abs (balance) - 2 + i;
			int v = j;
			if (balance < 0)
			{
				swap (u, v);
			}
			if (u < 0 || p.length <= u || v < 0 || q.length <= v)
			{
				continue;
			}
			auto s2 = t[0..q[v]] ~ s[p[u]..$];
			auto t2 = s[0..p[u]] ~ t[q[v]..$];
			Record [] temp = [Record (p[u], q[v])];
			temp ~= solve (s2, t2);
			if (res.length > temp.length)
			{
				res = temp;
			}
		}
	}
	return res;
}

void main ()
{
	string s, t;
	while ((s = readln.strip) != "")
	{
		t = readln.strip;
		auto res1 = solveStrategyLayer (s, t);
		auto res2 = solveStrategyLayer (t, s);
		if (res1.length > res2.length)
		{
			swap (res1, res2);
			res1.each !((ref a) => swap (a[0], a[1]));
		}
		writeln (res1.length);
		foreach (ref line; res1)
		{
			writefln ("%s %s", line.a, line.b);
		}
	}
}


Arthur owns a ski resort on a mountain. There are $$$n$$$ landing spots on the mountain numbered from $$$1$$$ to $$$n$$$ from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are no directed cycles formed by the tracks. There are at most two tracks leaving each spot, but many tracks may enter the same spot.A skier can start skiing from one spot and stop in another spot if there is a sequence of tracks that lead from the starting spot and end in the ending spot. Unfortunately, recently there were many accidents, because the structure of the resort allows a skier to go through dangerous paths, by reaching high speed and endangering himself and the other customers. Here, a path is called dangerous, if it consists of at least two tracks.Arthur wants to secure his customers by closing some of the spots in a way that there are no dangerous paths in the resort. When a spot is closed, all tracks entering and leaving that spot become unusable. Formally, after closing some of the spots, there should not be a path that consists of two or more tracks.Arthur doesn't want to close too many spots. He will be happy to find any way to close at most $$$\frac{4}{7}n$$$ spots so that the remaining part is safe. Help him find any suitable way to do so.

The first line contains a single positive integer $$$T$$$ — the number of test cases. $$$T$$$ test case description follows. The first line of each description contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of landing spots and tracks respectively. The following $$$m$$$ lines describe the tracks. Each of these lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x < y \leq n$$$) — indices of the starting and finishing spots for the respective track. It is guaranteed that at most two tracks start at each spot. There may be tracks in which starting and finishing spots both coincide. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer $$$k$$$ ($$$0 \leq k \leq \frac{4}{7}n$$$) — the number of spots to be closed. In the next line, print $$$k$$$ distinct integers — indices of all spots to be closed, in any order. If there are several answers, you may output any of them. Note that you don't have to minimize $$$k$$$. It can be shown that a suitable answer always exists.

NoteIn the first sample case, closing any two spots is suitable.In the second sample case, closing only the spot $$$1$$$ is also suitable.

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

void main ()
{
	foreach (t; 0..readln.strip.to !(int))
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto adj = new bool [int] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[v][u] = true;
		}

		auto z = new bool [n];
		foreach (u; 0..n)
		{
			bool [int] temp;
			foreach (v, _; adj[u])
			{
				if (!z[v])
				{
					temp[v] = true;
				}
			}
			adj[u] = temp;
			foreach (v, _; adj[u])
			{
				foreach (w, _; adj[v])
				{
					if (!z[w])
					{
						z[u] = true;
					}
				}
			}
		}

		writeln (z.sum);
		writefln !("%(%s %)")
		    (n.iota.filter !(u => z[u]).map !(q{a + 1}));
	}
}

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

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

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

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

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

        auto graph = new int[][N];
        foreach (i; 0 .. M) {
          graph[B[i]] ~= A[i];
        }

        auto col = new int[N];
        foreach (u; 0 .. N) {
          foreach (v; graph[u]) {
            if (col[v] < 2) {
              chmax(col[u], col[v] + 1);
            }
          }
        }

        const ans = iota(N).filter!(u => (col[u] == 2)).array;
        writeln(ans.length);
        foreach (index, u; ans) {
          if (index > 0) write(" ");
          write(u + 1);
        }
        writeln();
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	foreach (t; 0..readln.strip.to !(int))
	{
		int n, m;
		readf !(" %s %s") (n, m);
		auto adj = new int [] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
		}

		auto z = new bool [n];
		foreach_reverse (u; 0..n)
		{
			foreach (v; adj[u])
			{
				if (!z[v])
				{
					foreach (w; adj[v])
					{
						if (!z[w])
						{
							z[u] = true;
						}
					}
				}
			}
		}

		writeln (z.sum);
		writefln !("%(%s %)")
		    (n.iota.filter !(u => z[u]).map !(q{a + 1}));
	}
}

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 N, M;
int[] A, B;

bool[] del;
int[][] graph;
int[][] dp;
int[][] prev;

void solve(int u) {
  auto sums = new int[3];
  foreach (v; graph[u]) {
    solve(v);
    sums[] += dp[v][];
  }
  foreach (k; 0 .. 3) {
    // delete
    dp[u][k] = 1 + sums[0];
    // keep
    if (k < 2) {
      if (chmin(dp[u][k], sums[k + 1])) {
        prev[u][k] = 1;
      }
    }
  }
}

void recover(int u, int k) {
  int kk;
  if (prev[u][k] == 0) {
    del[u] = true;
    kk = 0;
  } else {
    kk = k + 1;
  }
  foreach (v; graph[u]) {
    recover(v, kk);
  }
}

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

        alias Entry = Tuple!(int, "deg", int, "u");
        auto es = new Entry[N];
        foreach (u; 0 .. N) {
          es[u].u = u;
        }
        auto graphIn = new int[][N];
        foreach (i; 0 .. M) {
          --es[A[i]].deg;
          --es[B[i]].deg;
          graphIn[B[i]] ~= A[i];
        }
        es.sort;

        del = new bool[N];
        foreach_reverse (ref e; es) {
          const u = e.u;
          int indeg;
          foreach (v; graphIn[u]) {
            if (!del[v]) {
              ++indeg;
            }
          }
          if (indeg >= 2) {
            del[u] = true;
          }
        }
        debug {
          writeln("del = ", del);
        }

        graph = new int[][N];
        auto isChild = new bool[N];
        foreach (i; 0 .. M) {
          if (!del[A[i]] && !del[B[i]]) {
            graph[A[i]] ~= B[i];
            isChild[B[i]] = true;
          }
        }
        debug {
          writeln("graph = ", graph);
        }

        dp = new int[][](N, 3);
        prev = new int[][](N, 3);
        foreach (u; 0 .. N) {
          if (!del[u]) {
            if (!isChild[u]) {
              solve(u);
              recover(u, 0);
            }
          }
        }
        debug {
          writeln("dp = ", dp);
          writeln("del = ", del);
        }

        int[] ans;
        foreach (u; 0 .. N) {
          if (del[u]) {
            ans ~= u;
          }
        }

if(ans.length>N*7/4)for(;;){}
        writeln(ans.length);
        foreach (index, u; ans) {
          if (index > 0) write(" ");
          write(u + 1);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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 N, M;
int[] A, B;

bool[] del;
int[][] graph;
int[][] dp;
int[][] prev;

void solve(int u) {
  auto sums = new int[3];
  foreach (v; graph[u]) {
    solve(v);
    sums[] += dp[v][];
  }
  foreach (k; 0 .. 3) {
    // delete
    dp[u][k] = 1 + sums[0];
    // keep
    if (k < 2) {
      if (chmin(dp[u][k], sums[k + 1])) {
        prev[u][k] = 1;
      }
    }
  }
}

void recover(int u, int k) {
  int kk;
  if (prev[u][k] == 0) {
    del[u] = true;
    kk = 0;
  } else {
    kk = k + 1;
  }
  foreach (v; graph[u]) {
    recover(v, kk);
  }
}

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

        auto graphIn = new int[][N];
        foreach (i; 0 .. M) {
          graphIn[B[i]] ~= A[i];
        }

        del = new bool[N];
        foreach (u; 0 .. N) {
          int indeg;
          foreach (v; graphIn[u]) {
            if (!del[v]) {
              ++indeg;
            }
          }
          if (indeg >= 2) {
            del[u] = true;
          }
        }
        debug {
          writeln("del = ", del);
        }

        graph = new int[][N];
        auto isChild = new bool[N];
        foreach (i; 0 .. M) {
          if (!del[A[i]] && !del[B[i]]) {
            graph[A[i]] ~= B[i];
            isChild[B[i]] = true;
          }
        }
        debug {
          writeln("graph = ", graph);
        }

        dp = new int[][](N, 3);
        prev = new int[][](N, 3);
        foreach (u; 0 .. N) {
          if (!del[u]) {
            if (!isChild[u]) {
              solve(u);
              recover(u, 0);
            }
          }
        }
        debug {
          writeln("dp = ", dp);
          writeln("del = ", del);
        }

        int[] ans;
        foreach (u; 0 .. N) {
          if (del[u]) {
            ans ~= u;
          }
        }

        writeln(ans.length);
        foreach (index, u; ans) {
          if (index > 0) write(" ");
          write(u + 1);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}


While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 108.

The first line contains two integers n and m (1 ≤ n, m ≤ 100)  — the size of the table.

Print the table that meets the condition: n lines containing m integers, separated by spaces. If there are multiple possible answers, you are allowed to print anyone. It is guaranteed that there exists at least one correct answer.

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

immutable int MAX_N = 102;
immutable int MAX_L = MAX_N ^^ 2;
immutable int NA = -1;

int [] [] f;

void prepare ()
{
	f = new int [] [] (MAX_L, MAX_N);
	foreach (ref g; f)
	{
		g[] = NA;
	}
	f[0][0] = 0;
	foreach (i; 1..MAX_L)
	{
		foreach (k; 1..MAX_N)
		{
			int k2 = k * k;
			if (k2 > i)
			{
				break;
			}
			foreach (j; 1..MAX_N)
			{
				if (f[i][j] == NA && f[i - k2][j - 1] != NA)
				{
					f[i][j] = k;
				}
			}
		}
	}

	debug
	{
		foreach (i; 0..MAX_N)
		{
			foreach (k; 0..MAX_N)
			{
				int k2 = k * k;
				if (f[k2][i] != NA)
				{
					writeln (i, ": ", k);
					break;
				}
			}
		}
	}
}

int [] solve (int n)
{
	int [] res;
	foreach (k; 0..MAX_N)
	{
		int k2 = k * k;
		if (f[k2][n] != NA)
		{
			int x = k2;
			int y = n;
			while (x)
			{
				res ~= f[x][y];
				x -= f[x][y] ^^ 2;
				y--;
			}
			assert (y == 0);
			return res;
		}
	}
	return res;
}

void main ()
{
	prepare ();

	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = solve (n);
		auto b = solve (m);
		debug {writeln (a, ' ', b);}
		auto c = new int [] [] (n, m);
		foreach (i; 0..n)
		{
			foreach (j; 0..m)
			{
				c[i][j] = a[i] * b[j];
			}
		}
		writefln ("%(%(%s %)\n%)", c);
	}
}


Vasya has recently bought some land and decided to surround it with a wooden fence.He went to a company called "Wooden board" that produces wooden boards for fences. Vasya read in the catalog of products that the company has at its disposal n different types of wood. The company uses the i-th type of wood to produce a board of this type that is a rectangular ai by bi block.Vasya decided to order boards in this company and build a fence from them. It turned out that the storehouse of the company is so large that Vasya can order arbitrary number of boards of every type. Note that Vasya is allowed to turn the boards as he builds the fence. However, Vasya cannot turn square boards.Vasya is required to construct a fence of length l, however, an arbitrary fence won't do. Vasya wants his fence to look beautiful. We'll say that a fence is beautiful if and only if the following two conditions are fulfilled:  there are no two successive boards of the same type  the first board of the fence has an arbitrary length, and the length of each subsequent board equals the width of the previous one In other words, the fence is considered beautiful, if the type of the i-th board in the fence is different from the i - 1-th board's type; besides, the i-th board's length is equal to the i - 1-th board's width (for all i, starting from 2).Now Vasya wonders, how many variants of arranging a fence for his land exist. Your task is to count the number of different beautiful fences of length l.Two fences will be considered the same if the corresponding sequences of fence boards types and rotations are the same, otherwise the fences are different. Since the sought number can be large enough, you need to calculate the answer modulo 1000000007 (109 + 7).

The first line contains two integers n and l (1 ≤ n ≤ 100, 1 ≤ l ≤ 3000) — the number of different board types and the fence length, correspondingly. Next n lines contain descriptions of board types: the i-th line contains two integers ai and bi (1 ≤ ai, bi ≤ 100) — the sizes of the board of the i-th type. All numbers on the lines are separated by spaces.

Print a single integer — the sought number of variants modulo 1000000007 (109 + 7).

NoteIn the first sample there are exactly two variants of arranging a beautiful fence of length 3:   As the first fence board use the board of the first type of length 1 and width 2. As the second board use board of the second type of length 2 and width 3.  Use one board of the second type after you turn it. That makes its length equal 3, and width — 2.

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

immutable int MD = 10 ^^ 9 + 7;

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

    int[][] arr;
    foreach (i; 0 .. n) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        arr ~= [x, y];
    }

    debug { arr.writeln; }

    auto dp = new int[][][] (len+1, n, 2);
    foreach (i, e; arr) {
        if (e[0] <= len) { dp[e[0]][i][0] = 1; }
        if (e[1] <= len && e[1] != e[0]) { dp[e[1]][i][1] = 1; }
    }

    debug { dp.writeln; }

    foreach (clen; 2 .. len+1) {
        foreach (i, e; arr) {
            foreach (turn; 0 .. 2) {
                if (turn == 1 && e[0] == e[1]) { continue; }

                int elen = e[turn];
                if (elen >= clen) { continue; }

                foreach (j, p; arr) {
                    if (i == j) { continue; }

                    foreach (pTurn; 0 .. 2) {
                        if (pTurn == 1 && p[0] == p[1]) { continue; }

                        int pMatch = p[1 - pTurn];
                        if (elen != pMatch) { continue; }

                        debug { if (clen == 3 && i == 1) { writeln(turn, ' ', j, ' ', pTurn, ' ', pMatch, ' ', dp[clen-elen][j][pTurn]); } }
                        dp[clen][i][turn] = (dp[clen][i][turn] + dp[clen-elen][j][pTurn]) % MD;
                    }
                }
            }
        }
    }

    debug { dp.each!writeln; }

    int ans = 0;
    foreach (ref e; dp[len]) {
        foreach (et; e) { ans = (ans + et) % MD; }
    }

    ans.writeln;
}

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

immutable int MD = 10 ^^ 9 + 7;

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

    int[][] arr;
    foreach (i; 0 .. n) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        arr ~= [x, y];
    }

    debug { arr.writeln; }

    auto dp = new int[][][] (len+1, n, 2);
    foreach (i, e; arr) {
        dp[e[0]][i][0] = 1;
        dp[e[1]][i][1] = 1;
    }

    debug { dp.writeln; }

    foreach (clen; 2 .. len+1) {
        foreach (i, e; arr) {
            foreach (turn; 0 .. 2) {
                if (turn == 1 && e[0] == e[1]) { continue; }

                int elen = e[turn];
                if (elen >= clen) { continue; }

                foreach (j, p; arr) {
                    if (i == j) { continue; }

                    foreach (pTurn; 0 .. 2) {
                        if (pTurn == 1 && p[0] == p[1]) { continue; }

                        int pMatch = p[1 - pTurn];
                        if (elen != pMatch) { continue; }

                        debug { if (clen == 3 && i == 1) { writeln(turn, ' ', j, ' ', pTurn, ' ', pMatch, ' ', dp[clen-elen][j][pTurn]); } }
                        dp[clen][i][turn] = (dp[clen][i][turn] + dp[clen-elen][j][pTurn]) % MD;
                    }
                }
            }
        }
    }

    debug { dp.each!writeln; }

    int ans = 0;
    foreach (ref e; dp[len]) {
        foreach (et; e) { ans = (ans + et) % MD; }
    }

    ans.writeln;
}


You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.Let's define the $$$k$$$-coloring of the tree as an assignment of exactly $$$k$$$ colors to each vertex, so that each color is used no more than two times. You can assume that you have infinitely many colors available. We say that an edge is saturated in the given $$$k$$$-coloring if its endpoints share at least one color (i.e. there exists a color that is assigned to both endpoints).Let's also define the value of a $$$k$$$-coloring as the sum of weights of saturated edges.Please calculate the maximum possible value of a $$$k$$$-coloring of the given tree.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) – the number of queries. The first line of each query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 5 \cdot 10^5$$$) — the number of vertices in the tree and the number of colors to assign to each vertex, respectively. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$, $$$1 \le w_i \le 10^5$$$) — the labels of vertices it connects and the weight of the edge. It is guaranteed that the given edges form a tree. It is guaranteed that sum of all $$$n$$$ over all queries does not exceed $$$5 \cdot 10^5$$$.

For each query print one integer — the maximum value of a $$$k$$$-coloring of the given tree.

NoteThe tree corresponding to the first query in the example:One of the possible $$$k$$$-colorings in the first example: $$$(1), (1), (2), (2)$$$, then the $$$1$$$-st and the $$$3$$$-rd edges are saturated and the sum of their weights is $$$8$$$.The tree corresponding to the second query in the example:One of the possible $$$k$$$-colorings in the second example: $$$(1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6)$$$, then the $$$1$$$-st, $$$2$$$-nd, $$$5$$$-th and $$$6$$$-th edges are saturated and the sum of their weights is $$$14$$$.

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

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

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

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

int N, K;
int[] U, V;
long[] W;

int[][] G;
long[][] dp;

void dfs(int u, int p) {
  long sum0;
  long[] diffs;
  foreach (i; G[u]) {
    const v = U[i] ^ V[i] ^ u;
    if (v != p) {
      dfs(v, u);
      sum0 += dp[v][0];
      diffs ~= max((W[i] + dp[v][1]) - dp[v][0], 0);
    }
  }
  sort(diffs);
  reverse(diffs);
  dp[u][] = sum0;
  foreach (j; 0 .. diffs.length) {
    if (j < K) {
      dp[u][0] += diffs[j];
    }
    if (j < K - 1) {
      dp[u][1] += diffs[j];
    }
  }
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        N = readInt();
        K = readInt();
        U = new int[N - 1];
        V = new int[N - 1];
        W = new long[N - 1];
        foreach (i; 0 .. N - 1) {
          U[i] = readInt() - 1;
          V[i] = readInt() - 1;
          W[i] = readLong();
        }

        G = new int[][N];
        foreach (i; 0 .. N - 1) {
          G[U[i]] ~= i;
          G[V[i]] ~= i;
        }
        dp = new long[][](N, 2);
        const rt = 0;
        dfs(rt, -1);
        debug {
          writeln("dp = ", dp);
        }
        writeln(dp[rt][0]);
      }
    }
  } catch (EOFException e) {
  }
}


Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n). The answer to the query li, ri is the number of such integers i (li ≤ i < ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.

The first line contains string s of length n (2 ≤ n ≤ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≤ li < ri ≤ n).

Print m integers — the answers to the queries in the order in which they are given in the input.

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

void main() {
    auto S = readln.chomp;
    auto N = S.length.to!int;

    auto same = new int[](N);
    foreach (i; 1..N) {
        same[i] = (S[i] == S[i-1]);
    }

    auto acm = new int[](N);
    foreach (i; 1..N) {
        acm[i] = acm[i-1] + same[i];
    }

    auto M = readln.chomp.to!int;
    foreach (_; 0..M) {
        auto s = readln.split.map!(to!int);
        auto l = s[0]-1;
        auto r = s[1]-1;
        writeln(acm[r] - acm[max(0, l-1)] - same[l]);
    }

}

// https://codeforces.com/problemset/problem/313/B
import std.stdio;
import std.string;
import std.conv;

void main() {
    string s = readln.chomp;

    int[100005] a;

    for(int i = 1; i < s.length; i++) {
        if(s[i] == s[i-1])
            a[i] = 1;
        a[i] += a[i-1];
    }

    int m = readln.chomp.to!int;
    //m.writeln;

    int l, r;
    foreach(idx; 0..m) {
        readf("%d %d\n", &l, &r);
        writefln("%d", a[--r]-a[--l]);
    }
}

// https://codeforces.com/problemset/problem/313/B
import std.stdio;
import std.string;
import std.conv;

void main() {
    string s = readln.chomp;

    int[100005] a;

    for(int i = 1; i < s.length; i++) {
        if(s[i] == s[i-1])
            a[i] = 1;
    }

    for(int i = 1; i < s.length; i++) {
        a[i] += a[i-1];
    }

    int m = readln.chomp.to!int;
    //m.writeln;

    int l, r;
    foreach(idx; 0..m) {
        readf("%d %d\n", &l, &r);
        writefln("%d", a[--r]-a[--l]);
    }
}

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

void main ()
{
	string s;
	while ((s = readln ()) != null)
	{
		int n = s.length;
		auto a = new int [n];
		a[0] = 0;
		foreach (i; 1..n)
		{
			a[i] = (s[i - 1] == s[i]);
		}
		foreach (i; 1..n)
		{
			a[i] += a[i - 1];
		}

		int m;
		readf (" %s ", &m);
		foreach (i; 0..m)
		{
			int l, r;
			readf (" %s %s ", &l, &r);
			writeln (a[r - 1] - a[l - 1]);
		}
	}
}

import std.stdio: readln, writeln;
import std.string: strip;
import std.conv: to;
import std.array: split;

/**
 * User: Jior
 * Date: 03.06.13
 * Time: 14:25
 */

void main(string[] args) {
    int[100001] m;
    char[] inString = strip(readln()).dup;
    for(int i = 0; i < inString.length-1; i++) {
        m[i+1] = m[i] + (inString[i] == inString[i+1]);
    }

    int countReq = to!int(strip(readln()).dup);
    foreach(int regNum; 0..countReq) {
        string request = strip(readln());
        int[] reqValue = to!(int[])(request.split());
        writeln(m[reqValue[1]-1] - m[reqValue[0]-1]);
    }
}

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

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    string str = strip(readln());
    int n = str.length;
    int[] a = new int[n];
    foreach (i; 0..n-1) {
        a[i] = str[i] == str[i+1];
    }
    foreach (i; 1..n-1) {
        a[i] += a[i-1];
    }
    int m;
    readf("%d ", &m);
    foreach (i; 0..m) {
        int l;
        int r;
        readf("%d %d ", &l, &r);
        l--;
        r--;
        int res = a[r-1]-(l == 0 ? 0 : a[l-1]);
        writeln(res);
    }
}

// https://codeforces.com/problemset/problem/313/B
import std.stdio;
import std.string;
import std.conv;

void main() {
    string s = readln.chomp;

    int[100005] a;

    for(int i = 1; i < s.length; i++) {
        if(s[i] == s[i-1])
            a[i+1] = 1;
        a[i] += a[i-1];
    }

    int m = readln.chomp.to!int;
    //m.writeln;

    int l, r;
    foreach(idx; 0..m) {
        readf("%d %d\n", &l, &r);
        writefln("%d", a[--r]-a[--l]);
    }
}


Given three numbers $$$n, a, b$$$. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to $$$a$$$, and the number of components in its complement is $$$b$$$. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.The adjacency matrix of an undirected graph is a square matrix of size $$$n$$$ consisting only of "0" and "1", where $$$n$$$ is the number of vertices of the graph and the $$$i$$$-th row and the $$$i$$$-th column correspond to the $$$i$$$-th vertex of the graph. The cell $$$(i,j)$$$ of the adjacency matrix contains $$$1$$$ if and only if the $$$i$$$-th and $$$j$$$-th vertices in the graph are connected by an edge.A connected component is a set of vertices $$$X$$$ such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to $$$X$$$ violates this rule.The complement or inverse of a graph $$$G$$$ is a graph $$$H$$$ on the same vertices such that two distinct vertices of $$$H$$$ are adjacent if and only if they are not adjacent in $$$G$$$.

In a single line, three numbers are given $$$n, a, b \,(1 \le n \le 1000, 1 \le a, b \le n)$$$: is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement.

If there is no graph that satisfies these constraints on a single line, print "NO" (without quotes). Otherwise, on the first line, print "YES"(without quotes). In each of the next $$$n$$$ lines, output $$$n$$$ digits such that $$$j$$$-th digit of $$$i$$$-th line must be $$$1$$$ if and only if there is an edge between vertices $$$i$$$ and $$$j$$$ in $$$G$$$ (and $$$0$$$ otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes.  If there are several matrices that satisfy the conditions — output any of them.

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

immutable long MOD = 10^^9+7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto A = s[1];
    auto B = s[2];
    bool sw = false;
    if (A > B) swap(A, B), sw = true;

    if (A != 1) {
        writeln("NO");
        return;
    }

    if (N == 2 && A == 1 && B == 1) {
        writeln("NO");
        return;
    }
    if (N == 3 && A == 1 && B == 1) {
        writeln("NO");
        return;
    }

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

    foreach (i; 0..N-B)
        ans[i][i+1] = ans[i+1][i] = 1;

    if (!sw && !(A == 1 && B == 1)) {
        foreach (i; 0..N) foreach (j; 0..N) if (i != j) ans[i][j] ^= 1;
    }

    writeln("YES");
    ans.each!(a => a.map!(to!string).join("").writeln);
}

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

immutable long MOD = 10^^9+7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto A = s[1];
    auto B = s[2];
    bool sw = false;
    if (A > B) swap(A, B), sw = true;

    if (A != 1) {
        writeln("NO");
        return;
    }

    if (N == 3 && A == 1 && B == 1) {
        writeln("NO");
        return;
    }

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

    foreach (i; 0..N-B)
        ans[i][i+1] = ans[i+1][i] = 1;

    if (!sw && !(A == 1 && B == 1)) {
        foreach (i; 0..N) foreach (j; 0..N) if (i != j) ans[i][j] ^= 1;
    }

    writeln("YES");
    ans.each!(a => a.map!(to!string).join("").writeln);
}

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

immutable long MOD = 10^^9+7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto A = s[1];
    auto B = s[2];
    bool sw = false;
    if (A > B) swap(A, B), sw = true;

    if (A != 1) {
        writeln("NO");
        return;
    }

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

    foreach (i; 0..N-B)
        ans[i][i+1] = ans[i+1][i] = 1;

    if (!sw) {
        foreach (i; 0..N) foreach (j; 0..N) if (i != j) ans[i][j] ^= 1;
    }

    writeln("YES");
    ans.each!(a => a.map!(to!string).join(" ").writeln);
}

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

immutable long MOD = 10^^9+7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto A = s[1];
    auto B = s[2];
    bool sw = false;
    if (A > B) swap(A, B), sw = true;

    if (A != 1) {
        writeln("NO");
        return;
    }

    if (A == 1 && B == 1) {
        if (N == 1) {
            writeln("YES");
            writeln(0);
        } else {
            writeln("NO");
        }
        return;
    }

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

    foreach (i; 0..N-B)
        ans[i][i+1] = ans[i+1][i] = 1;

    if (!sw) {
        foreach (i; 0..N) foreach (j; 0..N) if (i != j) ans[i][j] ^= 1;
    }

    writeln("YES");
    ans.each!(a => a.map!(to!string).join("").writeln);
}

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

immutable long MOD = 10^^9+7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto A = s[1];
    auto B = s[2];
    bool sw = false;
    if (A > B) swap(A, B), sw = true;

    if (A != 1) {
        writeln("NO");
        return;
    }

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

    foreach (i; 0..N-B)
        ans[i][i+1] = ans[i+1][i] = 1;

    if (!sw) {
        foreach (i; 0..N) foreach (j; 0..N) if (i != j) ans[i][j] ^= 1;
    }

    writeln("YES");
    ans.each!(a => a.map!(to!string).join("").writeln);
}


You are given an integer $$$n$$$. You have to construct a permutation of size $$$n$$$.A permutation is an array where each integer from $$$1$$$ to $$$s$$$ (where $$$s$$$ is the size of permutation) occurs exactly once. For example, $$$[2, 1, 4, 3]$$$ is a permutation of size $$$4$$$; $$$[1, 2, 4, 5, 3]$$$ is a permutation of size $$$5$$$; $$$[1, 4, 3]$$$ is not a permutation (the integer $$$2$$$ is absent), $$$[2, 1, 3, 1]$$$ is not a permutation (the integer $$$1$$$ appears twice).A subsegment of a permutation is a contiguous subsequence of that permutation. For example, the permutation $$$[2, 1, 4, 3]$$$ has $$$10$$$ subsegments: $$$[2]$$$, $$$[2, 1]$$$, $$$[2, 1, 4]$$$, $$$[2, 1, 4, 3]$$$, $$$[1]$$$, $$$[1, 4]$$$, $$$[1, 4, 3]$$$, $$$[4]$$$, $$$[4, 3]$$$ and $$$[3]$$$.The value of the permutation is the number of its subsegments which are also permutations. For example, the value of $$$[2, 1, 4, 3]$$$ is $$$3$$$ since the subsegments $$$[2, 1]$$$, $$$[1]$$$ and $$$[2, 1, 4, 3]$$$ are permutations.You have to construct a permutation of size $$$n$$$ with minimum possible value among all permutations of size $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 48$$$) — the number of test cases. Then, $$$t$$$ lines follow. The $$$i$$$-th of them contains one integer $$$n$$$ ($$$3 \le n \le 50$$$) representing the $$$i$$$-th test case.

For each test case, print $$$n$$$ integers — the permutation of size $$$n$$$ with minimum possible value. If there are multiple such permutations, print any of them.

NoteIn the first example, the permutation $$$[1, 4, 3, 5, 2]$$$ is one of the possible answers; its value is $$$2$$$.In the second example, the permutation $$$[4, 1, 6, 2, 5, 3]$$$ is one of the possible answers; its value is $$$2$$$.

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

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

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

void solve() {
    int n = read!int;
    int[] res;
    for(int i = 1; i <= n / 2 + n % 2; i++) {
        res ~= i;
        if (i > n - i)
            break;
        res ~= n - i + 1;
    }
    writefln("%(%s %)",res);
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto a = iota(1, n + 1).array;
    swap(a[1], a[$ - 1]);
    writefln("%(%s %)", a);
  }
}

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

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

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

void solve() {
    int N = read!int;
    auto a = new int[N];
    int l = 0, r = N - 1;
    for (int k = 1; k <= N; k++) {
        if (k % 2 == 0) {
            a[r--] = k;
        } else {
            a[l++] = k;
        }
    }
    writefln("%(%s %)", a);
}

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

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

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

void solve() {
    int n = read!int;
    int[] res;
    for(int i = 1; i <= n; i++) {
        res ~= i;
        if (i > n - i)
            break;
        res ~= n - i + 1;
    }
    writefln("%(%s %)",res);
}

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