Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $$$a$$$ minutes to feel refreshed.Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in $$$b$$$ minutes.Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than $$$a$$$ minutes in total, then he sets his alarm to go off in $$$c$$$ minutes after it is reset and spends $$$d$$$ minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another $$$c$$$ minutes and tries to fall asleep for $$$d$$$ minutes again.You just want to find out when will Polycarp get out of his bed or report that it will never happen.Please check out the notes for some explanations of the example.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The only line of each testcase contains four integers $$$a, b, c, d$$$ ($$$1 \le a, b, c, d \le 10^9$$$) — the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.

For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.

NoteIn the first testcase Polycarp wakes up after $$$3$$$ minutes. He only rested for $$$3$$$ minutes out of $$$10$$$ minutes he needed. So after that he sets his alarm to go off in $$$6$$$ minutes and spends $$$4$$$ minutes falling asleep. Thus, he rests for $$$2$$$ more minutes, totaling in $$$3+2=5$$$ minutes of sleep. Then he repeats the procedure three more times and ends up with $$$11$$$ minutes of sleep. Finally, he gets out of his bed. He spent $$$3$$$ minutes before the first alarm and then reset his alarm four times. The answer is $$$3+4 \cdot 6 = 27$$$.The second example is almost like the first one but Polycarp needs $$$11$$$ minutes of sleep instead of $$$10$$$. However, that changes nothing because he gets $$$11$$$ minutes with these alarm parameters anyway.In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is $$$b=9$$$.In the fourth testcase Polycarp wakes up after $$$5$$$ minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :(

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto ad = readln.split.to!(long[]);
        auto A = ad[0];
        auto B = ad[1];
        auto C = ad[2];
        auto D = ad[3];

        if (A <= B) {
            writeln(B);
            continue;
        }

        auto e = C - D;
        if (e <= 0) {
            writeln(-1);
            continue;
        }

        A -= B;
        auto f = (A + e - 1) / e;
        writeln(B + C * f);
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		a -= b;
		ans[ti] = b;
		if (a <= 0) continue;

		auto e = c - d;
		if (e <= 0)
		{
			ans[ti] = -1;
			continue;
		}

		ans[ti] += c * ((a+e-1) / e);
	}

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


A group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles.In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has bi personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.Each boy can rent at most one bike, one cannot give his bike to somebody else.What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?

The first line of the input contains three integers n, m and a (1 ≤ n, m ≤ 105; 0 ≤ a ≤ 109). The second line contains the sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104), where bi is the amount of the i-th boy's personal money. The third line contains the sequence of integers p1, p2, ..., pm (1 ≤ pj ≤ 109), where pj is the price for renting the j-th bike.

Print two integers r and s, where r is the maximum number of schoolboys that can rent a bike and s is the minimum total personal money needed to rent r bikes. If the schoolchildren cannot rent any bikes, then r = s = 0.

NoteIn the first sample both schoolchildren can rent a bike. For instance, they can split the shared budget in half (5 rubles each). In this case one of them will have to pay 1 ruble from the personal money and the other one will have to pay 2 rubles from the personal money. In total, they spend 3 rubles of their personal money. This way of distribution of money minimizes the amount of spent personal money.

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

void check(T...)(T args) {
    args.map!(to!string).array.join(" ").writeln;
}

int f(ref int[] b, ref int[] p, int a, int m) {
    for (int i = 0; i < m; i++) {
        a -= [p[i] - b[m - 1 - i], 0].reduce!max;
        if (a < 0) {
            return -1;
        }
    }
    return a;
}

void main() {
    int n, m, a; readf("%d %d %d\n", &n, &m, &a);
    int[] b = new int[n];
    int[] p = new int[m];
    foreach (i; 0 .. n) {
        scanf("%d", &b[i]);
    }
    foreach (i; 0 .. m) {
        scanf("%d", &p[i]);
    }
    b.sort!("a > b");
    p.sort;
    int x = 0;
    int l, r;
    int s = 0;
    for (l = 0, r = [n, m].reduce!min + 1; l + 1 < r; ) {
        x = (l + r) / 2;
        s = f(b, p, a, x);
        if (s >= 0) {
            l = x;
        } else {
            r = x;
        }
    }
    if (l == 0) {
        writeln("0 0");
        return;
    }
    [l, [0, p[0 .. l].reduce!"a + b" - a].reduce!max].check;
}

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

void check(T...)(T args) {
    args.map!(to!string).array.join(" ").writeln;
}

int f(ref int[] b, ref int[] p, int a, int m) {
    for (int i = 0; i < m; i++) {
        a -= [p[i] - b[m - 1 - i], 0].reduce!max;
        if (a < 0) {
            return -1;
        }
    }
    return a;
}

void main() {
    int n, m, a; readf("%d %d %d\n", &n, &m, &a);
    int[] b = new int[n];
    int[] p = new int[m];
    foreach (i; 0 .. n) {
        scanf("%d", &b[i]);
    }
    foreach (i; 0 .. m) {
        scanf("%d", &p[i]);
    }
    b.sort!("a > b");
    p.sort;
    int x = 0;
    int l, r;
    int s = 0;
    for (l = 0, r = [n, m].reduce!min + 1; l + 1 < r; ) {
        x = (l + r) / 2;
        s = f(b, p, a, x);
        if (s >= 0) {
            l = x;
        } else {
            r = x;
        }
    }
    [l, p[0 .. l].reduce!"a + b" - a].check;
}

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

void check(T...)(T args) {
    args.map!(to!string).array.join(" ").writeln;
}

void main() {
    int n, m, a; readf("%d %d %d\n", &n, &m, &a);
    int[] b = new int[n];
    int[] p = new int[m];
    foreach (i; 0 .. n) {
        scanf("%d", &b[i]);
    }
    foreach (i; 0 .. m) {
        scanf("%d", &p[i]);
    }
    b.sort!("a > b");
    p.sort!("a > b");
    int bi = 0, pi = 0;
    bool[] used = new bool[m];
    int c = 0;
    for (; bi < n && pi < m; ) {
        if (b[bi] >= p[pi]) {
            c++;
            bi++;
            used[pi] = true;
        }
        pi++;
    }
    Array!int pp;
    foreach (int i, x; p) {
        if (!used[i]) {
            pp.insert(x);
        }
    }
    auto rp = pp.array.sort;
    int rpi = 0;
    int a_ = a;
    for (; bi < n && rpi < rp.length; bi++, rpi++) {
        if (a >= rp[rpi] - b[bi]) {
            a -= rp[rpi] - b[bi];
            c++;
        }
    }
    int ps = p.sort[0 .. c].reduce!("a + b");
    [c, [ps - a_, 0].reduce!max].check;
}

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

void check(T...)(T args) {
    args.map!(to!string).array.join(" ").writeln;
}

void main() {
    int n, m, a; readf("%d %d %d\n", &n, &m, &a);
    int[] b = new int[n];
    int[] p = new int[m];
    foreach (i; 0 .. n) {
        scanf("%d", &b[i]);
    }
    foreach (i; 0 .. m) {
        scanf("%d", &p[i]);
    }
    b.sort!("a > b");
    p.sort!("a > b");
    int bi = 0, pi = 0;
    bool[] used = new bool[m];
    int c = 0;
    for (; bi < n && pi < m; ) {
        if (b[bi] >= p[pi]) {
            c++;
            bi++;
            used[pi] = true;
        }
        pi++;
    }
    Array!int pp;
    foreach (int i, x; p) {
        if (!used[i]) {
            pp.insert(x);
        }
    }
    auto rp = pp.array.sort;
    int rpi = 0;
    int a_ = a;
    for (; bi < n && rpi < rp.length; bi++) {
        if (a >= rp[rpi] - b[bi]) {
            a -= rp[rpi] - b[bi];
            c++;
            rpi++;
        }
    }
    int ps = p.sort[0 .. c].reduce!("a + b");
    [c, [ps - a_, 0].reduce!max].check;
}

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

void check(T...)(T args) {
    args.map!(to!string).array.join(" ").writeln;
}

void main() {
    int n, m, a; readf("%d %d %d\n", &n, &m, &a);
    int[] b = new int[n];
    int[] p = new int[m];
    foreach (i; 0 .. n) {
        scanf("%d", &b[i]);
    }
    foreach (i; 0 .. m) {
        scanf("%d", &p[i]);
    }
    b.sort!("a > b");
    p.sort!("a > b");
    int bi = 0, pi = 0;
    bool[] used = new bool[m];
    int c = 0;
    for (; bi < n && pi < m; ) {
        if (b[bi] >= p[pi]) {
            c++;
            bi++;
            used[pi] = true;
        }
        pi++;
    }
    Array!int pp;
    foreach (int i, x; p) {
        if (!used[i]) {
            pp.insert(x);
        }
    }
    auto rp = pp.array.sort;
    int rpi = 0;
    int a_ = a;
    for (; bi < n && rpi < rp.length; bi++, rpi++) {
        if (a >= rp[rpi] - b[bi]) {
            a -= rp[rpi] - b[bi];
            c++;
        }
    }
    int ps = p.sort[0 .. c].reduce!("a + b");
    [c, ps - a_].check;
}


Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others — a group of b-s), but cccc is not since in each possible consequent partition letters in these two groups coincide.You're given a string s. Check whether it can be split into two non-empty subsequences such that the strings formed by these subsequences are adorable. Here a subsequence is an arbitrary set of indexes of the string.

The only line contains s (1 ≤ |s| ≤ 105) consisting of lowercase latin letters.

Print «Yes» if the string can be split according to the criteria above or «No» otherwise. Each letter can be printed in arbitrary case.

NoteIn sample case two zzcxx can be split into subsequences zc and zxx each of which is adorable.There's no suitable partition in sample case three.

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

void main()
{
	uint[char] aa;

	foreach(c; readln.strip)
	{
		aa[c]++;
	}

	writeln(aa.length > 4 || aa.length < 2 || aa.byValue.sum < 4 || (aa.length == 2 && aa.byValue.reduce!min == 1) ? `No` : `Yes`);
}


Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.

The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000). The following line contains a binary string of length n representing Kevin's results on the USAICO.

Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.

NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score.

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

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

    auto dp = new int[][](N, 3);
    dp[0][0] = dp[0][1] = 1;

    foreach (i; 1..N) {
        bool same = (S[i] == S[i-1]);
        dp[i][0] = dp[i-1][0] + !same;
        dp[i][1] = max(dp[i-1][0]+same, dp[i-1][1]+!same);
        dp[i][2] = max(dp[i-1][1]+same, dp[i-1][2]+!same);
    }

    int ans = 0;
    foreach (i; 0..N) foreach (j; 0..3) ans = max(ans, dp[i][j]);
    writeln(ans);
}

import std.algorithm, std.range, std.stdio;
void main () {
	readln;
	auto s = readln, n = s.length - 1, res = (n - 1).iota.map !(i => s[i] != s[i + 1]).sum;
	n.min (res + 3).writeln;
}

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)
	{
		readln ();
		auto s = readln.strip;
		auto res = (n - 1).iota.map !(i => s[i] != s[i + 1]).sum;
		res = min (res + 3, n);
		writeln (res);
	}
}


Arkady and Kirill visited an exhibition of rare coins. The coins were located in a row and enumerated from left to right from 1 to k, each coin either was laid with its obverse (front) side up, or with its reverse (back) side up.Arkady and Kirill made some photos of the coins, each photo contained a segment of neighboring coins. Akrady is interested in obverses, so on each photo made by him there is at least one coin with obverse side up. On the contrary, Kirill is interested in reverses, so on each photo made by him there is at least one coin with its reverse side up.The photos are lost now, but Arkady and Kirill still remember the bounds of the segments of coins each photo contained. Given this information, compute the remainder of division by 109 + 7 of the number of ways to choose the upper side of each coin in such a way, that on each Arkady's photo there is at least one coin with obverse side up, and on each Kirill's photo there is at least one coin with reverse side up.

The first line contains three integers k, n and m (1 ≤ k ≤ 109, 0 ≤ n, m ≤ 105) — the total number of coins, the number of photos made by Arkady, and the number of photos made by Kirill, respectively. The next n lines contain the descriptions of Arkady's photos, one per line. Each of these lines contains two integers l and r (1 ≤ l ≤ r ≤ k), meaning that among coins from the l-th to the r-th there should be at least one with obverse side up. The next m lines contain the descriptions of Kirill's photos, one per line. Each of these lines contains two integers l and r (1 ≤ l ≤ r ≤ k), meaning that among coins from the l-th to the r-th there should be at least one with reverse side up.

Print the only line — the number of ways to choose the side for each coin modulo 109 + 7 = 1000000007.

NoteIn the first example the following ways are possible ('O' — obverse, 'R' — reverse side):   OROOR,  ORORO,  ORORR,  RROOR,  RRORO,  RRORR,  ORROR,  ORRRO. In the second example the information is contradictory: the second coin should have obverse and reverse sides up at the same time, that is impossible. So, the answer is 0.

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

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

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

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

void bAdd(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    bit[x] += val;
  }
}

// sum of [0, pos)
T bSum(T)(T[] bit, int pos)
in {
  assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold");
}
do {
  T ret = 0;
  for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
    ret += bit[x];
  }
  return ret;
}

struct ModInt(int M_) {
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op)() const if (op == "-") { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

enum MO = 1000000007;
alias Mint = ModInt!MO;

alias Interval = Tuple!(int, "l", int, "r", int, "s");

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

      auto xs = [0, K] ~ A ~ B ~ C ~ D;
      xs = xs.sort.uniq.array;
      const xsLen = cast(int)(xs.length);
      auto E = new Interval[M + N];
      foreach (i; 0 .. M) {
        E[i] = Interval(xs.lowerBound(A[i]), xs.lowerBound(B[i]), 0);
      }
      foreach (i; 0 .. N) {
        E[M + i] = Interval(xs.lowerBound(C[i]), xs.lowerBound(D[i]), 1);
      }
      E.sort!((a, b) => ((a.r != b.r) ? (a.r < b.r) : (a.l > b.l)));
      debug {
        writeln("xs = ", xs);
        writeln("E = ", E);
      }

      auto twos = new Mint[xsLen];
      auto invTwos = new Mint[xsLen];
      foreach (j; 0 .. xsLen) {
        twos[j] = Mint(2)^^xs[j];
        invTwos[j] = twos[j].inv;
      }
      // ovl: overlap > 0
      auto ovls = new Mint[][](2, xsLen);
      auto gaps = new Mint[][](2, xsLen);
      ovls[0].bAdd(0, Mint(1));
      gaps[0].bAdd(0, Mint(1));
      int[] maxLs = [-1, -1];
      foreach (ref e; E) {
        if (chmax(maxLs[e.s], e.l)) {
          Mint now;
          // same
          now += ovls[e.s].bSum(xsLen) - ovls[e.s].bSum(e.l + 1);
          now += gaps[e.s].bSum(e.l + 1) * twos[e.l];
          // diff
          now += gaps[e.s ^ 1].bSum(e.l + 1) * twos[e.l];
          now *= -1;
          ovls[e.s].bAdd(e.r, now);
          gaps[e.s].bAdd(e.r, now * invTwos[e.r]);
        }
      }

      Mint ans;
      foreach (s; 0 .. 2) {
        ans += gaps[s].bSum(xsLen) * twos[xsLen - 1];
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are playing a computer game. To pass the current level, you have to kill a big horde of monsters. In this horde, there are $$$n$$$ monsters standing in the row, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th monster has $$$a_i$$$ health and a special "Death's Blessing" spell of strength $$$b_i$$$ attached to it.You are going to kill all of them one by one. It takes exactly $$$h$$$ seconds to kill a monster with health $$$h$$$.When the $$$i$$$-th monster dies, it casts its spell that increases the health of its neighbors by $$$b_i$$$ (the neighbors of the $$$j$$$-th monster in the row are the monsters on places $$$j - 1$$$ and $$$j + 1$$$. The first and the last monsters have only one neighbor each).After each monster is killed, the row shrinks, so its former neighbors become adjacent to each other (so if one of them dies, the other one is affected by its spell). For example, imagine a situation with $$$4$$$ monsters with health $$$a = [2, 6, 7, 3]$$$ and spells $$$b = [3, 6, 0, 5]$$$. One of the ways to get rid of the monsters is shown below:  $$$2$$$$$$6$$$$$$7$$$$$$3$$$$$$\xrightarrow{6\ s}$$$$$$8$$$$$$13$$$$$$3$$$$$$\xrightarrow{13\ s}$$$$$$8$$$$$$3$$$$$$\xrightarrow{8\ s}$$$$$$6$$$$$$\xrightarrow{6\ s}$$$$$$\{\}$$$$$$3$$$$$$6$$$$$$0$$$$$$5$$$$$$3$$$$$$0$$$$$$5$$$$$$3$$$$$$5$$$$$$5$$$ The first row represents the health of each monster, the second one — the power of the spells. As a result, we can kill all monsters in $$$6 + 13 + 8 + 6$$$ $$$=$$$ $$$33$$$ seconds. Note that it's only an example and may not be the fastest way to get rid of the monsters.What is the minimum time required to kill all monsters in the row?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of monsters in the row. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial health of corresponding monsters. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i \le 10^9$$$), where $$$b_i$$$ is the strength of the spell for the $$$i$$$-th monster. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the minimum possible total time to kill all monsters.

NoteIn the first test case, there is only one monster that will be killed in $$$10$$$ seconds.In the second test case, it's optimal to kill the first monster, the last monster and then the middle one. It will take $$$100 + 100 + (1 + 1 + 1)$$$ $$$=$$$ $$$203$$$ seconds.In the third test case, it's optimal to kill the first monster, then the third one, then the fourth one and finally the second one. It will take $$$2 + 7 + (3 + 0) + (3 + 6 + 5)$$$ $$$=$$$ $$$26$$$ seconds.

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

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;
		auto b = readln.splitter.map !(to !(int)).array;
		writeln (sum (a, 0L) + sum (b, 0L) - maxElement (b));
	}
}

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 = readln.strip.to!long;
    auto a = readln.splitter.map!(to!long).array;
    auto b = readln.splitter.map!(to!long).array;
    writeln(a.sum + b.sum - b.maxElement);
  }
}

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

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

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

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

    auto r = B.reduce!max;
    writeln(A.reduce!"a+b" + B.reduce!"a+b" - r);
}


Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.Now Petya wants to know for each friend i the number of a friend who has given him a gift.

The first line contains one integer n (1 ≤ n ≤ 100) — the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi — the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.

Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.

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; scanf("%d\n", &N);
    auto D = readln.chomp.split(" ").map!(to!int).array;
    auto X = new int[N];
    foreach (int i, j; D) {
        X[j - 1] = i + 1;
    }
    writefln("%(%s %)", X);
}

import std.stdio;

/*
 * pi: numero della persona che ha dato il regalo alla persona
 * i. Potrebbe essere che pi == i e inoltre si sa che pi != pk per
 * ogni i != k.
 */
int[] gifters(int[] pis, int n) {
  int[] gifters;
  gifters.length = n;
  for (int i=0; i < n; i++) {
    gifters[(pis[i] - 1)] = i + 1;
  }
  return gifters;
}

void print_gifters(int[] gifters) {
  for (int i = 0; i < gifters.length; i++) {
    if (i == 0)
      writef("%s", gifters[i]);
    else
      writef(" %s", gifters[i]);
  }
}

int main() {
  int n, pi;
  readf("%s", &n);
  int[] pis;
  pis.length = n;
  for (int i=0; i < n; i++) {
    readf(" %s", &pi);
    pis[i] = pi;
  }
  print_gifters(gifters(pis, n));
  return 0;
}

import std.stdio;
import std.string;
import core.stdc.stdio;
import std.math;
import std.algorithm;

class Friend
{
	public int f;
	public int p;
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	Friend[] friends;
	friends.length = n;
	foreach (int i; 0..n)
	{
		friends[i] = new Friend();
		scanf("%d", &(friends[i].f));
		friends[i].p = i;
	}
	sort!("a.f < b.f", SwapStrategy.stable)(friends);
	foreach (int i; 0..n)
	{
		printf((i < n-1) ? "%d " : "%d", (friends[i].p + 1));
	}
	return 0;
}

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

void main() {
  int n = readln.chomp.to!int;
  auto p = readln.chomp.split.map!(to!int);

  auto ans = new int[n];

  for (int i = 0; i < n; i++) {
    ans[p[i]-1] = i + 1;
  }

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


Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day.In return, the fleas made a bigger ukulele for her: it has $$$n$$$ strings, and each string has $$$(10^{18} + 1)$$$ frets numerated from $$$0$$$ to $$$10^{18}$$$. The fleas use the array $$$s_1, s_2, \ldots, s_n$$$ to describe the ukulele's tuning, that is, the pitch of the $$$j$$$-th fret on the $$$i$$$-th string is the integer $$$s_i + j$$$.Miyako is about to leave the kingdom, but the fleas hope that Miyako will answer some last questions for them.Each question is in the form of: "How many different pitches are there, if we consider frets between $$$l$$$ and $$$r$$$ (inclusive) on all strings?"Miyako is about to visit the cricket kingdom and has no time to answer all the questions. Please help her with this task!Formally, you are given a matrix with $$$n$$$ rows and $$$(10^{18}+1)$$$ columns, where the cell in the $$$i$$$-th row and $$$j$$$-th column ($$$0 \le j \le 10^{18}$$$) contains the integer $$$s_i + j$$$. You are to answer $$$q$$$ queries, in the $$$k$$$-th query you have to answer the number of distinct integers in the matrix from the $$$l_k$$$-th to the $$$r_k$$$-th columns, inclusive.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the number of strings. The second line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \leq s_i \leq 10^{18}$$$) — the tuning of the ukulele. The third line contains an integer $$$q$$$ ($$$1 \leq q \leq 100\,000$$$) — the number of questions. The $$$k$$$-th among the following $$$q$$$ lines contains two integers $$$l_k$$$，$$$r_k$$$ ($$$0 \leq l_k \leq r_k \leq 10^{18}$$$) — a question from the fleas.

Output one number for each question, separated by spaces — the number of different pitches.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.splitter.map !(to !(long)).array;
		sort (s);

		long [] v;
		v.reserve (n - 1);
		foreach (i; 1..n)
		{
			v ~= s[i] - s[i - 1];
		}
		sort (v);
		debug {writeln (v);}

		long [] c;
		c.reserve (n);
		c ~= 0;
		foreach (i; 1..n)
		{
			c ~= c[$ - 1] + v[i - 1];
		}
		debug {writeln (c);}

		long solve (long d)
		{
			int lo = 0;
			int hi = n - 1;
			while (lo < hi)
			{
				int me = (lo + hi) / 2;
				if (v[me] <= d)
				{
					lo = me + 1;
				}
				else
				{
					hi = me;
				}
			}
			debug {writeln (lo, " ", d, " ", n - 1 - lo);}
			return c[lo] + (d + 1) * (n - lo);
		}

		int q;
		readf (" %s", &q);
		long [] res;
		res.reserve (q);
		foreach (j; 0..q)
		{
			long l, r;
			readf (" %s %s", &l, &r);
			long d = r - l;
			res ~= solve (d);
		}
		writefln ("%(%s %)", res);
	}
}

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

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

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

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

enum INF = 3 * 10L^^18;

int N;
long[] S;
int Q;
long[] L, R;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      S = new long[N];
      foreach (i; 0 .. N) {
        S[i] = readLong();
      }
      Q = readInt();
      L = new long[Q];
      R = new long[Q];
      foreach (q; 0 .. Q) {
        L[q] = readLong();
        R[q] = readLong();
      }

      S.sort;

      auto ds = new long[N];
      foreach (i; 0 .. N - 1) {
        ds[i] = S[i + 1] - S[i];
      }
      ds[N - 1] = INF;
      ds.sort;

      auto dsSum = new long[N + 1];
      foreach (i; 0 .. N) {
        dsSum[i + 1] = dsSum[i] + ds[i];
      }

      auto ans = new long[Q];
      foreach (q; 0 .. Q) {
        const pos = ds.lowerBound(R[q] - L[q] + 1);
        ans[q] = dsSum[pos] + (R[q] - L[q] + 1) * (N - pos);
      }
      foreach (q; 0 .. Q) {
        if (q > 0) {
          write(" ");
        }
        write(ans[q]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You can perform the following operations with it:   Choose some positions $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n, i \ne j$$$), write the value of $$$a_i \cdot a_j$$$ into the $$$j$$$-th cell and remove the number from the $$$i$$$-th cell;  Choose some position $$$i$$$ and remove the number from the $$$i$$$-th cell (this operation can be performed no more than once and at any point of time, not necessarily in the beginning). The number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations.Your task is to perform exactly $$$n - 1$$$ operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print any sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the elements of the array.

Print $$$n - 1$$$ lines. The $$$k$$$-th line should contain one of the two possible operations. The operation of the first type should look like this: $$$1~ i_k~ j_k$$$, where $$$1$$$ is the type of operation, $$$i_k$$$ and $$$j_k$$$ are the positions of the chosen elements. The operation of the second type should look like this: $$$2~ i_k$$$, where $$$2$$$ is the type of operation, $$$i_k$$$ is the position of the chosen element. Note that there should be no more than one such operation. If there are multiple possible sequences of operations leading to the maximum number — print any of them.

NoteLet X be the removed number in the array. Let's take a look at all the examples:The first example has, for example, the following sequence of transformations of the array: $$$[5, -2, 0, 1, -3] \to [5, -2, X, 1, -3] \to [X, -10, X, 1, -3] \to$$$ $$$[X, X, X, -10, -3] \to [X, X, X, X, 30]$$$. Thus, the maximum answer is $$$30$$$. Note, that other sequences that lead to the answer $$$30$$$ are also correct.The second example has, for example, the following sequence of transformations of the array: $$$[5, 2, 0, 4, 0] \to [5, 2, X, 4, 0] \to [5, 2, X, 4, X] \to [X, 10, X, 4, X] \to$$$ $$$[X, X, X, 40, X]$$$. The following answer is also allowed: 1 5 31 4 21 2 12 3Then the sequence of transformations of the array will look like this: $$$[5, 2, 0, 4, 0] \to [5, 2, 0, 4, X] \to [5, 8, 0, X, X] \to [40, X, 0, X, X] \to$$$ $$$[40, X, X, X, X]$$$.The third example can have the following sequence of transformations of the array: $$$[2, -1] \to [2, X]$$$.The fourth example can have the following sequence of transformations of the array: $$$[0, -10, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0]$$$.The fifth example can have the following sequence of transformations of the array: $$$[0, 0, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0]$$$.

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

const long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;

    auto zero = N.iota.filter!(i => A[i] == 0).map!(i => tuple(i+1, A[i])).array;
    auto minus = N.iota.filter!(i => A[i] < 0).map!(i => tuple(i+1, A[i])).array;
    auto plus = N.iota.filter!(i => A[i] > 0).map!(i => tuple(i+1, A[i])).array;
    minus.sort!("a[1] < b[1]")();
    int cnt = N - 1;
    bool nozero = false;

    if (minus.length % 2 == 1) {
        if (zero.length > 0) {
            zero ~= minus.back;
            minus.popBack;
            foreach (i; 0..zero.length.to!int-1) {
                writeln(1, " ", zero[i][0], " ", zero[i+1][0]);
                cnt--;
            }
            if (cnt > 0) {
                writeln(2, " ", zero.back[0]);
                --cnt;
            }
            nozero = true;
        } else {
            writeln(2, " ", minus.back[0]);
            minus.popBack;
            --cnt;
        }
    } else if (zero.length > 0) {
        foreach (i; 0..zero.length.to!int-1) {
            writeln(1, " ", zero[i][0], " ", zero[i+1][0]);
            cnt--;
        }
        if (cnt > 0) {
            writeln(2, " ", zero.back[0]);
            --cnt;
        }
        nozero = true;
    }

    auto rest = minus ~ plus;
    int len = rest.length.to!int;

    while (cnt > 0) {
        int x = rest.back[0];
        rest.popBack;
        int y = rest.back[0];
        writeln(1, " ", x, " ", y);
        cnt--;
    }
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; rd(n);
  auto a=readln.split.to!(int[]);

  auto count=reduce!((r, e)=>r+(e==0 ? 1 : 0))(0, a);
  auto minus=reduce!((r, e)=>r+(e<0 ? 1 : 0))(0, a);
  int[][] ans;
  if(count==0){
    if(minus%2==0){
      for(int i=1; i<n; i++){
        ans~=[1, i, i+1];
      }
    }else{
      int pos=-1;
      foreach(int i, e; a){
        if(e<0){
          if(pos==-1){
            pos=i;
          }else{
            if(a[pos]<e){
              pos=i;
            }
          }
        }
      }
      writeln(2, " ", pos+1);
      if(pos==0){
        for(int i=2; i<n; i++){
          ans~=[1, i, i+1];
        }
      }else if(pos==n-1){
        for(int i=1; i+1<n; i++){
          ans~=[1, i, i+1];
        }
      }else{
        for(int i=1; i<n; i++){
          if(i+1==pos+1){
            ans~=[1, i, i+2];
            i++;
          }else{
            ans~=[1, i, i+1];
          }
        }
      }
    }
  }else{
    int cnt=0;
    int zeropos=-1;
    if(count>=2){
      int last=-1;
      foreach(int i, e; a){ // 最右の0に寄せる
        if(e==0){
          if(last>=0){
            writeln(1, " ", last+1, " ", i+1);
            cnt++;
          }
          last=i;
          zeropos=i;
        }
      }
    }
    for(int i=n-1; i>=0; i--){
      if(a[i]==0){
        zeropos=i;
        break;
      }
    }
    int pos=-1;
    if(minus&1){
      foreach(int i, e; a){
        if(e<0){
          if(pos==-1){
            pos=i;
          }else{
            if(a[pos]<e){
              pos=i;
            }
          }
        }
      }
      writeln(1, " ", pos+1, " ", zeropos+1);
      cnt++;
    }
    if(cnt+1<n){
      writeln(2, " ", zeropos+1);
    }
    int last=-1;
    foreach(int i, e; a){
      if(e==0 || i==pos || i==zeropos) continue;
      if(last>=0){
        ans~=[1, last+1, i+1];
      }
      last=i;
    }
  }

  foreach(aa; ans){
    writefln("%(%s %)", aa);
  }

}
void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

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

const long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;

    auto zero = N.iota.filter!(i => A[i] == 0).map!(i => tuple(i+1, A[i])).array;
    auto minus = N.iota.filter!(i => A[i] < 0).map!(i => tuple(i+1, A[i])).array;
    auto plus = N.iota.filter!(i => A[i] > 0).map!(i => tuple(i+1, A[i])).array;
    minus.sort!("a[1] < b[1]")();
    int cnt = N - 1;
    bool nozero = false;

    if (minus.length % 2 == 1) {
        writeln(2, " ", minus.back[0]);
        minus.popBack;
        cnt--;
    } else if (zero.length > 0) {
        foreach (i; 0..zero.length.to!int-1) {
            writeln(1, " ", zero[i][0], " ", zero[i+1][0]);
            cnt--;
        }
        if (cnt > 0) {
            writeln(2, " ", zero.back[0]);
            --cnt;
        }
        nozero = true;
    }

    auto rest = minus ~ plus;
    if (!nozero) rest ~= zero;

    foreach (i; 0..rest.length.to!int-1) {
        int x = rest.back[0];
        rest.popBack;
        int y = rest.back[0];
        writeln(1, " ", x, " ", y);
        cnt--;
    }
}


A permutation — is a sequence of length $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all the numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ — permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ — no.Polycarp was recently gifted a permutation $$$a[1 \dots n]$$$ of length $$$n$$$. Polycarp likes trees more than permutations, so he wants to transform permutation $$$a$$$ into a rooted binary tree. He transforms an array of different integers into a tree as follows:   the maximum element of the array becomes the root of the tree;  all elements to the left of the maximum — form a left subtree (which is built according to the same rules but applied to the left part of the array), but if there are no elements to the left of the maximum, then the root has no left child;  all elements to the right of the maximum — form a right subtree (which is built according to the same rules but applied to the right side of the array), but if there are no elements to the right of the maximum, then the root has no right child. For example, if he builds a tree by permutation $$$a=[3, 5, 2, 1, 4]$$$, then the root will be the element $$$a_2=5$$$, and the left subtree will be the tree that will be built for the subarray $$$a[1 \dots 1] = [3]$$$, and the right one — for the subarray $$$a[3 \dots 5] = [2, 1, 4]$$$. As a result, the following tree will be built:     The tree corresponding to the permutation $$$a=[3, 5, 2, 1, 4]$$$. Another example: let the permutation be $$$a=[1, 3, 2, 7, 5, 6, 4]$$$. In this case, the tree looks like this:     The tree corresponding to the permutation $$$a=[1, 3, 2, 7, 5, 6, 4]$$$. Let us denote by $$$d_v$$$ the depth of the vertex $$$a_v$$$, that is, the number of edges on the path from the root to the vertex numbered $$$a_v$$$. Note that the root depth is zero. Given the permutation $$$a$$$, for each vertex, find the value of $$$d_v$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the permutation. This is followed by $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$ — permutation $$$a$$$.

For each test case, output $$$n$$$ values — $$$d_1, d_2, \ldots, d_n$$$.

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T); while (T--) {
        int N; get(N);
        int[] AA; get(AA);

        auto res = new int[](N);
        void solve(int l, int r, int d) {
            if (l == r) return;

            int p, max_a;
            foreach (i; l..r) if (AA[i] > max_a) {
                max_a = AA[i];
                p = i;
            }
            res[p] = d;
            solve(l, p, d + 1);
            solve(p + 1, r, d + 1);
        }
        solve(0, N, 0);
        writefln!"%(%d %)"(res);
    }
}

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;
		auto d = new int [n];

		void build (int lo, int hi, int depth)
		{
			if (lo >= hi)
			{
				return;
			}
			auto me = hi - maxPos (a[lo..hi]).length.to !(int);
			d[me] = depth;
			build (lo, me, depth + 1);
			build (me + 1, hi, depth + 1);
		}

		build (0, n, 0);
		writefln !("%(%s %)") (d);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		void dfs(int pos, int depth)
		{
			ans[ti][pos] = depth;
			auto x = a[pos];
			{
				int j = -1, y;
				foreach_reverse (i; 0..pos)
				{
					if (a[i] > x) break;
					if (a[i] > y)
					{
						j = i;
						y = a[j];
					}
				}
				if (j != -1)
					dfs(j, depth+1);
			}
			{
				int j = -1, y;
				foreach (i; pos+1..n)
				{
					if (a[i] > x) break;
					if (a[i] > y)
					{
						j = i;
						y = a[j];
					}
				}
				if (j != -1)
					dfs(j, depth+1);
			}
		}
		int p;
		foreach (i; 0..n)
		{
			if (a[i] > a[p])
				p = i;
		}
		dfs(p, 0);
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}


The little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of $$$n$$$ elements (the elements of the array are indexed starting from 1); also, there are $$$q$$$ queries, each one is defined by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \le l_i \le r_i \le n)$$$. You need to find for each query the sum of elements of the array with indexes from $$$l_i$$$ to $$$r_i$$$, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.

The first line contains two space-separated integers $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) and $$$q$$$ ($$$1 \le q \le 2\cdot10^5$$$) — the number of elements in the array and the number of queries, correspondingly. The next line contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \le a_i \le 2\cdot10^5$$$) — the array elements. Each of the following $$$q$$$ lines contains two space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the $$$i$$$-th query.

In a single line print, a single integer — the maximum sum of query replies after the array elements are reordered. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

void main() {
    uint n, q; readf("%d %d\n", &n, &q);
    ulong[] a = stdin.readln.split.map!(to!ulong).array;
    ulong[] c = new ulong[a.length + 1]; c.fill(0);
    foreach (i; 0 .. q) {
        int f, t; readf("%d %d\n", &f, &t); f--; t--;
        c[f]++;
        c[t + 1]--;
    }
    ulong acc = 0;
    foreach (ref e; c) {
        acc += e;
        e = acc;
    }
    ulong[] o = c[0 .. $ - 1].sort!("a > b").array;
    ulong[] x = a.sort!("a > b").array;
    ulong ans = 0;
    foreach (i; 0 .. o.length) {
        ans += o[i] * x[i];
    }
    writeln(ans);
}

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

void main() {
    uint n, q; readf("%d %d\n", &n, &q);
    ulong[] a = stdin.readln.split.map!(to!ulong).array;
    ulong[] c = new ulong[a.length + 1]; c.fill(0);
    foreach (i; 0 .. q) {
        int f, t; readf("%d %d\n", &f, &t); f--; t--;
        c[f]++;
        c[t + 1]--;
    }
    ulong acc = 0;
    foreach (ref e; c) {
        acc += e;
        e = acc;
    }
    auto o = c[0 .. $ - 1].sort;
    auto x = a.sort;
    ulong ans = 0;
    foreach (i; 0 .. o.length) {
        ans += o[i] * x[i];
    }
    writeln(ans);
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n,q;
    readf!"%d %d"(n,q);
    readln;
    int[] a=readln.splitter
                  .map!(to!int)
                  .array;
    long[] d=new long[n];
    int l,r;
    while(q--){
        readf!"%d %d"(l,r);
        readln;
        l--;
        d[l]++;
        if(r<n) d[r]--;
    }
    foreach(i;1..n)
        d[i]+=d[i-1];
    sort!"a>b"(d);
    sort!"a>b"(a);
    ulong ans=0;
    foreach(i;0..n)
        ans+=a[i]*d[i];
    writeln(ans);
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n,q;
    readf!"%d %d"(n,q);
    readln;
    int[] a=readln.splitter
                  .map!(to!int)
                  .array,
        d=new int[n];
    int l,r;
    while(q--){
        readf!"%d %d"(l,r);
        readln;
        l--;
        d[l]++;
        if(r<n) d[r]--;
    }
    foreach(i;1..n)
        d[i]+=d[i-1];
    sort!"a>b"(d);
    sort!"a>b"(a);
    ulong ans=0;
    foreach(i;0..n)
        ans+=a[i]*d[i];
    writeln(ans);
}


In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.

The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).

Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.

NoteIn the first example the ranks will be raised in the following manner:1 2 2 3  →  2 2 3 4  →  2 3 4 4  →  3 4 4 4  →  4 4 4 4Thus totals to 4 training sessions that require 4 golden coins.

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 k = cin.readInt;
                int[] arr = new int[n];
                int[101] count = 0;
                foreach (ref i; arr) {
                        i = cin.readInt;
                        count[i]++;
                }

                int level = 0;
                while (count[k] != n) {
                        auto temp = count.dup;
                        for (int i = 0; i < k; i++) {
                                if (temp[i]) {
                                        count[i]--;
                                        count[i + 1]++;
                                }
                        }
                        level++;
                }
                writeln(level);
	}
}


Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 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 number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$.

NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$.

import std.stdio;
import std.string : split, strip;
import std.algorithm : chunkBy, map, maxElement, sum;
import std.conv : to;

void main() {
  int t;
  readf!"%d\n"(t);

  foreach (i; 0..t) {
    int n;
    readf!"%d\n"(n);

    auto s = readln.strip.split
      .map!(to!long)
      .chunkBy!((a, b) => (a > 0) == (b > 0))
      .map!maxElement
      .sum;
    writeln(s);
  }
}

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!long;
        long[][] as = [[]];
        size_t i;
        long last = 0;
        foreach (a; readln.split.to!(long[])) {
            if (last*a < 0) {
                sort!"a > b"(as[i]);
                ++i;
                as ~= [[]];
            }
            as[i] ~= a;
            last = a;
        }
        sort!"a > b"(as[i]);
        long s;
        foreach (a; as) s += a[0];
        writeln(s);
    }
}

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

void main ()
{
	readln;
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		readln
		    .splitter
		    .map !(to !(int))
		    .chunkBy !(q{(a > 0) == (b > 0)})
		    .map !(maxElement)
		    .sum (0L)
		    .writeln;
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long m = a[0];
		foreach (i; 1..n)
		{
			if (a[i] * a[i-1] < 0)
			{
				ans[ti] += m;
				m = long.min;
			}
			m.chmax(a[i]);
		}
		ans[ti] += m;
	}

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


There are $$$n$$$ railway stations in Berland. They are connected to each other by $$$n-1$$$ railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the $$$n-1$$$ sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from $$$1$$$ to $$$10^6$$$ inclusive.You asked $$$m$$$ passengers some questions: the $$$j$$$-th one told you three values:  his departure station $$$a_j$$$;  his arrival station $$$b_j$$$;  minimum scenery beauty along the path from $$$a_j$$$ to $$$b_j$$$ (the train is moving along the shortest path from $$$a_j$$$ to $$$b_j$$$). You are planning to update the map and set some value $$$f_i$$$ on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values $$$f_1, f_2, \dots, f_{n-1}$$$, which the passengers' answer is consistent with or report that it doesn't exist.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of railway stations in Berland. The next $$$n-1$$$ lines contain descriptions of the railway sections: the $$$i$$$-th section description is two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \ne y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are the indices of the stations which are connected by the $$$i$$$-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 5000$$$) — the number of passengers which were asked questions. Then $$$m$$$ lines follow, the $$$j$$$-th line contains three integers $$$a_j$$$, $$$b_j$$$ and $$$g_j$$$ ($$$1 \le a_j, b_j \le n$$$; $$$a_j \ne b_j$$$; $$$1 \le g_j \le 10^6$$$) — the departure station, the arrival station and the minimum scenery beauty along his path.

If there is no answer then print a single integer -1. Otherwise, print $$$n-1$$$ integers $$$f_1, f_2, \dots, f_{n-1}$$$ ($$$1 \le f_i \le 10^6$$$), where $$$f_i$$$ is some valid scenery beauty along the $$$i$$$-th railway section. If there are multiple answers, you can print any of them.

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

string[] tokens;

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

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

const int N = 5000;

int n;
int[N] a, b, c, depth, head, edgeid, value;
int[N << 1] endp, next;

void prepare(int u)
{
    for (int iter = head[u]; ~iter; iter = next[iter])
        if ((iter >> 1) != (edgeid[u] >> 1))
        {
            int v = endp[iter];
            depth[v] = depth[u] + 1;
            edgeid[v] = iter;
            prepare(v);
        }
}

void add_edge(int i, int a, int b)
{
    endp[i] = b, next[i] = head[a], head[a] = i;
}

void main()
{
    int n = readInt;
    for (int i = 0; i < n; ++i)
        head[i] = -1, value[i] = 1;
    for (int i = 0; i < n - 1; ++i)
    {
        int a = readInt - 1;
        int b = readInt - 1;
        add_edge(i << 1, a, b);
        add_edge(i << 1 | 1, b, a);
    }
    depth[0] = edgeid[0] = -1;
    prepare(0);
    int q = readInt;
    for (int i = 0; i < q; ++i)
    {
        a[i] = readInt - 1;
        b[i] = readInt - 1;
        c[i] = readInt;
        int u = a[i], v = b[i];
        while (u != v)
        {
            if (depth[u] > depth[v])
            {
                value[edgeid[u] >> 1] = max(value[edgeid[u] >> 1], c[i]);
                u = endp[edgeid[u] ^ 1];
            }
            else
            {
                value[edgeid[v] >> 1] = max(value[edgeid[v] >> 1], c[i]);
                v = endp[edgeid[v] ^ 1];
            }
        }
    }
    bool ok = true;
    for (int i = 0; i < q; ++i)
    {
        int u = a[i], v = b[i], mi = 1000000;
        while (u != v)
        {
            if (depth[u] > depth[v])
            {
                mi = min(mi, value[edgeid[u] >> 1]);
                u = endp[edgeid[u] ^ 1];
            }
            else
            {
                mi = min(mi, value[edgeid[v] >> 1]);
                v = endp[edgeid[v] ^ 1];
            }
        }
        ok &= mi == c[i];
    }
    if (ok)
        for (int i = 0; i < n - 1; ++i)
            writeln(value[i]);
    else
        writeln(-1);
}

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

string[] tokens;

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

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

const int N = 5000;

int n;
int[N] a, b, c, depth, head, edgeid, value;
int[N << 1] endp, next;

void prepare(int u)
{
    for (int iter = head[u]; ~iter; iter = next[iter])
        if ((iter >> 1) != (edgeid[u] >> 1))
        {
            int v = endp[iter];
            depth[v] = depth[u] + 1;
            edgeid[v] = iter;
            prepare(v);
        }
}

void add_edge(int i, int a, int b)
{
    endp[i] = b, next[i] = head[a], head[a] = i;
}

void main()
{
    int n = readInt;
    for (int i = 0; i < n; ++i)
        head[i] = -1;
    for (int i = 0; i < n - 1; ++i)
    {
        int a = readInt - 1;
        int b = readInt - 1;
        add_edge(i << 1, a, b);
        add_edge(i << 1 | 1, b, a);
    }
    depth[0] = edgeid[0] = -1;
    prepare(0);
    int q = readInt;
    for (int i = 0; i < q; ++i)
    {
        a[i] = readInt - 1;
        b[i] = readInt - 1;
        c[i] = readInt;
        int u = a[i], v = b[i];
        while (u != v)
        {
            if (depth[u] > depth[v])
            {
                value[edgeid[u] >> 1] = max(value[edgeid[u] >> 1], c[i]);
                u = endp[edgeid[u] ^ 1];
            }
            else
            {
                value[edgeid[v] >> 1] = max(value[edgeid[v] >> 1], c[i]);
                v = endp[edgeid[v] ^ 1];
            }
        }
    }
    bool ok = true;
    for (int i = 0; i < q; ++i)
    {
        int u = a[i], v = b[i], mi = 1000000;
        while (u != v)
        {
            if (depth[u] > depth[v])
            {
                mi = min(mi, value[edgeid[u] >> 1]);
                u = endp[edgeid[u] ^ 1];
            }
            else
            {
                mi = min(mi, value[edgeid[v] >> 1]);
                v = endp[edgeid[v] ^ 1];
            }
        }
        ok &= mi == c[i];
    }
    if (ok)
        for (int i = 0; i < n - 1; ++i)
            writeln(value[i]);
    else
        writeln(-1);
}


The biggest event of the year – Cota 2 world championship "The Innernational" is right around the corner. $$$2^n$$$ teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from $$$1$$$ to $$$2^n$$$ and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with $$$2^{n-1}$$$ teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round $$$2^k$$$ teams play a game with each other (teams are split into games by team numbers). $$$2^{k-1}$$$ loosing teams are eliminated from the championship, $$$2^{k-1}$$$ winning teams are playing $$$2^{k-1}$$$ teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have $$$2^{k-1}$$$ teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers $$$a_1, a_2, ..., a_k$$$. You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?

First input line has two integers $$$n, k$$$ — $$$2^n$$$ teams are competing in the championship. You are a fan of $$$k$$$ teams ($$$2 \le n \le 17; 0 \le k \le 2^n$$$). Second input line has $$$k$$$ distinct integers $$$a_1, \ldots, a_k$$$ — numbers of teams you're a fan of ($$$1 \le a_i \le 2^n$$$).

Output single integer — maximal possible number of championship games that include teams you're fan of.

NoteOn the image, each game of the championship is denoted with an English letter ($$$a$$$ to $$$n$$$). Winner of game $$$i$$$ is denoted as $$$Wi$$$, loser is denoted as $$$Li$$$. Teams you're a fan of are highlighted with red background.In the first example, team $$$6$$$ will play in 6 games if it looses the first upper bracket game (game $$$c$$$) and wins all lower bracket games (games $$$h, j, l, m$$$). In the second example, teams $$$7$$$ and $$$8$$$ have to play with each other in the first game of upper bracket (game $$$d$$$). Team $$$8$$$ can win all remaining games in upper bracket, when teams $$$1$$$ and $$$7$$$ will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship.

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

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

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

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

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

      auto fav = new int[1 << N];
      foreach (k; 0 .. K) {
        fav[A[k]] = 1;
      }

      auto dp = new int[][][][](N + 1);
      dp[1] = new int[][][](1 << (N - 1), 2, 2);
      foreach (i; 0 .. 1 << (N - 1)) {
        foreach (s; 0 .. 2) foreach (t; 0 .. 2) {
          dp[1][i][s][t] = -1;
        }
        const f0 = fav[i << 1 | 0];
        const f1 = fav[i << 1 | 1];
        chmax(dp[1][i][f0][f1], f0 | f1);
        chmax(dp[1][i][f1][f0], f0 | f1);
      }
      foreach (e; 2 .. N + 1) {
        dp[e] = new int[][][](1 << (N - e), 2, 2);
        foreach (i; 0 .. 1 << (N - e)) {
          foreach (s; 0 .. 2) foreach (t; 0 .. 2) {
            dp[e][i][s][t] = -1;
          }
          foreach (s0; 0 .. 2) foreach (t0; 0 .. 2) {
            foreach (s1; 0 .. 2) foreach (t1; 0 .. 2) {
              const d0 = dp[e - 1][i << 1 | 0][s0][t0];
              const d1 = dp[e - 1][i << 1 | 1][s1][t1];
              if (d0 >= 0 && d1 >= 0) {
                const score = d0 + d1 + (s0 | s1) + (t0 | t1);
                chmax(dp[e][i][s0][s1 | t0 | t1], score + (s1 | t0 | t1));
                chmax(dp[e][i][s1][s0 | t0 | t1], score + (s0 | t0 | t1));
              }
            }
          }
        }
      }

      int ans = -1;
      foreach (s; 0 .. 2) foreach (t; 0 .. 2) {
        const d = dp[N][0][s][t];
        if (d >= 0) {
          chmax(ans, d + (s | t));
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto xs = new int[1 << N];
      auto ys = new int[1 << (N - 1)];
      foreach (i; 0 .. K) {
        xs[A[i]] = 1;
      }

      int ans;
      foreach_reverse (e; 1 .. N) {
        debug {
          writeln(xs, " ", ys);
        }
        auto xxs = new int[1 << e];
        auto yys = new int[1 << max(e - 1, 0)];
        foreach (i; 0 .. 1 << (e - 1)) {
          int a = xs[i << 2 | 0];
          int b = xs[i << 2 | 1];
          int c = xs[i << 2 | 2];
          int d = xs[i << 2 | 3];
          int p = ys[i << 1 | 0];
          int q = ys[i << 1 | 1];
          int mx = -1;
          int sm = -1;
          foreach (s; 0 .. 4) {
            int aa = a, bb = b, cc = c, dd = d;
            if (s & 1) swap(aa, bb);
            if (s & 2) swap(cc, dd);
            int score;
            if (aa | bb) ++score;
            if (cc | dd) ++score;
            if (e < N - 1 && bb | p) ++score;
            if (e < N - 1 && dd | q) ++score;
            if ((bb | p) | (dd | q)) ++score;
            score *= 1000;
            if ((bb | p) | (dd | q)) score += 100;
            if (aa | cc) score += 10;
            if (aa & cc) score += 1;
            if (chmax(mx, score)) {
              sm = s;
            }
          }
          if (sm & 1) swap(a, b);
          if (sm & 2) swap(c, d);
          if (a | b) ++ans;
          if (c | d) ++ans;
          if (e < N - 1 && b | p) ++ans;
          if (e < N - 1 && d | q) ++ans;
          if ((b | p) | (d | q)) ++ans;
          xxs[i << 1 | 0] = a;
          xxs[i << 1 | 1] = c;
          yys[i] = (b | p) | (d | q);
        }
        xs = xxs;
        ys = yys;
      }
      {
        debug {
          writeln(xs, " ", ys);
        }
        const a = xs[0];
        const b = xs[1];
        const p = ys[0];
        int tmp;
        chmax(tmp, (a | b) + (b | p) + (a | b));
        chmax(tmp, (a | b) + (b | p) + (a | p));
        chmax(tmp, (a | b) + (a | p) + (b | a));
        chmax(tmp, (a | b) + (a | p) + (b | p));
        ans += tmp;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto xs = new int[1 << N];
      auto ys = new int[1 << (N - 1)];
      foreach (i; 0 .. K) {
        xs[A[i]] = 1;
      }

      int ans;
      foreach_reverse (e; 1 .. N) {
        debug {
          writeln(xs, " ", ys);
        }
        auto xxs = new int[1 << e];
        auto yys = new int[1 << max(e - 1, 0)];
        foreach (i; 0 .. 1 << (e - 1)) {
          int a = xs[i << 2 | 0];
          int b = xs[i << 2 | 1];
          int c = xs[i << 2 | 2];
          int d = xs[i << 2 | 3];
          int p = ys[i << 1 | 0];
          int q = ys[i << 1 | 1];
          int mx = -1;
          int sm = -1;
          foreach (s; 0 .. 4) {
            int aa = a, bb = b, cc = c, dd = d;
            if (s & 1) swap(aa, bb);
            if (s & 2) swap(cc, dd);
            int score;
            if (aa | bb) ++score;
            if (cc | dd) ++score;
            if (e < N - 1 && bb | p) ++score;
            if (e < N - 1 && dd | q) ++score;
            if ((bb | p) | (dd | q)) ++score;
            score *= 1000;
            if ((bb | p) | (dd | q)) score += 1;
            if (aa | cc) score += 100;
            if (aa & cc) score += 10;
            if (chmax(mx, score)) {
              sm = s;
            }
          }
          if (sm & 1) swap(a, b);
          if (sm & 2) swap(c, d);
          if (a | b) ++ans;
          if (c | d) ++ans;
          if (e < N - 1 && b | p) ++ans;
          if (e < N - 1 && d | q) ++ans;
          if ((b | p) | (d | q)) ++ans;
          xxs[i << 1 | 0] = a;
          xxs[i << 1 | 1] = c;
          yys[i] = (b | p) | (d | q);
        }
        xs = xxs;
        ys = yys;
      }
      {
        debug {
          writeln(xs, " ", ys);
        }
        const a = xs[0];
        const b = xs[1];
        const p = ys[0];
        int tmp;
        chmax(tmp, (a | b) + (b | p) + (a | b));
        chmax(tmp, (a | b) + (b | p) + (a | p));
        chmax(tmp, (a | b) + (a | p) + (b | a));
        chmax(tmp, (a | b) + (a | p) + (b | p));
        ans += tmp;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto xs = new int[1 << N];
      auto ys = new int[1 << (N - 1)];
      foreach (i; 0 .. K) {
        xs[A[i]] = 1;
      }

      int ans;
      foreach_reverse (e; 1 .. N) {
        debug {
          writeln(xs, " ", ys);
        }
        auto xxs = new int[1 << e];
        auto yys = new int[1 << max(e - 1, 0)];
        foreach (i; 0 .. 1 << (e - 1)) {
          int a = xs[i << 2 | 0];
          int b = xs[i << 2 | 1];
          int c = xs[i << 2 | 2];
          int d = xs[i << 2 | 3];
          int p = ys[i << 1 | 0];
          int q = ys[i << 1 | 1];
          int mx = -1;
          int sm = -1;
          foreach (s; 0 .. 4) {
            int aa = a, bb = b, cc = c, dd = d;
            if (s & 1) swap(aa, bb);
            if (s & 2) swap(cc, dd);
            int score;
            if (aa | bb) ++score;
            if (cc | dd) ++score;
            if (e < N - 1 && bb | p) ++score;
            if (e < N - 1 && dd | q) ++score;
            if ((bb | p) | (dd | q)) ++score;
            score *= 1000;
            if ((bb | p) | (dd | q)) score += 10;
            if (aa | cc) score += 100;
            if (aa & cc) score += 1;
            if (chmax(mx, score)) {
              sm = s;
            }
          }
          if (sm & 1) swap(a, b);
          if (sm & 2) swap(c, d);
          if (a | b) ++ans;
          if (c | d) ++ans;
          if (e < N - 1 && b | p) ++ans;
          if (e < N - 1 && d | q) ++ans;
          if ((b | p) | (d | q)) ++ans;
          xxs[i << 1 | 0] = a;
          xxs[i << 1 | 1] = c;
          yys[i] = (b | p) | (d | q);
        }
        xs = xxs;
        ys = yys;
      }
      {
        debug {
          writeln(xs, " ", ys);
        }
        const a = xs[0];
        const b = xs[1];
        const p = ys[0];
        int tmp;
        chmax(tmp, (a | b) + (b | p) + (a | b));
        chmax(tmp, (a | b) + (b | p) + (a | p));
        chmax(tmp, (a | b) + (a | p) + (b | a));
        chmax(tmp, (a | b) + (a | p) + (b | p));
        ans += tmp;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto xs = new int[1 << N];
      auto ys = new int[1 << (N - 1)];
      foreach (i; 0 .. K) {
        xs[A[i]] = 1;
      }

      int ans;
      foreach_reverse (e; 1 .. N) {
        debug {
          writeln(xs, " ", ys);
        }
        auto xxs = new int[1 << e];
        auto yys = new int[1 << max(e - 1, 0)];
        foreach (i; 0 .. 1 << (e - 1)) {
          int a = xs[i << 2 | 0];
          int b = xs[i << 2 | 1];
          int c = xs[i << 2 | 2];
          int d = xs[i << 2 | 3];
          int p = ys[i << 1 | 0];
          int q = ys[i << 1 | 1];
          if (a < b) swap(a, b);
          if (c < d) swap(c, d);
          if (p == 0 && q == 0 && a > b) swap(a, b);
          if (p == 0 && q == 0 && c > d && b == 0) swap(c, d);
          debug {
            writeln("  ", [a, b, c, d], " ", [p, q]);
          }
          if (a | b) ++ans;
          if (c | d) ++ans;
          if (e < N - 1 && b | p) ++ans;
          if (e < N - 1 && d | q) ++ans;
          if ((b | p) | (d | q)) ++ans;
          xxs[i << 1 | 0] = a;
          xxs[i << 1 | 1] = c;
          yys[i] = (b | p) | (d | q);
        }
        xs = xxs;
        ys = yys;
      }
      {
        debug {
          writeln(xs, " ", ys);
        }
        const a = xs[0];
        const b = xs[1];
        const p = ys[0];
        int tmp;
        chmax(tmp, (a | b) + (b | p) + (a | b));
        chmax(tmp, (a | b) + (b | p) + (a | p));
        chmax(tmp, (a | b) + (a | p) + (b | a));
        chmax(tmp, (a | b) + (a | p) + (b | p));
        ans += tmp;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto xs = new int[1 << N];
      auto ys = new int[1 << (N - 1)];
      foreach (i; 0 .. K) {
        xs[A[i]] = 1;
      }

      int ans;
      foreach_reverse (e; 1 .. N) {
        debug {
          writeln(xs, " ", ys);
        }
        auto xxs = new int[1 << e];
        auto yys = new int[1 << max(e - 1, 0)];
        foreach (i; 0 .. 1 << (e - 1)) {
          int a = xs[i << 2 | 0];
          int b = xs[i << 2 | 1];
          int c = xs[i << 2 | 2];
          int d = xs[i << 2 | 3];
          int p = ys[i << 1 | 0];
          int q = ys[i << 1 | 1];
          if (a > b) swap(a, b);
          if (c > d) swap(c, d);
          if ((p | q | d) && a < b) swap(a, b);
          if ((p | q | b) && c < d) swap(c, d);
          if (a | b) ++ans;
          if (c | d) ++ans;
          if (e < N - 1 && b | p) ++ans;
          if (e < N - 1 && d | q) ++ans;
          if ((b | p) | (d | q)) ++ans;
          xxs[i << 1 | 0] = a;
          xxs[i << 1 | 1] = c;
          yys[i] = (b | p) | (d | q);
        }
        xs = xxs;
        ys = yys;
      }
      {
        debug {
          writeln(xs, " ", ys);
        }
        const a = xs[0];
        const b = xs[1];
        const p = ys[0];
        int tmp;
        chmax(tmp, (a | b) + (b | p) + (a | b));
        chmax(tmp, (a | b) + (b | p) + (a | p));
        chmax(tmp, (a | b) + (a | p) + (b | a));
        chmax(tmp, (a | b) + (a | p) + (b | p));
        ans += tmp;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto xs = new int[1 << N];
      auto ys = new int[1 << (N - 1)];
      foreach (i; 0 .. K) {
        xs[A[i]] = 1;
      }

      int ans;
      foreach_reverse (e; 1 .. N) {
        debug {
          writeln(xs, " ", ys);
        }
        auto xxs = new int[1 << e];
        auto yys = new int[1 << max(e - 1, 0)];
        foreach (i; 0 .. 1 << (e - 1)) {
          int a = xs[i << 2 | 0];
          int b = xs[i << 2 | 1];
          int c = xs[i << 2 | 2];
          int d = xs[i << 2 | 3];
          int p = ys[i << 1 | 0];
          int q = ys[i << 1 | 1];
          if (a < b) swap(a, b);
          if (c < d) swap(c, d);
          if (p == 0 && a > b) swap(a, b);
          if (q == 0 && c > d) swap(c, d);
          debug {
            writeln("  ", [a, b, c, d], " ", [p, q]);
          }
          if (p == 0 && q == 0 && a < b && c < d) swap(a, b);
          debug {
            writeln("  ", [a, b, c, d], " ", [p, q]);
          }
          if (a | b) ++ans;
          if (c | d) ++ans;
          if (e < N - 1 && b | p) ++ans;
          if (e < N - 1 && d | q) ++ans;
          if ((b | p) | (d | q)) ++ans;
          xxs[i << 1 | 0] = a;
          xxs[i << 1 | 1] = c;
          yys[i] = (b | p) | (d | q);
        }
        xs = xxs;
        ys = yys;
      }
      {
        debug {
          writeln(xs, " ", ys);
        }
        const a = xs[0];
        const b = xs[1];
        const p = ys[0];
        int tmp;
        chmax(tmp, (a | b) + (b | p) + (a | b));
        chmax(tmp, (a | b) + (b | p) + (a | p));
        chmax(tmp, (a | b) + (a | p) + (b | a));
        chmax(tmp, (a | b) + (a | p) + (b | p));
        ans += tmp;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}