You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges.You have to write a number on each vertex of the graph. Each number should be $$$1$$$, $$$2$$$ or $$$3$$$. The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers $$$1$$$, $$$2$$$ and $$$3$$$ on vertices so the graph becomes beautiful. Since this number may be large, print it modulo $$$998244353$$$.Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) — the number of tests in the input. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5$$$) — the number of vertices and the number of edges, respectively. Next $$$m$$$ lines describe edges: $$$i$$$-th line contains two integers $$$u_i$$$, $$$ v_i$$$ ($$$1 \le u_i, v_i \le n; u_i \neq v_i$$$) — indices of vertices connected by $$$i$$$-th edge. It is guaranteed that $$$\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5$$$ and $$$\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5$$$.

For each test print one line, containing one integer — the number of possible ways to write numbers $$$1$$$, $$$2$$$, $$$3$$$ on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo $$$998244353$$$.

NotePossible ways to distribute numbers in the first test:   the vertex $$$1$$$ should contain $$$1$$$, and $$$2$$$ should contain $$$2$$$;  the vertex $$$1$$$ should contain $$$3$$$, and $$$2$$$ should contain $$$2$$$;  the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$1$$$;  the vertex $$$1$$$ should contain $$$2$$$, and $$$2$$$ should contain $$$3$$$. In the second test there is no way to distribute numbers.

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

immutable long MOD = 998244353;

long powmod(long a, long x, long m) {
    long ret = 1;
    while (x) {
        if (x % 2) ret = ret * a % m;
        a = a * a % m;
        x /= 2;
    }
    return ret;
}

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

    long ans = 1;
    auto cnt = new long[](2);
    auto C = new int[](N);
    fill(C, -1);

    bool dfs(int n, int c) {
        if (C[n] != -1)
            return C[n] == c;
        C[n] = c;
        cnt[c] += 1;
        foreach (m; G[n]) {
            if (C[m] != -1) {
                if (C[m] == (c^1))
                    continue;
                else
                    return false;
            }
            if (!dfs(m, c^1))
                return false;
        }
        return true;
    }

    foreach (i; 0..N) {
        if (C[i] != -1) continue;
        cnt[0] = cnt[1] = 0;
        if (dfs(i, 0)) {
            long tmp = powmod(2, cnt[0], MOD) + powmod(2, cnt[1], MOD);
            tmp %= MOD;
            ans = ans * tmp % MOD;
        } else {
            writeln(0);
            return;
        }
    }

    ans.writeln;
}

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

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.ascii, std.typecons;

void main()
{
    immutable int MD = 998244353;
    immutable int MXN = 3 * 10 ^^ 5;

    auto pw = new int[] (MXN + 1);
    pw[0] = 1;
    foreach (i; 1 .. MXN+1) { pw[i] = pw[i-1] * 2 % MD; }

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

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

        auto g = new int[][] (n+1);
        foreach (i; 0 .. m) {
            int u, v;
            readf("%s %s", &u, &v);
            readln;

            g[u] ~= v;
            g[v] ~= u;
        }

        auto clr = new int[] (n+1);
        clr[] = 0;
        int ans = 1;
        foreach (i; 1 .. n+1) {
            if (clr[i] != 0) { continue; }

            auto res = new int[] (3);
            res[] = 0;

            bool dfs(int v, int c) {
                clr[v] = c;
                res[c] += 1;
                auto ok = true;
                foreach (u; g[v]) {
                    if (clr[u] == 0) {
                        ok &= dfs(u, 3 - c);
                    }
                    else if (clr[u] == 3 - c) { continue; }
                    else { return false; }
                }

                return ok;
            }

            if (!dfs(i, 1)) {
                writeln(0);
                continue outer;
            }

            debug { writeln(i, ' ', res); }

            int cur = (pw[res[1]] + pw[res[2]]) % MD;
            ans = ans.to!long * cur % MD;
        }

        ans.writeln;
    }
}

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

immutable long MOD = 998244353;

long powmod(long a, long x, long m) {
    long ret = 1;
    while (x) {
        if (x % 2) ret = ret * a % m;
        a = a * a % m;
        x /= 2;
    }
    return ret;
}

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

    long ans = 0;
    auto cnt = new long[](2);
    auto C = new int[](N);
    fill(C, -1);

    bool dfs(int n, int c) {
        if (C[n] != -1)
            return C[n] == c;
        C[n] = c;
        cnt[c] += 1;
        foreach (m; G[n]) {
            if (C[m] != -1) {
                if (C[m] != (c^1))
                    return false;
                else
                    continue;
            }
            if (!dfs(m, c^1))
                return false;
        }
        return true;
    }

    foreach (i; 0..N) {
        if (C[i] != -1) continue;
        cnt[0] = cnt[1] = 0;
        if (dfs(i, 0)) {
            ans += powmod(2, cnt[0], MOD) + powmod(2, cnt[1], MOD);
            ans %= MOD;
        } else {
            writeln(0);
            return;
        }
    }

    ans.writeln;
}

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

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.ascii, std.typecons;

void main()
{
    immutable int MD = 998244353;
    immutable int MXN = 3 * 10 ^^ 5;

    auto pw = new int[] (MXN + 1);
    pw[0] = 1;
    foreach (i; 1 .. MXN+1) { pw[i] = pw[i-1] * 2 % MD; }

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

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

        auto g = new int[][] (n+1);
        foreach (i; 0 .. m) {
            int u, v;
            readf("%s %s", &u, &v);
            readln;

            g[u] ~= v;
            g[v] ~= u;
        }

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

        bool dfs(int v, int c) {
            clr[v] = c;
            bool ok = true;
            foreach (u; g[v]) {
                if (clr[u] == 0) {
                    ok &= dfs(u, 3 - c);
                }
                else if (clr[u] == 3 - c) { continue; }
                else { return false; }
            }

            return ok;
        }

        if (!dfs(1, 1)) {
            writeln(0);
            continue;
        }

        debug { writeln(clr); }

        auto side = clr.count!(x => x == 1).to!int;
        int ans = (pw[side] + pw[n - side]) % MD;
        ans.writeln;
    }
}


A frog is currently at the point $$$0$$$ on a coordinate axis $$$Ox$$$. It jumps by the following algorithm: the first jump is $$$a$$$ units to the right, the second jump is $$$b$$$ units to the left, the third jump is $$$a$$$ units to the right, the fourth jump is $$$b$$$ units to the left, and so on.Formally:   if the frog has jumped an even number of times (before the current jump), it jumps from its current position $$$x$$$ to position $$$x+a$$$;  otherwise it jumps from its current position $$$x$$$ to position $$$x-b$$$. Your task is to calculate the position of the frog after $$$k$$$ jumps.But... One more thing. You are watching $$$t$$$ different frogs so you have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. Each of the next $$$t$$$ lines contain queries (one query per line). The query is described as three space-separated integers $$$a, b, k$$$ ($$$1 \le a, b, k \le 10^9$$$) — the lengths of two types of jumps and the number of jumps, respectively.

Print $$$t$$$ integers. The $$$i$$$-th integer should be the answer for the $$$i$$$-th query.

NoteIn the first query frog jumps $$$5$$$ to the right, $$$2$$$ to the left and $$$5$$$ to the right so the answer is $$$5 - 2 + 5 = 8$$$.In the second query frog jumps $$$100$$$ to the right, $$$1$$$ to the left, $$$100$$$ to the right and $$$1$$$ to the left so the answer is $$$100 - 1 + 100 - 1 = 198$$$.In the third query the answer is $$$1 - 10 + 1 - 10 + 1 = -17$$$.In the fourth query the answer is $$$10^9 - 1 + 10^9 - 1 + 10^9 - 1 = 2999999997$$$.In the fifth query all frog's jumps are neutralized by each other so the answer is $$$0$$$.The sixth query is the same as the fifth but without the last jump so the answer is $$$1$$$.

import std.algorithm;
import std.container;
import std.conv;
import std.exception;
import std.format;
import std.math;
import std.random;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main()
{
    int t = readln.strip.to!int;

    while (t--)
    {
        long a, b, k;
        readf!" %s %s %s "(a, b, k);

        long ans = k / 2 * (a - b);
        if (k % 2)
            ans += a;

        writefln!"%s"(ans);
    }
}

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

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

    while (t--) {
        int a, b, k;
        readf("%s %s %s", &a, &b, &k);
        readln;

        auto diff = a - b;
        auto ans = cast(long)diff * (k/2);

        if (k % 2 == 1) ans += a;

        ans.writeln;
    }
}

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		long a=0;
		long b=0;
		long c=0;
		readf(" %d", &a);
		readf(" %d", &b);
		readf(" %d", &c);
		long d=c/2;
		writeln(a*(c-d)-b*d);
	}
	return 0;
}


Ran is especially skilled in computation and mathematics. It is said that she can do unimaginable calculation work in an instant.—Perfect Memento in Strict SenseRan Yakumo is a cute girl who loves creating cute Maths problems.Let $$$f(x)$$$ be the minimal square number strictly greater than $$$x$$$, and $$$g(x)$$$ be the maximal square number less than or equal to $$$x$$$. For example, $$$f(1)=f(2)=g(4)=g(8)=4$$$.A positive integer $$$x$$$ is cute if $$$x-g(x)<f(x)-x$$$. For example, $$$1,5,11$$$ are cute integers, while $$$3,8,15$$$ are not. Ran gives you an array $$$a$$$ of length $$$n$$$. She wants you to find the smallest non-negative integer $$$k$$$ such that $$$a_i + k$$$ is a cute number for any element of $$$a$$$.

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$) — the length of $$$a$$$. The second line contains $$$n$$$ intergers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \leq a_1 \leq a_2 \leq \ldots \leq a_n \leq 2\cdot 10^6$$$) — the array $$$a$$$.

Print a single interger $$$k$$$ — the answer.

NoteTest case 1:$$$3$$$ is not cute integer, so $$$k\ne 0$$$.$$$2,4,9,11$$$ are cute integers, so $$$k=1$$$.

import std;

void main () {
	auto n = readln.strip.to !(int);
	auto a = readln.splitter.map !(to !(long)).array;
	rndGen.seed (123);
	long first = a.front;
	a.popFront ();
	randomShuffle (a);
	for (long u = 1; ; u++) {
		auto lo = max (u ^^ 2 - first, 0);
		auto hi = u ^^ 2 + u - first;
		foreach (i, ref c; a) {
			auto d = c + lo;
			auto v = cast (long) (sqrt (cast (double) (d)));
			if (d > v ^^ 2 + v) lo += (v + 1) ^^ 2 - d;
			else hi = min (hi, lo + v ^^ 2 + v - d);
			if (lo > hi) {
				a.swapAt (i, uniform (0, i + 1));
				break;
			}
		}
		if (lo <= hi) {
			writeln (lo);
			break;
		}
	}
}

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

immutable long limit = 2 * 10 ^^ 6 + 5;

void main ()
{

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto used = new bool [limit];
		auto a = readln.splitter.map !(to !(long)).array;

		rndGen.seed (263_473_470);
		long sel = a.front;
		long cur = sel;
		a.popFront ();
		randomShuffle (a);
		while (true)
		{
			long base = cast (long) (sqrt (cur * 1.0));
			long lo = cast (long) (cur - base * 1L * base);
			long hi = base;
			long delta = cur - sel;
			foreach (i, ref c; a)
			{
				long d = c + delta;
				long v = cast (long) (sqrt (d * 1.0));
				long w = v * 1L * v;
				if (d > w + v)
				{
					long e = w + v * 2 + 1;
					long add = cast (long) (e - d);
					cur += add;
					delta += add;
					lo += add;
				}
				else
				{
					hi = min (hi,
					    lo + cast (long) (w + v - d));
				}
				if (lo > hi)
				{
					a.swapAt (i, uniform (0, i + 1));
					break;
				}
			}
			if (lo <= hi)
			{
				break;
			}
			cur = (base + 1L) ^^ 2;
		}
		writeln (cur - sel);
	}
}

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

immutable long limit = 2 * 10 ^^ 6 + 5;

void main ()
{

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto used = new bool [limit];
		auto a = readln.splitter.map !(to !(long)).array;

		rndGen.seed (263_473_470);
		long sel = a.front;
		long cur = sel;
		a.popFront ();
		randomShuffle (a);
		while (true)
		{
			long base = cast (long) (sqrt (cur * 1.0));
			long lo = cast (long) (cur - base * 1L * base);
			long hi = base;
			long delta = cur - sel;
			foreach (i, ref c; a)
			{
				long d = c + delta;
				long v = cast (long) (sqrt (d * 1.0));
				long w = v * 1L * v;
				if (d > w + v)
				{
					long e = w + v * 2 + 1;
					long add = cast (long) (e - d);
					cur += add;
					delta += add;
					lo += add;
				}
				else
				{
					hi = min (hi,
					    lo + cast (long) (w + v - d));
				}
				if (lo > hi)
				{
					swap (a[0], a[i]);
					break;
				}
			}
			if (lo <= hi)
			{
				break;
			}
			cur = (base + 1L) ^^ 2;
		}
		writeln (cur - sel);
	}
}

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

immutable long limit = 2 * 10 ^^ 6 + 5;

void main ()
{

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto used = new bool [limit];
		auto a = readln.splitter.map !(to !(long)).array;

		rndGen.seed (263_473_470);
		long sel = a.front;
		long cur = sel;
		a.popFront ();
		randomShuffle (a);
		while (true)
		{
			long base = cast (long) (sqrt (cur * 1.0));
			long lo = cast (long) (cur - base * 1L * base);
			long hi = base;
			long delta = cur - sel;
			foreach (ref c; a)
			{
				long d = c + delta;
				long v = cast (long) (sqrt (d * 1.0));
				long w = v * 1L * v;
				if (d > w + v)
				{
					long e = w + v * 2 + 1;
					long add = cast (long) (e - d);
					cur += add;
					delta += add;
					lo += add;
				}
				else
				{
					hi = min (hi, cast (long) (w + v - d));
				}
				if (lo > hi)
				{
					break;
				}
			}
			if (lo <= hi)
			{
				break;
			}
			cur = (base + 1L) ^^ 2;
		}
		writeln (cur - sel);
	}
}

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

immutable int limit = 2 * 10 ^^ 6 + 5;

void main ()
{

	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto used = new bool [limit];
		auto a = readln.splitter.map !(to !(int)).array;

		rndGen.seed (263_473_470);
		long sel = a.front;
		long cur = sel;
		a.popFront ();
		randomShuffle (a);
		while (true)
		{
			int base = cast (int) (sqrt (cur * 1.0));
			int lo = cast (int) (cur - base * 1L * base);
			int hi = base;
			long delta = cur - sel;
			debug {writefln !("considering %s [%s..%s]")
			    (cur, lo, hi);}
			foreach (ref c; a)
			{
				long d = c + delta;
				int v = cast (int) (sqrt (d * 1.0));
				long w = v * 1L * v;
				debug {writefln
				    !("lo = %s, %s -> %s in [%s..%s]")
				    (lo, c, d, w, w + v);}
				if (d > w + v)
				{
					long e = w + v * 2 + 1;
					int add = cast (int) (e - d);
					debug {writeln ("add ", add);}
					cur += add;
					debug {writeln ("cur = ", cur);}
					delta += add;
					lo += add;
				}
				else
				{
					hi = min (hi, cast (int) (w + v - d));
				}
				if (lo > hi)
				{
					break;
				}
			}
			if (lo <= hi)
			{
				break;
			}
			cur = (base + 1L) ^^ 2;
			debug {writeln ("cur = ", cur);}
		}
		writeln (cur - sel);
	}
}


A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".

The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.

Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".

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

void main()
{
  int n;
  long r;
  auto k = readln().chomp().to!int();
  auto str = readln().chomp();
  auto dp = new long[str.length + 1];
  dp[0] = 1;

  foreach (s; str) {
    if (s == '1') n++;
    if (n >= k) r += dp[n - k];
    dp[n]++;
  }

  writeln(r);
}

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

void main()
{
  int n, r;
  auto k = readln().chomp().to!int();
  auto str = readln().chomp();
  auto dp = new long[str.length];

  foreach (s; str) {
    if (s == '1') n++;
    if (n >= k) r += dp[n - k];
    dp[n]++;
  }

  writeln(r);
}

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

void main()
{
  int n, r;
  auto k = readln().chomp().to!int();
  auto str = readln().chomp();
  auto dp = new long[str.length];
  dp[0] = 1;

  foreach (s; str) {
    if (s == '1') n++;
    if (n >= k) r += dp[n - k];
    dp[n]++;
  }

  writeln(r);
}


The GCD table G of size n × n for an array of positive integers a of length n is defined by formula   Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows:  Given all the numbers of the GCD table G, restore array a.

The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a.  All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.

In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.

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

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

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

    int [int] cnt;

    arr.each!(x => ++cnt[x]);

    int[] ans;
    foreach (i; 0 .. n) {
        auto cur = cnt.keys.maxElement();
        ans ~= cur;
        cnt[cur] -= 1;
        if (cnt[cur] == 0) cnt.remove(cur);

        foreach (j; 0 .. i) {
            auto now = gcd(ans[i], ans[j]);
            cnt[now] -= 2;
            if (cnt[now] == 0) cnt.remove(now);
        }
    }

    ans.sort();
    //debug { ans.writeln; }
    ans.writefln!("%(%s %)");
}

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

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto a = readln.split.map !(to !(int)).array;
		sort (a);
		int [] r;
		foreach (i; 0..n)
		{
			auto cur = a.minPos !(q{a > b}).front;
			int [] b = [cur];
			foreach (p; r)
			{
				b ~= gcd (p, cur);
			}
			b ~= b;
			b ~= int.max;
			sort (b);
			for (int j = 0, p = 0; j < a.length; j++)
			{
				if (b.front == a[j])
				{
					b.popFront ();
				}
				else
				{
					a[p] = a[j];
					p++;
				}
			}
			a.length -= r.length * 2 + 1;
			r ~= cur;
		}
		writefln ("%(%s %)", r);
	}
}

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

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

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

    int [int] cnt;

    arr.each!(x => ++cnt[x]);

    int[] ans;
    foreach (i; 0 .. n) {
        auto cur = cnt.keys.maxElement();
        ans ~= cur;
        cnt[cur] -= 1;
        if (cnt[cur] == 0) cnt.remove(cur);

        foreach (j; 0 .. i) {
            auto now = gcd(ans[i], ans[j]);
            cnt[now] -= 2;
            if (cnt[now] == 0) cnt.remove(cur);
        }
    }

    ans.sort();
    //debug { ans.writeln; }
    ans.writefln!("%(%s %)");
}

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

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

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

    int [int] cnt;

    arr.each!(x => ++cnt[x]);

    int[] ans;
    foreach (i; 0 .. n) {
        auto cur = cnt.keys.maxElement();
        ans ~= cur;
        cnt[cur] -= 1;
        if (cnt[cur] == 0) cnt.remove(cur);

        foreach (j; 0 .. i) {
            auto now = gcd(ans[i], ans[j]);
            cnt[now] -= 2;
            if (cnt[now] == 0) cnt.remove(cur);
        }
    }

    //debug { ans.writeln; }
    ans.writefln!("%(%s %)");
}


You are given an array $$$a$$$ of $$$n$$$ positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that $$$a_1 < a_2 < \dots < a_n$$$ holds.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array.

For each test case, output "YES" (without quotes) if the array satisfies the condition, and "NO" (without quotes) otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case any rearrangement will keep the array $$$[1,1,1,1]$$$, which is not strictly increasing.In the second test case, you can make the array $$$[1,3,4,7,8]$$$.

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n;
        scanf("%d\n", &n);
        auto arr = readln.split.to!(long[]);
        if (arr.length == 1)
            writeln("YES");
        else {
            if (arr.length == uniq(arr.sort).array.length)
                writeln("YES");
            else
                writeln("NO");
        }
    }
}

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) {
    long n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!long).array.sort.array;
    long prev = 0;
    bool good = true;
    foreach (x ; a) {
      if (x == prev) {
        good = false;
        break;
      }
      prev = x;
    }
    writeln(good ? "YES" : "NO");
  }
}

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

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

void solve() {
    int N = read!int;
    auto A = readarray!int;
    sort(A);
    bool f() {
        for (int i = 0; i + 1 < N; i++) {
            if (A[i] == A[i + 1]) return false;
        }
        return true;
    }
    writeln(f() ? "YES" : "NO");
}

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

import std;

void main()
{
    int t;
    scanf("%d\n", &t);
    foreach(_; 0..t) {
        int n;
        scanf("%d\n", &n);
        auto arr = readln.split.to!(long[]);
        if (arr.length == 1)
            writeln("YES");
        else {
            if (arr.length == uniq(arr).array.length)
                writeln("YES");
            else
                writeln("NO");
        }
    }
}


BerOilGasDiamondBank has branches in n cities, at that n is an even number. The bank management wants to publish a calendar with the names of all those cities written in two columns: the calendar should consist of exactly n / 2 lines of strictly equal length, each of which contains exactly two names and exactly one separator character between them. The name of every city should be used in the calendar exactly once. For historical reasons the symbol d is used as the separator of words in the calendar. The BerOilGasDiamondBank management wants to show that all its branches are equally important to it, that's why the order of their appearance in the calendar should be following: if we "glue"(concatinate) all the n / 2 calendar lines (from top to bottom) to make a single line, then the lexicographically minimal line is obtained. No separator character will be used to separate calendar lines. For example, if the lines are "bertown!berville", "newberville!bera", then the resulting line is "bertown!bervillenewberville!bera". In some sense one has to find the lexicographically minimal calendar, where the comparison of calendars happens line by line.Help BerOilGasDiamondBank and construct the required calendar.

The first line contains an integer n (1 ≤ n ≤ 104, n is even) which is the number of branches. Then follow n lines which are the names of the cities. All the names consist of lowercase Latin letters; their lengths are no less than 1 and no more than 10 symbols. The next line contains a single symbol d (d has an ASCII-code from 33 to 126 inclusively, excluding lowercase Latin letters) which is the separator between words in the calendar lines. It is guaranteed that the calendar is possible to be constructed and all the names are different.

Print n / 2 lines of similar length which are the required calendar. Every line should contain exactly two words and exactly one separator between them. If there are several solutions, print the lexicographically minimal one. The lexicographical comparison of lines is realized by the "<" operator in the modern programming languages.

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.variant,
	std.stdio,std.bitmanip;
import core.stdc.stdio : freopen;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias boyerMooreFinder strfind;
alias make_pair mp;
alias binary_search bins;
alias pair(X,Y)=Tuple!(X,q{fi},Y,q{se});
pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_)
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
immutable int mod=10^^9+7;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b)
	{
		return a/gcd(a,b)*b;
	}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(g<a[m])r=m;
			else l=m;
		}
		return (g<a[l])?l:r;
	}
	size_t binf(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (g==a[l])?l:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n,in size_t m) if(isRandomAccessRange!X)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n) if(hasSlicing!X)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~'\n', ptrs)==ptrs.length;}
nothrow void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter countUntil
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	//debug writeln('}'>'z');
	int n;
	loop:while(read(&n))
	{
		auto ar=new string[n];
		int l;
		foreach(i;0..n){ar[i]=readln.strip;l+=ar[i].length;}
		l/=(n/2);
		char d;
		read(&d);
		if(d>'z')
		{
			bool cmp(string a,string b)
			{
				if(a.length<=b.length)
				{
					if(a==b[0..a.length])return false;
					else return a<b;
				}
				else
				{
					if(b==a[0..b.length])return true;
					else return a<b;
				}
			}
			sort!cmp(ar);
		}
		else sort(ar);
		string[][int] q;

		bool[string] u;

		foreach(i;ar)
		{

			q[i.length]~=i;
		}
		auto p=new int[30];
		foreach(i;ar)
		{
			if(i !in u)
			{
				debug writeln(l-i.length);
				debug writeln(i);
				u[i]=true;
				p[i.length]++;
				writeln(i,d,q[l-i.length][p[l-i.length]]);
				u[q[l-i.length][p[l-i.length]]]=true;
				p[l-i.length]++;

			}
		}
	}
}

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.variant,
	std.stdio,std.bitmanip;
import core.stdc.stdio : freopen;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias boyerMooreFinder strfind;
alias make_pair mp;
alias binary_search bins;
alias pair(X,Y)=Tuple!(X,q{fi},Y,q{se});
pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_)
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
immutable int mod=10^^9+7;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b)
	{
		return a/gcd(a,b)*b;
	}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(g<a[m])r=m;
			else l=m;
		}
		return (g<a[l])?l:r;
	}
	size_t binf(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (g==a[l])?l:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n,in size_t m) if(isRandomAccessRange!X)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n) if(hasSlicing!X)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~'\n', ptrs)==ptrs.length;}
nothrow void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter countUntil
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n;
	loop:while(read(&n))
	{
		auto ar=new string[n];
		int l;
		foreach(i;0..n){ar[i]=readln.strip;l+=ar[i].length;}
		l/=n/2;
		debug writeln(l);
		char d;
		read(&d);
		if(d>'z')
		{
			bool cmp(string a,string b)
			{
				if(a.length<=b.length)
				{
					if(a==b[0..a.length])return false;
					else return a<b;
				}
				else
				{
					if(b==a[0..a.length])return true;
					else return a<b;
				}
			}
			sort!cmp(ar);
		}
		else sort(ar);
		string[][int] q;

		bool[string] u;

		foreach(i;ar)
		{

			q[i.length]~=i;
		}
		auto p=new int[30];
		foreach(i;ar)
		{
			if(i !in u)
			{
				debug writeln("ok");
				u[i]=true;
				writeln(i,d,q[l-i.length][p[l-i.length]]);
				u[q[l-i.length][p[l-i.length]++]]=true;
				p[i.length]++;
			}
		}
	}
}

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.variant,
	std.stdio,std.bitmanip;
import core.stdc.stdio : freopen;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias boyerMooreFinder strfind;
alias make_pair mp;
alias binary_search bins;
alias pair(X,Y)=Tuple!(X,q{fi},Y,q{se});
pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_)
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
immutable int mod=10^^9+7;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b)
	{
		return a/gcd(a,b)*b;
	}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(g<a[m])r=m;
			else l=m;
		}
		return (g<a[l])?l:r;
	}
	size_t binf(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (g==a[l])?l:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g)
		if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n,in size_t m) if(isRandomAccessRange!X)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n) if(hasSlicing!X)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~'\n', ptrs)==ptrs.length;}
nothrow void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter countUntil
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n;
	loop:while(read(&n))
	{
		auto ar=new string[n];
		foreach(i;0..n)ar[i]=readln.strip;
		char d;
		read(&d);
		if(d>'z')
		{
			bool cmp(string a,string b)
			{
				if(a.length<=b.length)
				{
					if(a==b[0..a.length])return false;
					else return a<b;
				}
				else
				{
					if(b==a[0..a.length])return true;
					else return a<b;
				}
			}
			sort!cmp(ar);
		}
		else sort(ar);
		for(int i=0;i<n;i+=2)
		{
			writeln(ar[i],d,ar[i+1]);
		}

	}
}


A class of students wrote a multiple-choice test.There are $$$n$$$ students in the class. The test had $$$m$$$ questions, each of them had $$$5$$$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $$$i$$$ worth $$$a_i$$$ points. Incorrect answers are graded with zero points.The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of students in the class and the number of questions in the test. Each of the next $$$n$$$ lines contains string $$$s_i$$$ ($$$|s_i| = m$$$), describing an answer of the $$$i$$$-th student. The $$$j$$$-th character represents the student answer (A, B, C, D or E) on the $$$j$$$-th question. The last line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \le a_i \le 1000$$$) — the number of points for the correct answer for every question.

Print a single integer — the maximum possible total score of the class.

NoteIn the first example, one of the most optimal test answers is "ABCD", this way the total number of points will be $$$16$$$.In the second example, one of the most optimal test answers is "CCC", this way each question will be answered by exactly one student and the total number of points is $$$5 + 4 + 12 = 21$$$.

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

void main() {
  int n,m;
  readln.strip.formattedRead(" %s %s", n, m);

  string[] ans;

  foreach (i; 0 .. n) {
    ans ~= readln.strip;
  }

  int[] maxAns;
  foreach (i; 0 .. m) {
    int[26] cnt = 0;
    foreach (j; 0 .. n) {
      cnt[ans[j][i]-'A']++;
    }
    maxAns ~= cnt[].maxElement;
  }

  auto point = readln.split.map!(a => parse!int(a));

  int sum = 0;
  foreach (i; 0 .. m) {
    sum += maxAns[i] * point[i];
  }

  writeln(sum);
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto S = N.iota.map!(_ => readln.chomp).array;
    auto A = readln.split.map!(to!long).array;
    auto cnt = new long[](5);
    long ans = 0;

    foreach (i; 0..M) {
        cnt[] = 0;
        foreach (j; 0..N) cnt[S[j][i]-'A'] += 1;
        ans += cnt.reduce!max * A[i];
    }

    ans.writeln;
}

import std.algorithm.searching : maxElement;
import std.range : generate, takeExactly;
import std.stdio : readf, readln, writeln;
import std.string : strip;

void main()
{
  int n, m; // number of students, number of questions
  readf!"%d %d\n"(n, m);
  auto s = new string[n];
  foreach (i; 0..n) s[i] = readln.strip;

  auto total = 0;

  // read points for each question
  foreach (i; 0..m) {
    int a;
    char c;
    readf!"%d%c"(a, c);

    auto counts = new int[26];

    foreach (j; 0..n) {
      counts[s[j][i] - 'A']++;
    }

    total += counts.maxElement * a;
  }

  writeln(total);
}


In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:  overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.

The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.

Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto F = new int[][M];
    foreach (i; 0 .. M) {
        auto s = readln.chomp.split(" ").map!(to!int).array;
        foreach (ref e; s) e--;
        F[i] = s;
    }

    auto X = new int[N];
    foreach (i; 0 .. M) {
        auto used = new bool[4];
        foreach (j; 0 .. 3) {
            int p = F[i][j];
            if (X[p] != 0) {
                used[ X[p] ] = true;
            }
        }
        foreach (j; 0 .. 3) {
            int p = F[i][j];
            if (X[p] != 0) continue;
            foreach (int k; 1 .. 4) {
                if (!used[k]) {
                    X[p] = k;
                    used[k] = true;
                    break;
                }
            }
        }
    }
    writefln("%(%s %)", X);
}

#!/usr/bin/env rdmd
import std.stdio, std.string, std.conv;
import std.algorithm, std.array;

void main()
{
    for(string S; (S=readln().chomp()).length; )
    {
        auto nm = S.split().map!(to!int)();
        auto n = nm[0], m = nm[1];
        auto d = new int[3][m];
        foreach(ref a;d)
            a[] = array(readln().split().map!(to!int)().map!("a-1")());
        auto c = new int[n];
        foreach(ref a;d)
        {
            auto o = 0;
            foreach(i;0..3)
                if(c[a[i]]!=0)
                    o=c[a[i]]+2-i;
            foreach(i;0..3)
                c[a[i]]=(i+o)%3+1;
        }
        writeln(c.map!(to!string)().join(" "));
    }
}


Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves:  Value x and some direction are announced, and all boys move x positions in the corresponding direction.  Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy.

The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while  - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type.

Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves.

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

immutable int INF = 10 ^^ 9 + 23;

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

    long[2] mv;
    foreach (_; 0 .. q) {
        int t, x;
        readf("%s", &t);
        if (t == 1) { readf(" %s", &x); }
        readln;

        if (t == 1) {
            mv[0] += x;
            mv[1] += x;
        } else {
            if (mv[0] % 2 == 0) { mv[0] -= 1; }
            else { mv[0] += 1; }

            if (mv[1] % 2 == 0) { mv[1] += 1; }
            else { mv[1] -= 1; }
        }
    }

    foreach (ref e; mv) { e = ((e % n) + n) % n; }

    auto ans = new int[] (n);
    foreach (i; 1 .. n+1) {
        auto cmv = mv[i.to!int % 2];
        int npos = (i.to!int - 1 + cmv) % n;
        ans[npos] = i;
    }

    ans.writefln!"%(%s %)";
}


Let's denote correct match equation (we will denote it as CME) an equation $$$a + b = c$$$ there all integers $$$a$$$, $$$b$$$ and $$$c$$$ are greater than zero.For example, equations $$$2 + 2 = 4$$$ (||+||=||||) and $$$1 + 2 = 3$$$ (|+||=|||) are CME but equations $$$1 + 2 = 4$$$ (|+||=||||), $$$2 + 2 = 3$$$ (||+||=|||), and $$$0 + 1 = 1$$$ (+|=|) are not.Now, you have $$$n$$$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if $$$n = 2$$$, you can buy two matches and assemble |+|=||, and if $$$n = 5$$$ you can buy one match and assemble ||+|=|||.   Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. The only line of each query contains one integer $$$n$$$ ($$$2 \le n \le 10^9$$$) — the number of matches.

For each test case print one integer in single line — the minimum number of matches which you have to buy for assembling CME.

NoteThe first and second queries are explained in the statement.In the third query, you can assemble $$$1 + 3 = 4$$$ (|+|||=||||) without buying matches.In the fourth query, buy one match and assemble $$$2 + 4 = 6$$$ (||+||||=||||||).

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (i; 0..q)
	{
		auto n = RD!int;
		if (n == 2)
		{
			ans[i] = 2;
		}
		else
			ans[i] = n % 2 == 0 ? 0 : 1;
	}

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

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		readf(" %d", &a);
		if (a<4)
		{
			writeln(4-a);
		}
		else
		{
			if (a%2==0)
			{
				writeln(0);
			}
			else
			{
				writeln(1);
			}
		}
	}
	return 0;
}


You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.You must paint a fence which consists of $$$10^{100}$$$ planks in two colors in the following way (suppose planks are numbered from left to right from $$$0$$$):   if the index of the plank is divisible by $$$r$$$ (such planks have indices $$$0$$$, $$$r$$$, $$$2r$$$ and so on) then you must paint it red;  if the index of the plank is divisible by $$$b$$$ (such planks have indices $$$0$$$, $$$b$$$, $$$2b$$$ and so on) then you must paint it blue;  if the index is divisible both by $$$r$$$ and $$$b$$$ you can choose the color to paint the plank;  otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it). Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all painted planks of the fence in ascending order: if there are $$$k$$$ consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. The next $$$T$$$ lines contain descriptions of test cases — one per line. Each test case contains three integers $$$r$$$, $$$b$$$, $$$k$$$ ($$$1 \le r, b \le 10^9$$$, $$$2 \le k \le 10^9$$$) — the corresponding coefficients.

Print $$$T$$$ words — one per line. For each test case print REBEL (case insensitive) if the execution is unavoidable or OBEY (case insensitive) otherwise.

import std.stdio;

void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]))
      foreach(ref e; args[i])
	read(e);
    else
      readf!" %s"(args[i]);
}
alias r = read;
alias w = writeln;

int main()
{
  int t;
  r(t);
  foreach(tc; 0 .. t)
    {
      long red, b, k;
      r(red, b, k);
      import std.numeric: gcd;
      long g = gcd(red, b);
      red /= g;
      b /= g;
      if (red * (k - 1) < (b - 1) || b * (k - 1) < (red - 1))
	{
	  w("REBEL");
	}
      else
	{
	  w("OBEY");
	}
    }
  return 0;
}

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.ascii, std.typecons;

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

    while (t--) {
        int r, b, k;
        readf("%s %s %s", &r, &b, &k);
        readln;

        if (r > b) { swap(r, b); }

        auto g = gcd(r, b);

        r /= g;
        b /= g;

        auto m = (b-1+r-1) / r;

        debug { writeln(m, ' ', g); }

        writeln(m < k ? "OBEY" : "REBEL");
    }
}

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

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

void solve(){
	int t = rint;
	foreach(_; 0 .. t){
		string ans = "OBEY";
		long r = rlong, b = rlong, k = rlong;
		long g = gcd(r, b);
		r /= g, b /= g;
		if(r > b && (r - 2) / b + 1 >= k) ans = "REBEL";
		if(b > r && (b - 2) / r + 1 >= k) ans = "REBEL";
		ans.writeln;
	}

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

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.ascii, std.typecons;

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

    while (t--) {
        int r, b, k;
        readf("%s %s %s", &r, &b, &k);
        readln;

        if (r > b) { swap(r, b); }

        auto g = gcd(r, b);

        auto m = b / r;

        if (g == r && r != b) { --m; }

        debug { writeln(m, ' ', g); }

        writeln(m < k ? "OBEY" : "REBEL");
    }
}

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.ascii, std.typecons;

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

    while (t--) {
        int r, b, k;
        readf("%s %s %s", &r, &b, &k);
        readln;

        if (r > b) { swap(r, b); }

        auto g = gcd(r, b);

        auto m = b / r;

        debug { writeln(m, ' ', g); }

        writeln(m < k ? "OBEY" : "REBEL");
    }
}

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

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

void solve(){
	int t = rint;
	foreach(_; 0 .. t){
		string ans = "OBAY";
		long r = rlong, b = rlong, k = rlong;
		long g = gcd(r, b);
		r /= g, b /= g;
		if(r > b && (r - 2) / b + 1 >= k) ans = "REBEL";
		if(b > r && (b - 2) / r + 1 >= k) ans = "REBEL";
		ans.writeln;
	}

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


There are $$$n$$$ boxes with different quantities of candies in each of them. The $$$i$$$-th box has $$$a_i$$$ candies inside.You also have $$$n$$$ friends that you want to give the candies to, so you decided to give each friend a box of candies. But, you don't want any friends to get upset so you decided to eat some (possibly none) candies from each box so that all boxes have the same quantity of candies in them. Note that you may eat a different number of candies from different boxes and you cannot add candies to any of the boxes.What's the minimum total number of candies you have to eat to satisfy the requirements?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the number of boxes you have. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the quantity of candies in each box.

For each test case, print a single integer denoting the minimum number of candies you have to eat to satisfy the requirements.

NoteFor the first test case, you can eat $$$1$$$ candy from the second box, $$$2$$$ candies from the third box, $$$3$$$ candies from the fourth box and $$$4$$$ candies from the fifth box. Now the boxes have $$$[1, 1, 1, 1, 1]$$$ candies in them and you ate $$$0 + 1 + 2 + 3 + 4 = 10$$$ candies in total so the answer is $$$10$$$.For the second test case, the best answer is obtained by making all boxes contain $$$5$$$ candies in them, thus eating $$$995 + 995 + 0 + 995 + 995 + 995 = 4975$$$ candies in total.

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

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

void main() {
    int t, n, m;
    readf("%d\n", t);
    while(t--) {
		readln;
		int sum;
        auto b = rtln!int;
		int min = b.minElement;
		foreach (x; b)
				sum += (x - min);
		writeln(sum);
    }
}

void main() { runSolver(); }

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

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

      auto mi = A.minElement;
      return A.sum - mi*N;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		writeln (a.sum - a.minElement * n);
	}
}


The only difference between the easy and the hard versions is the maximum value of $$$k$$$.You are given an infinite sequence of form "112123123412345$$$\dots$$$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $$$1$$$ to $$$1$$$, the second one — from $$$1$$$ to $$$2$$$, the third one — from $$$1$$$ to $$$3$$$, $$$\dots$$$, the $$$i$$$-th block consists of all numbers from $$$1$$$ to $$$i$$$. So the first $$$56$$$ elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the $$$1$$$-st element of the sequence is $$$1$$$, the $$$3$$$-rd element of the sequence is $$$2$$$, the $$$20$$$-th element of the sequence is $$$5$$$, the $$$38$$$-th element is $$$2$$$, the $$$56$$$-th element of the sequence is $$$0$$$.Your task is to answer $$$q$$$ independent queries. In the $$$i$$$-th query you are given one integer $$$k_i$$$. Calculate the digit at the position $$$k_i$$$ of the sequence.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. The $$$i$$$-th of the following $$$q$$$ lines contains one integer $$$k_i$$$ $$$(1 \le k_i \le 10^9)$$$ — the description of the corresponding query.

Print $$$q$$$ lines. In the $$$i$$$-th line print one digit $$$x_i$$$ $$$(0 \le x_i \le 9)$$$ — the answer to the query $$$i$$$, i.e. $$$x_i$$$ should be equal to the element at the position $$$k_i$$$ of the sequence.

NoteAnswers on queries from the first example are described in the problem statement.

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 q;
    readf("%s", &q);
    readln;

    immutable int MXK = 10 ^^ 9;
    immutable int MX = 10 ^^ 5;

    auto sz = new long[] (MX);
    sz[0] = 0;
    foreach (i; 1 .. MX) {
        sz[i] = sz[i-1] + i.to!string.length.to!int;
    }

    debug { sz.take(20).writeln; }

    while (q--) {
        int x;
        readf("%s", &x);
        readln;

        auto idx = 0;
        while (x > sz[idx]) {
            x -= sz[idx];
            ++idx;
        }

        debug { writeln("x : ", x); }

        int start = 1;
        int m = 9;
        while (start.to!string.length.to!long * m < x) {
            x -= start.to!string.length * m;
            start *= 10;
            m *= 10;
        }

        debug { writeln(x, ' ', start); }

        int v = start;
        while (v.to!string.length < x) {
            x -= v.to!string.length;
            ++v;
        }

        auto str = v.to!string;

        debug { str.writeln; }

        str[x-1].writeln;
    }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Indices of the array start from zero (i. e. the first element is $$$a_0$$$, the second one is $$$a_1$$$, and so on).You can reverse at most one subarray (continuous subsegment) of this array. Recall that the subarray of $$$a$$$ with borders $$$l$$$ and $$$r$$$ is $$$a[l; r] = a_l, a_{l + 1}, \dots, a_{r}$$$.Your task is to reverse such a subarray that the sum of elements on even positions of the resulting array is maximized (i. e. the sum of elements $$$a_0, a_2, \dots, a_{2k}$$$ for integer $$$k = \lfloor\frac{n-1}{2}\rfloor$$$ should be maximum possible).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_0, a_1, \dots, a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer on the separate line — the maximum possible sum of elements on even positions after reversing at most one subarray (continuous subsegment) of $$$a$$$.

import std.stdio;
import std.container;
import std.range;
import std.algorithm;

long calculate_max_sum(long[] arr) {
	long current = 0;
	long best_res = 0;
	int left = 0;

	for (int i = 0; i < arr.length; i++) {
		current += arr[i];
		while (left <= i && arr[left] < 0) {
			current -= arr[left];
			left++;
		}

		if (current < 0) {
			current = 0;
			left = i + 1;
		}

		best_res = max(best_res, current);
	}

	return best_res;
}

void main() {
	int t;
	scanf("%d", &t);

	while (t--) {
		int n;
		scanf("%d", &n);

		long[] arr = new long[n];
		foreach (i; iota(n)) scanf("%lld", &arr[i]);

		// calculate the sum for even elems
		long sum = 0;
		foreach (i, e; arr) sum += ((i + 1) % 2) * e;

		// sum-diff-array starting at first element
		long[] a = new long[n / 2];
		for (int i = 0; i + 1 < n; i += 2) {
			a[i / 2] = arr[i + 1] - arr[i];
		}

		// starting at second
		int n_odd = (n - 1) / 2;
		long[] b = new long[n_odd];
		for (int i = 1; i + 1 < n; i += 2) {
			b[i / 2] = arr[i] - arr[i + 1];
		}

		writeln(sum + max(calculate_max_sum(a), calculate_max_sum(b)));
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		long [] [] s = [[0], [0], [0]];
		foreach (i, c; a)
		{
			s[0] ~= s[0][$ - 1] + !(i & 1) * c;
			s[1] ~= s[1][$ - 1] + (i & 1) * c;
			s[2] ~= s[1][$ - 1] - s[0][$ - 1];
		}
		long res = 0;
		long [2] lo = [long.max / 2, 0];
		foreach (i; 0..n)
		{
			lo[i & 1] = min (lo[i & 1], s[2][i + 1]);
			res = max (res, s[2][i + 1] - lo[i & 1]);
		}
		writeln (res + s[0].back);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto b = new long[](n+1);
		foreach (i; 0..n)
		{
			if (i % 2)
			{
				b[i+1] = b[i] - a[i];
			}
			else
			{
				b[i+1] = b[i] + a[i];
			}
		}

		auto c0 = new long[](n+1);
		auto c1 = new long[](n+1);
		c0[] = long.max;
		c1[] = long.max;
		long tot;
		foreach_reverse (i; 0..n)
		{
			if (i % 2)
			{
				c1[i] = min(c1[i+1], b[i+1]);
				c0[i] = c0[i+1];
			}
			else
			{
				c0[i] = min(c0[i+1], b[i+1]);
				c1[i] = c1[i+1];
				tot += a[i];
			}
		}
		debug writeln(b);
		debug writeln(c0);
		debug writeln(c1);

		ans[ti] = tot;
		foreach (i; 0..n-1)
		{
			long x;
			if (i % 2)
			{
				x = -(c0[i+1] - b[i]);
				debug writeln("i:", i, " ", c0[i+1], " ", b[i]);
			}
			else
			{
				x = -(c1[i+1] - b[i]);
				debug writeln("i:", i, " ", c1[i+1], " ", b[i]);
			}

			ans[ti].chmax(tot+x);
			debug writeln("i:", i, " ", ans[ti]);
		}
	}

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


Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n.Bob gave you all the values of ai, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.

The first line of the input will contain a single integer n (2 ≤ n ≤ 50). The next n lines will contain the values of ai, j. The j-th number on the i-th line will represent ai, j. The i-th number on the i-th line will be 0. It's guaranteed that ai, j = aj, i and there is at least one solution consistent with the information given.

Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them.

NoteIn the first case, the answer can be {1, 2} or {2, 1}.In the second case, another possible answer is {2, 4, 5, 1, 3}.

import std.algorithm;
import std.array;
import std.conv;
import std.numeric;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		int [] [] a;
		foreach (i; 0..n)
		{
			a ~= readln.split.map !(to !(int)).array;
		}

		auto p = new int [n];
main_loop:
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				foreach (k; j + 1..n)
				{
					if (a[i][j] == a[i][k])
					{
						p[i] = a[i][j];
						continue main_loop;
					}
				}
			}
		}

		int v = n - 1;
		foreach (i; 0..n)
		{
			if (p[i] == 0)
			{
				p[i] = v;
				v++;
			}
		}

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

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

void main() {
    int n = readln.chomp.to!int;
    int[][] t;
    for (int i = 0; i < n; i++) {
        t ~= readln.chomp.split.map!(to!int).array;
    }

    int[] ans;
    foreach (e; t) {
        ans ~= e.minPos!("a > b")[0];
    }

    ans[ans.length - ans.minPos!("a > b").length] = ans.length.to!int;

    writeln(ans.map!(to!string).join(" "));
}

import std.stdio;
int n,i,j,k;
int[50][50] v;
int[50] ans;
void main()
{
	scanf(" %d",&n);
	for(i=0;i<n;++i)
	{
		for(j=0;j<n;++j)
		{
			scanf(" %d",&v[i][j]);
		}
	}
	for(k=1;k<=n;++k)
	{
		int cnt;
		for(i=0;i<n;++i)
		{
			if(ans[i]) continue;
			cnt=0;
			for(j=0;j<n;++j) if(v[i][j]==k) ++cnt;
			if(cnt==n-1) break;
		}
		ans[i]=k;
		for(i=0;i<n;++i) for(j=0;j<n;++j) if(v[i][j]==k) v[i][j]=k+1;
	}
	for(i=0;i<n;++i) writef("%d ",ans[i]);
	writeln();
}


Iahubina is tired of so many complicated languages, so she decided to invent a new, simple language. She already made a dictionary consisting of n 3-words. A 3-word is a sequence of exactly 3 lowercase letters of the first 24 letters of the English alphabet (a to x). She decided that some of the letters are vowels, and all the others are consonants. The whole language is based on a simple rule: any word that contains at least one vowel is correct.Iahubina forgot which letters are the vowels, and wants to find some possible correct sets of vowels. She asks Iahub questions. In each question, she will give Iahub a set of letters considered vowels (in this question). For each question she wants to know how many words of the dictionary are correct, considering the given set of vowels.Iahubina wants to know the xor of the squared answers to all the possible questions. There are 224 different questions, they are all subsets of the set of the first 24 letters of the English alphabet. Help Iahub find that number.

The first line contains one integer, n (1 ≤ n ≤ 104). Each of the next n lines contains a 3-word consisting of 3 lowercase letters. There will be no two identical 3-words.

Print one number, the xor of the squared answers to the queries.

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 LOG_L = 24;
immutable int MAX_L = 1 << LOG_L;

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto f = new int [MAX_L];
		f[] = 0;
		foreach (i; 0..n)
		{
			string t = readln ().strip ();
			assert (t.length == 3);
			int [3] b;
			foreach (j, c; t)
			{
				b[j] = 1 << (c - 'a');
			}
			sort (b[]);
			if (b[0] == b[2])
			{
				f[b[0]] += 1;
			}
			else if (b[0] == b[1] || b[1] == b[2])
			{
				f[b[0]] += 1;
				f[b[2]] += 1;
				f[b[0] + b[2]] -= 1;
			}
			else
			{
				f[b[0]] += 1;
				f[b[1]] += 1;
				f[b[2]] += 1;
				f[b[0] + b[1]] -= 1;
				f[b[0] + b[2]] -= 1;
				f[b[1] + b[2]] -= 1;
				f[b[0] + b[1] + b[2]] += 1;
			}
		}

		for (int v = 1; v < MAX_L; v <<= 1)
		{
			immutable int m = MAX_L - 1 - v;
			int s = m;
			do
			{
				f[s ^ v] += f[s];
				s = (s - 1) & m;
			}
			while (s != m);
		}

		long res = 0;
		foreach (s; 0..MAX_L)
		{
			long cur = f[s];
			debug {if (s < 16) {writeln (s, ' ', cur);}}
			cur *= cur;
			res ^= cur;
		}
		writeln (res);
	}
}


The Great Mushroom King descended to the dwarves, but not everyone managed to see him. Only the few chosen ones could see the King.We know that only LCM(k2l + 1, k2l + 1 + 1, ..., k2r + 1) dwarves can see the Great Mushroom King. Numbers k, l, r are chosen by the Great Mushroom King himself in some complicated manner which is unclear to common dwarves. The dwarven historians decided to document all visits of the Great Mushroom King. For each visit the dwarven historians know three integers ki, li, ri, chosen by the Great Mushroom King for this visit. They also know a prime number pi. Help them to count the remainder of dividing the number of dwarves who can see the King, by number pi, for each visit.

The first line contains the single integer t (1 ≤ t ≤ 105) — the number of the King's visits.  Each of the following t input lines contains four space-separated integers ki, li, ri and pi (1 ≤ ki ≤ 106; 0 ≤ li ≤ ri ≤ 1018; 2 ≤ pi ≤ 109) — the numbers, chosen by the Great Mushroom King and the prime module, correspondingly.  It is guaranteed that for all visits number pi is prime. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

For each visit print the answer on a single line — the remainder of dividing the number of the dwarves who can see the King this time, by number pi. Print the answers for the visits in the order, in which the visits are described in the input.

NoteWe consider that LCM(a1, a2, ..., an) represents the least common multiple of numbers a1, a2, ..., an.We consider that x0 = 1, for any x.

import std.stdio;

long power(long a, long b, long mod) {
  if (b && ! (a % mod)) return 0;
  long ret = 1;
  while (b) {
    if (b & 1) (ret *= a) %= mod;
    (a *= a) %= mod, b >>= 1;
  }
  return ret;
}

long inv(long a, long p) {
  return power(a, p - 2, p);
}

int main() {
  int T; readf(" %d", &T);
  while (T--) {
    long k, l, r, p, ans;
    readf(" %d %d %d %d", &k, &l, &r, &p);
    if (p == 2) {
      if (k & 1) writeln(0); else writeln(1);
      continue;
    }
    ans = (power(k, power(2, l, p - 1) + p - 1, p) + p - 1) % p;
    if (! ans) ans = power(2, r - l + 1, p);
    else ans = (power(k, power(2, r + 1, p - 1) + p - 1, p) + p - 1) * inv(ans, p) % p;
    if (k & 1) (ans *= power((p >> 1) + 1, r - l, p)) %= p;
    writeln(ans);
  }
  return 0;
}

import std.stdio;

int T;

long power(long a, long b, long mod) {
  if (b && ! (a % mod)) return 0;
  long ret = 1;
  while (b) {
    if (b & 1) (ret *= a) %= mod;
    (a *= a) %= mod;
    b >>= 1;
  }
  return ret;
}

long inv(long a, long p) {
  return power(a, p - 2, p);
}

int main() {
  readf(" %d", &T);
  while (T--) {
    long k, l, r, p, ans;
    readf(" %d %d %d %d", &k, &l, &r, &p);
    if (p == 2) {
      if (k & 1) writeln(0);
      else writeln(1);
      continue;
    }
    ans = (power(k, power(2, l, p - 1) + p - 1, p) + p - 1) % p;
    if (! ans) ans = power(2, r - l + 1, p);
    else ans = (power(k, power(2, r + 1, p - 1) + p - 1, p) + p - 1) % p * inv(ans, p) % p;
    if (k & 1) (ans *= power((p >> 1) + 1, r - l, p)) %= p;
    writeln(ans);
  }
  return 0;
}

import std.stdio;

long power(long a, long b, long mod) {
  if (b && ! (a % mod)) return 0;
  long ret = 1;
  while (b) {
    if (b & 1) (ret *= a) %= mod;
    (a *= a) %= mod, b >>= 1;
  }
  return ret;
}

long inv(long a, long p) {
  return power(a, p - 2, p);
}

int main() {
  int T; readf(" %d", &T);
  while (T--) {
    long k, l, r, p, q, ans;
    readf(" %d %d %d %d", &k, &l, &r, &p), q = p - 1;
    if (p == 2) {
      if (k & 1) writeln(0); else writeln(1);
      continue;
    }
    ans = (power(k, power(2, l, q) + q, p) + q) % p;
    if (! ans) ans = power(2, r - l + 1, p);
    else ans = (power(k, power(2, r + 1, q) + q, p) + q) * inv(ans, p) % p;
    if (k & 1) (ans *= power((p >> 1) + 1, r - l, p)) %= p;
    writeln(ans);
  }
  return 0;
}

import std.stdio;

int T;

long power(long a, long b, long mod) {
  long ret = 1;
  while (b) {
    if (b & 1) (ret *= a) %= mod;
    (a *= a) %= mod;
    b >>= 1;
  }
  return ret;
}

long inv(long a, long p) {
  return power(a, p - 2, p);
}

int main() {
  readf(" %d", &T);
  while (T--) {
    long k, l, r, p, ans;
    readf(" %d %d %d %d", &k, &l, &r, &p);
    if (p == 2) {
      if (k & 1) writeln(0);
      else writeln(1);
      continue;
    }
    ans = power(k, power(2, l, p - 1), p) - 1;
    if (! ans) ans = power(2, r - l + 1, p);
    else ans = (power(k, power(2, r + 1, p - 1), p) - 1) * inv(ans, p);
    if (k & 1) ans *= power((p >> 1) + 1, r - l, p);
    writeln(ans);
  }
  return 0;
}

import std.stdio;

int T;

long power(long a, long b, long mod) {
  long ret = 1;
  while (b) {
    if (b & 1) (ret *= a) %= mod;
    (a *= a) %= mod;
    b >>= 1;
  }
  return ret;
}

long inv(long a, long p) {
  return power(a, p - 2, p);
}

int main() {
  readf(" %d", &T);
  while (T--) {
    long k, l, r, p, ans;
    readf(" %d %d %d %d", &k, &l, &r, &p);
    if (p == 2) {
      if (k & 1) writeln(0);
      else writeln(1);
      continue;
    }
    ans = power(k, power(2, l, p), p) - 1;
    if (! ans) ans = power(2, r - l + 1, p);
    else ans = (power(k, power(2, r + 1, p), p) - 1) * inv(ans, p);
    writeln(ans);
  }
  return 0;
}

import std.stdio;

long power(long a, long b, long mod) {
  if (b && ! (a % mod)) return 0;
  long ret = 1;
  while (b) {
    if (b & 1) (ret *= a) %= mod;
    (a *= a) %= mod, b >>= 1;
  }
  return ret;
}

long inv(long a, long p) {
  return power(a, p - 2, p);
}

int main() {
  int T; readf(" %d", &T);
  while (T--) {
    long k, l, r, p, ans;
    readf(" %d %d %d %d", &k, &l, &r, &p);
    if (p == 2) {
      if (k & 1) writeln(0); else writeln(1);
      continue;
    }
    ans = power(k, power(2, l, p - 1) + p - 1, p) + p - 1;
    if (! ans) ans = power(2, r - l + 1, p);
    else ans = (power(k, power(2, r + 1, p - 1) + p - 1, p) + p - 1) * inv(ans, p) % p;
    if (k & 1) (ans *= power((p >> 1) + 1, r - l, p)) %= p;
    writeln(ans);
  }
  return 0;
}

import std.stdio;

int T;

long power(long a, long b, long mod) {
  long ret = 1;
  while (b) {
    if (b & 1) (ret *= a) %= mod;
    (a *= a) %= mod;
    b >>= 1;
  }
  return ret;
}

long inv(long a, long p) {
  return power(a, p - 2, p);
}

int main() {
  readf(" %d", &T);
  while (T--) {
    long k, l, r, p, ans;
    readf(" %d %d %d %d", &k, &l, &r, &p);
    if (p == 2) {
      if (k & 1) writeln(0);
      else writeln(1);
      continue;
    }
    ans = power(k, power(2, l, p), p) - 1;
    if (! ans) ans = power(2, r - l + 1, p);
    else ans = (power(k, power(2, r + 1, p), p) - 1) * inv(ans, p);
    if (k & 1) ans *= power((p >> 1) + 1, r - l, p);
    writeln(ans);
  }
  return 0;
}

import std.stdio;

int T;

long power(long a, long b, long mod) {
  if (! a) return 0;
  long ret = 1;
  while (b) {
    if (b & 1) (ret *= a) %= mod;
    (a *= a) %= mod;
    b >>= 1;
  }
  return ret;
}

long inv(long a, long p) {
  return power(a, p - 2, p);
}

int main() {
  readf(" %d", &T);
  while (T--) {
    long k, l, r, p, ans;
    readf(" %d %d %d %d", &k, &l, &r, &p);
    if (p == 2) {
      if (k & 1) writeln(0);
      else writeln(1);
      continue;
    }
    k %= p;
    ans = power(k, power(2, l, p - 1), p) + p - 1;
    if (! ans) ans = power(2, r - l + 1, p);
    else ans = (power(k, power(2, r + 1, p - 1), p) + p - 1) * inv(ans, p) % p;
    if (k & 1) (ans *= power((p >> 1) + 1, r - l, p)) %= p;
    writeln(ans);
  }
  return 0;
}

import std.stdio;

int T;

long power(long a, long b, long mod) {
  if (! (a % mod)) return 0;
  long ret = 1;
  while (b) {
    if (b & 1) (ret *= a) %= mod;
    (a *= a) %= mod;
    b >>= 1;
  }
  return ret;
}

long inv(long a, long p) {
  return power(a, p - 2, p);
}

int main() {
  readf(" %d", &T);
  while (T--) {
    long k, l, r, p, ans;
    readf(" %d %d %d %d", &k, &l, &r, &p);
    if (p == 2) {
      if (k & 1) writeln(0);
      else writeln(1);
      continue;
    }
    ans = (power(k, power(2, l, p - 1), p) + p - 1) % p;
    if (! ans) ans = power(2, r - l + 1, p);
    else ans = (power(k, power(2, r + 1, p - 1), p) + p - 1) % p * inv(ans, p) % p;
    if (k & 1) (ans *= power((p >> 1) + 1, r - l, p)) %= p;
    writeln(ans);
  }
  return 0;
}

import std.stdio;

int T;

long power(long a, long b, long mod) {
  if (! a) return 0;
  long ret = 1;
  while (b) {
    if (b & 1) (ret *= a) %= mod;
    (a *= a) %= mod;
    b >>= 1;
  }
  return ret;
}

long inv(long a, long p) {
  return power(a, p - 2, p);
}

int main() {
  readf(" %d", &T);
  while (T--) {
    long k, l, r, p, ans;
    readf(" %d %d %d %d", &k, &l, &r, &p);
    if (p == 2) {
      if (k & 1) writeln(0);
      else writeln(1);
      continue;
    }
    k %= p;
    ans = (power(k, power(2, l, p - 1), p) + p - 1) % p;
    if (! ans) ans = power(2, r - l + 1, p);
    else ans = (power(k, power(2, r + 1, p - 1), p) + p - 1) % p * inv(ans, p) % p;
    if (k & 1) (ans *= power((p >> 1) + 1, r - l, p)) %= p;
    writeln(ans);
  }
  return 0;
}


Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces alternatively "Loves" and "Doesn't love", at that Marina always starts with "Loves". There are n camomiles growing in the field, possessing the numbers of petals equal to a1, a2, ... an. Marina wants to pick a bouquet with the maximal possible total number of petals so that the result would still be "Loves". Help her do that; find the maximal number of petals possible in the bouquet.

The first line contains an integer n (1 ≤ n ≤ 100), which is the number of flowers growing in the field. The second line contains n integers ai (1 ≤ ai ≤ 100) which represent the number of petals on a given i-th camomile.

Print a single number which is the maximal number of petals in the bouquet, the fortune telling on which would result in "Loves". If there are no such bouquet, print 0 instead. The bouquet may consist of a single flower.

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

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

void main() {
        IO cin;
        int n_Cases = 1;
        // n_Cases = cin.readInt;

	for (int case_i = 1; case_i <= n_Cases; case_i++) {
                int n = cin.readInt;
                int[] arr = new int[n];
                int sum = 0;
                int smallestOdd = int.max;
                foreach (ref i; arr) {
                        i = cin.readInt;
                        sum += i;
                        if ((i % 2) && i < smallestOdd) {
                                smallestOdd = i;
                        }
                }
                writeln((sum & 1 ? sum : sum - (smallestOdd == int.max ? sum : smallestOdd)));
	}
}