In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with n - k + 1 strings s1, s2, ..., sn - k + 1, each either "YES" or "NO".   The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise).  The string s2 describes a group of soldiers 2 through k + 1.  And so on, till the string sn - k + 1 that describes a group of soldiers n - k + 1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing names — it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution.

The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 50) — the number of soldiers and the size of a group respectively. The second line contains n - k + 1 strings s1, s2, ..., sn - k + 1. The string si is "YES" if the group of soldiers i through i + k - 1 is effective, and "NO" otherwise.

Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them.

Adam Bob Bob Cpqepqwer Limak Adam Bob Adam

R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc

NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output:  First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO".  Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO".  Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES".  ...,  Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO".

/+ dub.sdl:
    name "A"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.range, std.algorithm, std.conv;
// import dcomp.scanner;

string genNewName() {
    static int id = 424;
    id++;
    return "Sugim" ~ id.to!string.map!(x => cast(char)(x-'0'+'a')).array.idup;
}

int main() {
    auto sc = new Scanner(stdin);
    int n, k;
    sc.read(n, k);
    string[] v;
    sc.read(v);
    string[] ans;
    foreach(i; 0..k-1) {
        ans ~= genNewName();
    }
    foreach (s; v) {
        if (s == "YES") {
            ans ~= genNewName();
        } else {
            string u = ans[$-k+1];
            ans ~= u;
        }
    }
    writeln(ans.join(" "));
    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    string[] buf;
    private bool succ() {
        while (!buf.length) {
            if (f.eof) return false;
            buf = f.readln.split;
        }
        return true;
    }
    private bool readSingle(T)(ref T x) {
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {
                //string or char[10] etc
                x = buf.front;
                buf.popFront;
            } else {
                static if (isStaticArray!T) {
                    //static
                    assert(buf.length == T.length);
                }
                x = buf.map!(to!E).array;
                buf.length = 0;
            }
        } else {
            x = buf.front.to!T;
            buf.popFront;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

unittest {
    import std.path : buildPath;
    import std.file : tempDir;
    import std.algorithm : equal;
    import std.stdio : File;
    string fileName = buildPath(tempDir, "kyuridenanmaida.txt");
    auto fout = File(fileName, "w");
    fout.writeln("1 2 3");
    fout.writeln("ab cde");
    fout.writeln("1.0 1.0 2.0");
    fout.close;
    Scanner sc = new Scanner(File(fileName, "r"));
    int a;
    int[2] b;
    char[2] c;
    string d;
    double e;
    double[] f;
    sc.read(a, b, c, d, e, f);
    assert(a == 1);
    assert(equal(b[], [2, 3]));
    assert(equal(c[], "ab"));
    assert(equal(d, "cde"));
    assert(e == 1.0);
    assert(equal(f, [1.0, 2.0]));
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.split;
		string [] s;
		foreach (i; 0..n)
		{
			s ~= "" ~
			    cast (char) ('A' + i % 10) ~
			    cast (char) ('a' + i / 10);
		}
		foreach (i; 0..n - k + 1)
		{
			if (a[i] == "NO")
			{
				s[i + k - 1] = s[i];
			}
		}
		writefln ("%-(%s %)", s);
	}
}

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 S = new string[N - K + 1];
      foreach (i; 0 .. N - K + 1) {
        S[i] = readToken();
      }

      auto ans = new string[N];
      foreach (i; 0 .. N) {
        ans[i] ~= cast(char)('A' + i / 26);
        ans[i] ~= cast(char)('a' + i % 26);
        if (i - (K - 1) >= 0 && S[i - (K - 1)] == "NO") {
          ans[i] = ans[i - (K - 1)];
        }
      }

      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;
    }
  } catch (EOFException e) {
  }
}

/+ dub.sdl:
    name "A"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.range, std.algorithm, std.conv;
// import dcomp.scanner;

string genNewName() {
    static int id = 424;
    id++;
    return "sugim" ~ id.to!string.map!(x => cast(char)(x-'0'+'a')).array.idup;
}

int main() {
    auto sc = new Scanner(stdin);
    int n, k;
    sc.read(n, k);
    string[] v;
    sc.read(v);
    string[] ans;
    foreach(i; 0..k-1) {
        ans ~= genNewName();
    }
    foreach (s; v) {
        if (s == "YES") {
            ans ~= genNewName();
        } else {
            string u = ans[$-k+1];
            ans ~= u;
        }
    }
    writeln(ans.join(" "));
    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    string[] buf;
    private bool succ() {
        while (!buf.length) {
            if (f.eof) return false;
            buf = f.readln.split;
        }
        return true;
    }
    private bool readSingle(T)(ref T x) {
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {
                //string or char[10] etc
                x = buf.front;
                buf.popFront;
            } else {
                static if (isStaticArray!T) {
                    //static
                    assert(buf.length == T.length);
                }
                x = buf.map!(to!E).array;
                buf.length = 0;
            }
        } else {
            x = buf.front.to!T;
            buf.popFront;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

unittest {
    import std.path : buildPath;
    import std.file : tempDir;
    import std.algorithm : equal;
    import std.stdio : File;
    string fileName = buildPath(tempDir, "kyuridenanmaida.txt");
    auto fout = File(fileName, "w");
    fout.writeln("1 2 3");
    fout.writeln("ab cde");
    fout.writeln("1.0 1.0 2.0");
    fout.close;
    Scanner sc = new Scanner(File(fileName, "r"));
    int a;
    int[2] b;
    char[2] c;
    string d;
    double e;
    double[] f;
    sc.read(a, b, c, d, e, f);
    assert(a == 1);
    assert(equal(b[], [2, 3]));
    assert(equal(c[], "ab"));
    assert(equal(d, "cde"));
    assert(e == 1.0);
    assert(equal(f, [1.0, 2.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 main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      auto S = new string[N - K + 1];
      foreach (i; 0 .. N - K + 1) {
        S[i] = readToken();
      }

      auto ans = new string[N];
      foreach (i; 0 .. N) {
        ans[i] ~= cast(char)('a' + i / 26);
        ans[i] ~= cast(char)('a' + i % 26);
        if (i - K >= 0 && S[i - K] == "NO") {
          ans[i] = ans[i - K];
        }
      }

      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto ans = new string[N];
      foreach (i; 0 .. N) {
        ans[i] ~= cast(char)('a' + i / 26);
        ans[i] ~= cast(char)('a' + i % 26);
        if (i - (K - 1) >= 0 && S[i - (K - 1)] == "NO") {
          ans[i] = ans[i - (K - 1)];
        }
      }

      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;
    }
  } catch (EOFException e) {
  }
}


Vova had a pretty weird sleeping schedule. There are $$$h$$$ hours in a day. Vova will sleep exactly $$$n$$$ times. The $$$i$$$-th time he will sleep exactly after $$$a_i$$$ hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is $$$0$$$). Each time Vova sleeps exactly one day (in other words, $$$h$$$ hours).Vova thinks that the $$$i$$$-th sleeping time is good if he starts to sleep between hours $$$l$$$ and $$$r$$$ inclusive.Vova can control himself and before the $$$i$$$-th time can choose between two options: go to sleep after $$$a_i$$$ hours or after $$$a_i - 1$$$ hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.

The first line of the input contains four integers $$$n, h, l$$$ and $$$r$$$ ($$$1 \le n \le 2000, 3 \le h \le 2000, 0 \le l \le r < h$$$) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i < h$$$), where $$$a_i$$$ is the number of hours after which Vova goes to sleep the $$$i$$$-th time.

Print one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.

NoteThe maximum number of good times in the example is $$$3$$$.The story starts from $$$t=0$$$. Then Vova goes to sleep after $$$a_1 - 1$$$ hours, now the time is $$$15$$$. This time is not good. Then Vova goes to sleep after $$$a_2 - 1$$$ hours, now the time is $$$15 + 16 = 7$$$. This time is also not good. Then Vova goes to sleep after $$$a_3$$$ hours, now the time is $$$7 + 14 = 21$$$. This time is good. Then Vova goes to sleep after $$$a_4 - 1$$$ hours, now the time is $$$21 + 19 = 16$$$. This time is not good. Then Vova goes to sleep after $$$a_5$$$ hours, now the time is $$$16 + 20 = 12$$$. This time is not good. Then Vova goes to sleep after $$$a_6$$$ hours, now the time is $$$12 + 11 = 23$$$. This time is good. Then Vova goes to sleep after $$$a_7$$$ hours, now the time is $$$23 + 22 = 21$$$. This time is also good.

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

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

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

    auto dp = new int[][] (n, h);
    foreach (i; n.iota) { dp[i][] = -1; }

    int score(int idx, int ch) {
        if (idx == n) { return 0; }
        if (dp[idx][ch] != -1) { return dp[idx][ch]; }

        int h1 = (ch + arr[idx] - 1) % h;
        int h2 = (ch + arr[idx]) % h;

        auto isGood = (int v) => le <= v && v <= r ? 1 : 0;

        auto good1 = isGood(h1);
        auto good2 = isGood(h2);

        return dp[idx][ch] = max(good1 + score(idx+1, h1), good2 + score(idx+1, h2));
    }

    auto ans = score(0, 0);

    ans.writeln;
}

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

void main()
{
    auto nhlr = readln.split.to!(int[]);
    auto N = nhlr[0];
    auto H = nhlr[1];
    auto L = nhlr[2];
    auto R = nhlr[3];
    auto as = readln.split.to!(int[]);

    auto DP = new int[][](N, H);
    foreach (ref dp; DP) dp[] = -1;
    int solve(int i, int h) {
        if (i == N) return 0;
        if (DP[i][h] == -1) {
            auto r1 = (h + as[i]) % H;
            auto r2 = (h + as[i] - 1) % H;
            DP[i][h] = max(
                solve(i+1, r1) + (L <= r1 && r1 <= R ? 1 : 0),
                solve(i+1, r2) + (L <= r2 && r2 <= R ? 1 : 0)
            );
        }
        return DP[i][h];
    }
    writeln(solve(0, 0));
}

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 = 998244353;
//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 n = RD!int;
	auto h = RD!int;
	auto l = RD!int;
	auto r = RD!int+1;
	auto a = RDA!int;

	auto dp = new int[](h);
	dp[] = -1;
	dp[0] = 0;
	foreach (i; 0..n)
	{
		auto ndp = new int[](h);
		ndp[] = -1;
		foreach (j; 0..h)
		{
			if (dp[j] == -1) continue;
			int nc1 = dp[j], nc2 = dp[j];
			auto t1 = (j+a[i]) % h;
			auto t2 = (j+a[i]-1) % h;
			if (inside(t1, l, r))
				++nc1;
			if (inside(t2, l, r))
				++nc2;
			ndp[t1].chmax(nc1);
			ndp[t2].chmax(nc2);
		}
		dp = ndp;
	}

	auto pos = dp.MIN_POS!"a > b";
	writeln(dp[pos]);
	stdout.flush;
	debug readln;
}


A sequence of $$$n$$$ numbers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences [$$$3, 1, 4, 2$$$], [$$$1$$$] and [$$$2,1$$$] are permutations, but [$$$1,2,1$$$], [$$$0,1$$$] and [$$$1,3,4$$$] — are not.Polycarp lost his favorite permutation and found only some of its elements — the numbers $$$b_1, b_2, \dots b_m$$$. He is sure that the sum of the lost elements equals $$$s$$$.Determine whether one or more numbers can be appended to the given sequence $$$b_1, b_2, \dots b_m$$$ such that the sum of the added numbers equals $$$s$$$, and the resulting new array is a permutation?

The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) —the number of test cases.  Then the descriptions of the test cases follow. The first line of each test set contains two integers $$$m$$$ and $$$s$$$ ($$$1 \le m \le 50$$$, $$$1 \le s \le 1000$$$)—-the number of found elements and the sum of forgotten numbers. The second line of each test set contains $$$m$$$ different integers $$$b_1, b_2 \dots b_m$$$ ($$$1 \le b_i \le 50$$$) — the elements Polycarp managed to find.

Print $$$t$$$ lines, each of which is the answer to the corresponding test set. Print as the answer YES if you can append several elements to the array $$$b$$$, that their sum equals $$$s$$$ and the result will be a permutation. Output NO otherwise. You can output the answer in any case (for example, yEs, yes, Yes and YES will be recognized as positive answer).

NoteIn the test case of the example, $$$m=3, s=13, b=[3,1,4]$$$. You can append to $$$b$$$ the numbers $$$6,2,5$$$, the sum of which is $$$6+2+5=13$$$. Note that the final array will become $$$[3,1,4,6,2,5]$$$, which is a permutation.In the second test case of the example, $$$m=1, s=1, b=[1]$$$. You cannot append one or more numbers to $$$[1]$$$ such that their sum equals $$$1$$$ and the result is a permutation.In the third test case of the example, $$$m=3, s=3, b=[1,4,2]$$$. You can append the number $$$3$$$ to $$$b$$$. Note that the resulting array will be $$$[1,4,2,3]$$$, which is a permutation.

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;

bool trysolve(bool[] vis, int n, long s)
{
  long rs = 0;
  foreach (i ; 0 .. n) {
    if (!vis[i])
      rs += i + 1;
  }
  foreach (i ; n .. 100) {
    if (vis[i])
      return false;
  }
  return rs == s;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int m, s;
    readf!" %d %d "(m, s);
    auto a = readln.splitter.map!(to!int).array;
    auto vis = new bool[100];
    foreach (x ; a) {
      vis[x - 1] = true;
    }
    bool good = false;
    foreach (n ; (a.length + 1).to!int .. 100 + 1) {
      if (trysolve(vis, n, s)) {
        good = true;
        break;
      }
    }
    writeln(good ? "YES" : "NO");
  }
}

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

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

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

void solve() {
    int m, s;
    readf!" %d %d "(m,s);
    bool good = false;
    auto b = readarray!int;
    auto mb = maxElement(b);
    auto sb = sum(b);
    auto curS = sum(iota(mb + 1));
    while (curS <= sb + s) {
        if (curS == sb + s) {
            good = true;
            break;
        }
        mb++;
        curS += mb;
    }
    if (good)
        writeln("yes");
    else
        writeln("no");
}

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

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

bool solve (int m, int s, int [] a)
{
	auto hi = a.maxElement;
	auto vis = new bool [hi + 1];
	foreach (ref c; a)
	{
		if (vis[c])
		{
			return false;
		}
		vis[c] = true;
	}
	foreach (i; 1..hi + 1)
	{
		if (!vis[i])
		{
			s -= i;
		}
	}
	while (s > 0)
	{
		hi += 1;
		s -= hi;
	}
	return (s == 0);
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int m, s;
		readf !(" %s %s") (m, s);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		writeln (solve (m, s, a) ? "YES" : "NO");
	}
}

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

bool trysolve(bool[] vis, int n, long s)
{
  long rs = 0;
  foreach (i ; 0 .. n) {
    if (!vis[i])
      rs += i + 1;
  }
  foreach (i ; n .. 50) {
    if (vis[i])
      return false;
  }
  return rs == s;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int m, s;
    readf!" %d %d "(m, s);
    auto a = readln.splitter.map!(to!int).array;
    auto vis = new bool[50];
    foreach (x ; a) {
      vis[x - 1] = true;
    }
    bool good = false;
    foreach (n ; (a.length + 1).to!int .. 50 + 1) {
      if (trysolve(vis, n, s)) {
        good = true;
        break;
      }
    }
    writeln(good ? "YES" : "NO");
  }
}

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int m, s;
    readf!" %d %d "(m, s);
    auto a = readln.splitter.map!(to!int).array;
    auto vis = new bool[50];
    int mx = 0;
    foreach (x ; a) {
      vis[x - 1] = true;
      mx = max(mx, x);
    }
    long rs = 0;
    bool good = false;
    foreach (i ; 0 .. vis.length) {
      if (!vis[i])
        rs += i + 1;
      if (i + 1 >= mx && rs == s) {
        good = true;
        break;
      }
    }
    writeln(s == rs ? "YES" : "NO");
  }
}


Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations:  Choose a number and delete it with cost x.  Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.

First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.

Print a single integer: the minimum possible cost to make the list good.

NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.

import std.stdio;
import std.file;
import std.algorithm;
import std.typecons;
import std.math;
import std.random;
import std.container.rbtree;
import std.string;
import std.conv;
import std.bigint;

const int N = 1000001;

void main()
{
	int n;
	long x, y;
	scanf("%d", &n);
	scanf("%lld", &x);
	scanf("%lld", &y);

	int[] list = new int[n];

	foreach(i; 0..n)
		scanf("%d", &list[i]);

	bool[] pr = new bool[N];

	list.sort();

	foreach(i; 2..N - 1)
		pr[i] = true;

	for (int i = 2; i * i < N; i++)
		if (pr[i])
			for (int j = i * i; j < N; j += i)
				pr[j] = false;

	long[] psum = new long[N];
	psum[0] = list[0];

	foreach(i; 1..n)
		psum[i] = list[i] + psum[i - 1];

	long get(int l, int r)
	{
		return psum[r] - (l > 0 ? psum[l - 1] : 0);
	}

	long ans = x * n;

	for (long d = 2; d < N; d++)
		if (pr[cast(int)d])
		{
			long curr = 0;

			for (int j = 0; j < n; )
			{
				long k = list[j] / d - (list[j] % d == 0 ? 1 : 0);

				int L = j, R = n;

				while (L < R - 1)
				{
					int M = (L + R) / 2;
					if (list[M] > k * d + d)
						R = M;
					else
						L = M;
				}

				R = L;
				int l = j, r = R, pos = -1;
				while (l <= r)
				{
					int m = (l + r) / 2;
					if ((k * d + d - list[m]) * y <= x)
						r = m - 1;
					else
						pos = m, l = m + 1;
				}

				L = j;
				j = R + 1;

				if (pos != -1)
					curr += x * (pos - L + 1) + y * ((k * d + d) * (R - pos) - get(pos + 1, R));
				else
					curr += y * ((k * d + d) * (R - L + 1) - get(L, R));
				k++;
			}

			ans = min(ans, curr);
		}

	writeln(ans);

	//stdin.readln();
	//stdin.readln();
}

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

void main() {
    auto s = readln.split.map!(to!long);
    auto N = s[0].to!int;
    auto X = s[1];
    auto Y = s[2];
    auto A = readln.split.map!(to!int).array;
    A.sort();

    const int MAX = 10^^6 + 1;
    const int border = ((X - 1) / Y).to!int;

    auto cnt = new long[](MAX * 2);
    auto cntsum = new long[](MAX * 2);

    foreach (i; 0..N)
        cnt[A[i]] += 1;
    foreach (i; 0..MAX*2-1)
        cnt[i + 1] += cnt[i];
    foreach (i; 0..MAX*2-1)
        cntsum[i + 1] += cntsum[i] + cnt[i + 1];

    long ans = 1L << 59;

    foreach (g; 2..MAX) {
        long tmp = 0;
        for (int l = 1; l < MAX; l += g) {
            int r = l + g - 1;
            int m = max(l, r - border);
            long y = Y * (cntsum[r - 1] - cntsum[m - 1] - cnt[m - 1] * (r - m));
            long x = X * (cnt[m - 1] - cnt[l - 1]);
            tmp += x + y;
        }
        ans = min(ans, tmp);
    }

    debug {
        cnt[0..20].writeln;
        cntsum[0..20].writeln;
    }

    ans.writeln;
}

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

enum LIM = 10^^6 + 100;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const X = readLong();
      const Y = readLong();
      auto A = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
      }
      A.sort;

      auto lpf = iota(LIM).array;
      foreach (p; 2 .. LIM) {
        if (lpf[p] == p) {
          for (int n = 2 * p; n < LIM; n += p) {
            chmin(lpf[n], p);
          }
        }
      }

      auto freq = new int[LIM];
      foreach (i; 0 .. N) {
        for (int a = A[i]; a > 1; ) {
          const p = lpf[a];
          ++freq[p];
          do {
            a /= p;
          } while (a % p == 0);
        }
      }

      long ans = N * X;
      foreach (p; 2 .. LIM) {
        if (ans > (N - freq[p]) * min(X, Y)) {
          long cost;
          foreach (i; 0 .. N) {
            const r = A[i] % p;
            if (r != 0) {
              cost += min(X, Y * (p - r));
              if (ans < cost) {
                break;
              }
            }
          }
          chmin(ans, cost);
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

void main() {
    auto s = readln.split.map!(to!long);
    auto N = s[0].to!int;
    auto X = s[1];
    auto Y = s[2];
    auto A = readln.split.map!(to!long).array;

    const int MAX = 10^^6 + 1;
    auto table = new long[MAX];
    fill(table, true);
    table[0] = table[1] = false;
    long[] P;

    for (int i = 2; i * i < MAX; ++i) {
        if (table[i]) {
            P ~= i;
            for (int j = i + i; j * j < MAX; j += i)
                table[j] = false;
        }
    }

    long ans = 1L << 59;

    foreach (p; P) {
        long tmp = 0;
        foreach (a; A)
            tmp += min(X, (a % p) * Y);
        ans = min(ans, tmp);
    }

    long tmp = 0;
    long m = A.reduce!max;
    foreach (a; A)
        tmp += min(X, (m - a) * Y);
    ans = min(ans, tmp);

    ans.writeln;
}

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

void main() {
    auto s = readln.split.map!(to!long);
    auto N = s[0].to!int;
    auto X = s[1];
    auto Y = s[2];
    auto A = readln.split.map!(to!int).array;
    A.sort();

    const int MAX = 10^^6 + 1;
    const int border = ((X - 1) / Y + 1).to!int;

    auto cnt = new long[](MAX * 2);
    auto cntsum = new long[](MAX * 2);

    foreach (i; 0..N)
        cnt[A[i]] += 1;
    foreach (i; 0..MAX*2-1)
        cnt[i + 1] += cnt[i];
    foreach (i; 0..MAX*2-1)
        cntsum[i + 1] += cntsum[i] + cnt[i + 1];

    long ans = 1L << 59;

    foreach (g; 2..MAX) {
        long tmp = 0;
        for (int l = 1; l < MAX; l += g) {
            int r = l + g - 1;
            int m = max(l, r - border);
            long y = Y * (cntsum[r - 1] - cntsum[m - 1] - cnt[m - 1] * (r - m));
            long x = X * (cnt[m - 1] - cnt[l - 1]);
            tmp += x + y;
        }
        ans = min(ans, tmp);
    }

    debug {
        cnt[0..20].writeln;
        cntsum[0..20].writeln;
    }

    ans.writeln;
}

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

void main() {
    auto s = readln.split.map!(to!long);
    auto N = s[0].to!int;
    auto X = s[1];
    auto Y = s[2];
    auto A = readln.split.map!(to!long).array;

    if (A.map!(a => a == 1).all) {
        writeln(min(X, Y) * N);
        return;
    }

    const int MAX = 10^^6 + 1;
    auto table = new long[MAX];
    fill(table, true);
    table[0] = table[1] = false;
    long[] P;

    for (int i = 2; i * i < MAX; ++i) {
        if (table[i]) {
            P ~= i;
            for (int j = i + i; j * j < MAX; j += i)
                table[j] = false;
        }
    }

    long ans = 1L << 59;

    foreach (p; P) {
        long tmp = 0;
        foreach (a; A)
            tmp += min(X, (p - a % p) * Y);
        ans = min(ans, tmp);
    }

    long tmp = 0;
    long m = A.reduce!max;
    foreach (a; A)
        tmp += min(X, (m - a) * Y);
    ans = min(ans, tmp);

    ans.writeln;
}

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

void main() {
    auto s = readln.split.map!(to!long);
    auto N = s[0].to!int;
    auto X = s[1];
    auto Y = s[2];
    auto A = readln.split.map!(to!long).array;

    if (A.map!(a => a == 1).all) {
        writeln(min(X, Y) * N);
        return;
    }

    const int MAX = 10^^6 + 1;
    auto table = new long[MAX];
    fill(table, true);
    table[0] = table[1] = false;
    long[] P;

    for (int i = 2; i * i < MAX; ++i) {
        if (table[i]) {
            P ~= i;
            for (int j = i + i; j * j < MAX; j += i)
                table[j] = false;
        }
    }

    long ans = 1L << 59;

    foreach (p; P) {
        long tmp = 0;
        foreach (a; A)
            tmp += min(X, (a % p == 0 ? 0 : p - a % p) * Y);
        ans = min(ans, tmp);
    }

    long tmp = 0;
    long m = A.reduce!max;
    foreach (a; A)
        tmp += min(X, (m - a) * Y);
    ans = min(ans, tmp);

    ans.writeln;
}

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

void main() {
    auto s = readln.split.map!(to!long);
    auto N = s[0].to!int;
    auto X = s[1];
    auto Y = s[2];
    auto A = readln.split.map!(to!long).array;

    if (A.map!(a => a == 1).all) {
        writeln(min(X, Y) * N);
        return;
    }

    const int MAX = 10^^6 + 1;
    auto table = new long[MAX];
    fill(table, true);
    table[0] = table[1] = false;
    long[] P;

    for (int i = 2; i * i < MAX; ++i) {
        if (table[i]) {
            P ~= i;
            for (int j = i + i; j * j < MAX; j += i)
                table[j] = false;
        }
    }

    long ans = 1L << 59;

    foreach (p; P) {
        long tmp = 0;
        foreach (a; A)
            tmp += min(X, (a % p) * Y);
        ans = min(ans, tmp);
    }

    long tmp = 0;
    long m = A.reduce!max;
    foreach (a; A)
        tmp += min(X, (m - a) * Y);
    ans = min(ans, tmp);

    ans.writeln;
}

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 X = readLong();
      const Y = readLong();
      auto A = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
      }
      A.sort;

      const lim = A.maxElement + 1;
      auto lpf = iota(lim).array;
      foreach (p; 2 .. lim) {
        if (lpf[p] == p) {
          for (int n = 2 * p; n < lim; n += p) {
            chmin(lpf[n], p);
          }
        }
      }

      auto freq = new int[lim];
      foreach (i; 0 .. N) {
        for (int a = A[i]; a > 1; ) {
          const p = lpf[a];
          ++freq[p];
          do {
            a /= p;
          } while (a % p == 0);
        }
      }

      long ans = N * X;
      foreach (p; 2 .. lim) {
        if (ans > (N - freq[p]) * min(X, Y)) {
          long cost;
          foreach (i; 0 .. N) {
            const r = A[i] % p;
            if (r != 0) {
              cost += min(X, Y * (p - r));
              if (ans < cost) {
                break;
              }
            }
          }
          chmin(ans, cost);
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


As a human, she can erase history of its entirety. As a Bai Ze (Hakutaku), she can create history out of nothingness.—Perfect Memento in Strict SenseKeine has the ability to manipulate history. The history of Gensokyo is a string $$$s$$$ of length $$$1$$$ initially. To fix the chaos caused by Yukari, she needs to do the following operations $$$n$$$ times, for the $$$i$$$-th time:  She chooses a non-empty substring $$$t_{2i-1}$$$ of $$$s$$$. She replaces $$$t_{2i-1}$$$ with a non-empty string, $$$t_{2i}$$$. Note that the lengths of strings $$$t_{2i-1}$$$ and $$$t_{2i}$$$ can be different.Note that if $$$t_{2i-1}$$$ occurs more than once in $$$s$$$, exactly one of them will be replaced.For example, let $$$s=$$$"marisa", $$$t_{2i-1}=$$$"a", and $$$t_{2i}=$$$"z". After the operation, $$$s$$$ becomes "mzrisa" or "marisz".After $$$n$$$ operations, Keine got the final string and an operation sequence $$$t$$$ of length $$$2n$$$. Just as Keine thinks she has finished, Yukari appears again and shuffles the order of $$$t$$$. Worse still, Keine forgets the initial history. Help Keine find the initial history of Gensokyo!Recall that a substring is a sequence of consecutive characters of the string. For example, for string "abc" its substrings are: "ab", "c", "bc" and some others. But the following strings are not its substring: "ac", "cba", "acb".HacksYou cannot make hacks in this problem.

Each test contains multiple test cases. The first line contains a single integer $$$T$$$ ($$$1 \leq T \leq 10^3$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n < 10 ^ 5$$$) — the number of operations. The next $$$2n$$$ lines contains one non-empty string $$$t_{i}$$$ — the $$$i$$$-th string of the shuffled sequence $$$t$$$. The next line contains one non-empty string $$$s$$$ — the final string. It is guaranteed that the total length of given strings (including $$$t_i$$$ and $$$s$$$) over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$. All given strings consist of lowercase English letters only. It is guaranteed that the initial string exists. It can be shown that the initial string is unique.

For each test case, print the initial string in one line.

2

2

a

ab

b

cd

acd

3

z

a

a

aa

yakumo

ran

yakumoran

NoteTest case 1:Initially $$$s$$$ is "a". In the first operation, Keine chooses "a", and replaces it with "ab". $$$s$$$ becomes "ab". In the second operation, Keine chooses "b", and replaces it with "cd". $$$s$$$ becomes "acd".So the final string is "acd", and $$$t=[$$$"a", "ab", "b", "cd"$$$]$$$ before being shuffled.Test case 2:Initially $$$s$$$ is "z". In the first operation, Keine chooses "z", and replaces it with "aa". $$$s$$$ becomes "aa". In the second operation, Keine chooses "a", and replaces it with "ran". $$$s$$$ becomes "aran". In the third operation, Keine chooses "a", and replaces it with "yakumo". $$$s$$$ becomes "yakumoran".So the final string is "yakumoran", and $$$t=[$$$"z", "aa", "a", "ran", "a", "yakumo"$$$]$$$ before being shuffled.

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

void solve() {
    int N = readln.chomp.to!int;
    auto T = new string[2*N];
    foreach (i; 0 .. 2*N) {
        T[i] = readln.chomp;
    }
    auto S = readln.chomp;

    char f() {
        int[char] C;
        foreach (i; 0 .. 2*N) {
            foreach (c; T[i]) {
                C[c] = C.get(c, 0) + 1;
            }
        }
        foreach (c; S) {
            C[c] = C.get(c, 0) + 1;
        }
        foreach (c, count; C) {
            if (count % 2 == 1) {
                return c;
            }
        }
        assert(false);
    }
    writeln(f());
}

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


This is an interactive problem.In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.The subway of the Metropolis is one line (regular straight line with no self-intersections) with $$$n$$$ stations, indexed consecutively from $$$1$$$ to $$$n$$$. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers $$$l$$$ and $$$r$$$ ($$$l \le r$$$), and then check, whether the train is located on a station with index between $$$l$$$ and $$$r$$$, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most $$$k$$$ stations away. Formally, if the train was at the station $$$x$$$ when the gadget was applied, then at the next application of the gadget the train can appear at any station $$$y$$$ such that $$$\max(1, x - k) \leq y \leq \min(n, x + k)$$$.Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.After an examination of the gadget you found that it is very old and can hold no more than $$$4500$$$ applications, after which it will break and your mission will be considered a failure.Can you find the station with the train using no more than $$$4500$$$ applications of the gadgets?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^{18}$$$, $$$0 \leq k \leq 10$$$) — the number of stations and the maximum number of stations the train can move between two applications of the gadget.

NoteIn the first sample, the train was initially at the station $$$5$$$, after the first application of the gadget it did not move, after the second application it moved to the station $$$3$$$, and after the third application moved again to the station $$$5$$$.

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

immutable int steps = 4500;

bool ask (long lo, long hi)
{
	writeln (lo, " ", hi);
	stdout.flush ();
	auto s = readln.strip;
	return s == "Yes";
}

void main ()
{
	long n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		long lo = 1;
		long hi = n;
		foreach (step; 0..steps)
		{
			if (hi - lo < 50)
			{
				long me = uniform (lo, hi + 1);
				if (ask (me, me))
				{
					break;
				}
			}
			else
			{
				long me = (lo + hi) >> 1;
				if (ask (lo, me))
				{
					hi = me;
				}
				else
				{
					lo = me + 1;
				}
			}
			lo = max (1, lo - k);
			hi = min (n, hi + k);
		}
	}
}


Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.

Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.

4
hello
hello
hello
helloo
hello
hlllloo
hello
helo

5
aa
bb
codeforces
codeforce
polycarp
poolycarpp
aaaa
aaaab
abcdefghijklmnopqrstuvwxyz
zabcdefghijklmnopqrstuvwxyz

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

int[] va,vb;
void rec(ref int[] a,ref string s){
    a=null;
    for(int i=0;i<s.length;){
        int c=0;
        while(i+c<s.length && s[i+c]==s[i])
            c++;
        a~=c;
        i+=c;
    }
}
void main(){
    int n=readln.chomp.to!int;
    string a,b;
    bool r;
    while(n--){
        va=[];
        vb=[];
        a=readln.strip;
        b=readln.strip;
        r=true;
        if(b.length>=a.length){
            rec(va,a);
            rec(vb,b);
            debug{
                writeln(va);
                writeln(vb);
            }
            if(va.length==vb.length){
                int j=0,k=0;
                for(int i=0;i<va.length;i++){
                    j+=va[i];
                    k+=vb[i];
                    if(a[j-1]!=b[k-1] || va[i]>vb[i]){
                        r=false;
                        break;
                    }
              }
            }else r=false;
        }else r=false;
        if(r) writeln("YES");
        else writeln("NO");
    }
}

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

void main ()
{
	foreach (test; 0..readln.strip.to !(int))
	{
		auto s = readln.strip.group.array;
		auto t = readln.strip.group.array;
		writeln (s.length == t.length && zip (s, t).all
		    !(c => c[0][0] == c[1][0] && c[0][1] <= c[1][1]) ?
		    "YES" : "NO");
	}
}

import std.algorithm, std.conv, std.range, std.stdio, std.string;
void main() {
	readln.strip.to!int.iota.each!(_ => {
		auto u = [readln.group, readln.group];
		writeln(u[0].count == u[1].count && zip(u[0], u[1])
		.all!"a[0][0] == a[1][0] && a[0][1] <= a[1][1]" ? "YES" : "NO");
	}());
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	readln;
	foreach (test; 0..tests)
	{
		auto s = readln.strip ~ '$';
		auto t = readln.strip ~ '$';
		int i = 0;
		int j = 0;
		for ( ; i < s.length; i++)
		{
			if (s[i] == t[j])
			{
				j += 1;
				continue;
			}
			while (i > 0 && s[i - 1] == t[j])
			{
				j += 1;
			}
			if (s[i] == t[j])
			{
				j += 1;
				continue;
			}
			else
			{
				break;
			}
		}
		writeln ((i == s.length && j == t.length) ? "YES" : "NO");
	}
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n   = RD!int;
	auto ans = new bool[](n);
	foreach (i; 0..n)
	{
		auto s1 = RD!string;
		auto s2 = RD!string;
		bool ok = true;
		char last;
		size_t pos;
		foreach (c; s2)
		{
			if (pos >= s1.length)
			{
				if (c == last) continue;
				else
				{
					ok = false;
					break;
				}
			}
			if (c == s1[pos])
			{
				++pos;
				last = c;
				continue;
			}
			else if (c == last) continue;
			else
			{
				ok = false;
				break;
			}
		}
		if (pos < s1.length) ok = false;

		ans[i] = ok;
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush();
	debug readln();
}

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

int[] va,vb;
void rec(ref int[] a,ref string s){
    a=null;
    for(int i=0;i<s.length;){
        int c=0;
        while(i+c<s.length && s[i+c]==s[i])
            c++;
        a~=c;
        i+=c;
    }
}
void main(){
    int n=readln.chomp.to!int;
    string a,b;
    bool r;
    while(n--){
        va=[];
        vb=[];
        a=readln.strip;
        b=readln.strip;
        r=true;
        if(b.length>=a.length){
            rec(va,a);
            rec(vb,b);
            if(va.length==vb.length){
                int j=0,k=0;
                for(int i=0;i<va.length;i++){
                    if(a[i+j]!=b[i+k] || va[j]>vb[k]){
                        r=false;
                        break;
                    }
                    j+=va[i]-1;
                    k+=vb[i]-1;
              }
            }else r=false;
        }else r=false;
        if(r) writeln("YES");
        else writeln("NO");
    }
}


There are $$$n$$$ workers and $$$m$$$ tasks. The workers are numbered from $$$1$$$ to $$$n$$$. Each task $$$i$$$ has a value $$$a_i$$$ — the index of worker who is proficient in this task.Every task should have a worker assigned to it. If a worker is proficient in the task, they complete it in $$$1$$$ hour. Otherwise, it takes them $$$2$$$ hours.The workers work in parallel, independently of each other. Each worker can only work on one task at once.Assign the workers to all tasks in such a way that the tasks are completed as early as possible. The work starts at time $$$0$$$. What's the minimum time all tasks can be completed by?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le m \le 2 \cdot 10^5$$$) — the number of workers and the number of tasks. The second line contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_i \le n$$$) — the index of the worker proficient in the $$$i$$$-th task. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the minimum time all tasks can be completed by.

NoteIn the first testcase, the first worker works on tasks $$$1$$$ and $$$3$$$, and the second worker works on tasks $$$2$$$ and $$$4$$$. Since they both are proficient in the corresponding tasks, they take $$$1$$$ hour on each. Both of them complete $$$2$$$ tasks in $$$2$$$ hours. Thus, all tasks are completed by $$$2$$$ hours.In the second testcase, it's optimal to assign the first worker to tasks $$$1, 2$$$ and $$$3$$$ and the second worker to task $$$4$$$. The first worker spends $$$3$$$ hours, the second worker spends $$$2$$$ hours (since they are not proficient in the taken task).In the third example, each worker can be assigned to the task they are proficient at. Thus, each of them complete their task in $$$1$$$ hour.

import std;

int t,n,m;
long[] answers;

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d %d", &n, &m);
        getchar();
        auto arr = readln.split.to!(int[]);
        int[] w = new int[](n);
        foreach (k; arr)
            w[--k]++;
        w.sort.reverse.array;
        auto ans = maxElement(w);
        long l = 0;
        long r = ans;
        while (r - l != 1) {
            long mid = (l + r) / 2;
            long rem = 0;

            foreach (i; 0 .. n)
                if (w[i] > mid)
                    rem += w[i] - mid;
                else
                    rem -= (mid - w[i]) / 2;

            if (rem <= 0)
                r = mid;
            else
                l = mid;
        }
        answers ~= r;
    }
    writefln("%(%s \n%)", answers);
}

import std;

int t,n,m;
// int[] answers;

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d %d", &n, &m);
        getchar();
        auto arr = readln.split.to!(int[]);
        int[] w = new int[](n);
        foreach (k; arr)
            w[--k]++;
        w.sort.reverse.array;
        auto ans = maxElement(w);
        long l = 0;
        long r = ans;
        while (r - l != 1) {
            auto mid = (l + r) / 2;
            auto rem = 0;

            foreach (i; 0 .. n)
                if (w[i] > mid)
                    rem += w[i] - mid;
                else
                    rem -= (mid - w[i]) / 2;

            if (rem <= 0)
                r = mid;
            else
                l = mid;
        }
        writeln(r);
    }
    // writefln("%(%s \n%)", answers);
}

import std;

int t,n,m;
// int[] answers;

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d %d", &n, &m);
        getchar();
        auto arr = readln.split.to!(int[]);
        int[] w = new int[](n);
        foreach (k; arr)
            w[--k]++;
        w.sort.reverse.array;
        auto ans = maxElement(w);
        int l = 0;
        int r = ans;
        while (r - l != 1) {
            auto mid = (l + r) / 2;
            auto rem = 0;

            foreach (i; 0 .. n)
                if (w[i] > mid)
                    rem += w[i] - mid;
                else
                    rem -= (mid - w[i]) / 2;

            if (rem <= 0)
                r = mid;
            else
                l = mid;
        }
        writeln(r);
    }
    // writefln("%(%s \n%)", answers);
}

import std;

int t,n,m;
int[] answers;

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d %d", &n, &m);
        getchar();
        auto arr = readln.split.to!(int[]);
        int[] w = new int[](n);
        foreach (k; arr)
            w[--k]++;
        w.sort.reverse.array;
        auto ans = maxElement(w);
        int l = 0;
        int r = ans;
        while (r - l != 1) {
            auto mid = (l + r) / 2;
            auto rem = 0;

            foreach (i; 0 .. n)
                if (w[i] > mid)
                    rem += w[i] - mid;
                else
                    rem -= (mid - w[i]) / 2;

            if (rem <= 0)
                r = mid;
            else
                l = mid;
        }
        answers ~= r;
    }
    writefln("%(%s \n%)", answers);
}

import std;

int t,n,m;

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d %d", &n, &m);
        getchar();
        auto arr = readln.split.to!(int[]);
        int[] w = new int[](n);
        foreach (k; arr)
            w[--k]++;
        size_t prevMax, prevMin;
        auto w_init = w.dup;
        prevMax = maxIndex(w);
        prevMin = minIndex(w);
        auto tmp = (w[prevMax] - w[prevMin]);
        while(tmp > 2) {
            writeln(w);
            if (w[prevMax] > w_init[prevMax]) {
                auto tmp2 = (tmp / 3);

                w[prevMax] -= 2*tmp2;
                if (w_init[prevMin] > w[prevMax])
                    w[prevMin] += tmp2;
                else
                    w[prevMin] += 2*tmp2;
            }
            else {
                w[prevMax] -= tmp / 3;
                w[prevMin] += 2* (tmp / 3);
            }
            prevMax = maxIndex(w);
            prevMin = minIndex(w);
            tmp = w[prevMax] - w[prevMin];
        }
        writeln(w[prevMax]);
    }
}

import std;

int t,n,m;

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d %d", &n, &m);
        getchar();
        auto arr = readln.split.to!(int[]);
        int[] w = new int[](n);
        foreach (k; arr)
            w[--k]++;
        size_t prevMax, prevMin;
        auto w_init = w.dup;
        prevMax = maxIndex(w);
        prevMin = minIndex(w);
        auto tmp = (w[prevMax] - w[prevMin]);
        while(tmp > 2) {
            if (w[prevMax] > w_init[prevMax])
                w[prevMax] -= 2 * (tmp / 3);
            else
                w[prevMax] -= tmp / 3;
            w[prevMin] += 2* (tmp / 3);
            prevMax = maxIndex(w);
            prevMin = minIndex(w);
            tmp = w[prevMax] - w[prevMin];
        }
        writeln(w[prevMax]);
    }
}

import std;

int t,n,m;

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d %d", &n, &m);
        getchar();
        auto arr = readln.split.to!(int[]);
        int[] w = new int[](n);
        foreach (k; arr)
            w[--k]++;
        size_t prevMax, prevMin;
        auto w_init = w.dup;
        prevMax = maxIndex(w);
        prevMin = minIndex(w);
        auto tmp = (w[prevMax] - w[prevMin]);
        while(tmp > 2) {
            if (w[prevMax] > w_init[prevMax])
                w[prevMax] -= 2 * tmp / 3;
            else
                w[prevMax] -= tmp / 3;
            w[prevMin] += 2* (tmp / 3);
            prevMax = maxIndex(w);
            prevMin = minIndex(w);
            tmp = w[prevMax] - w[prevMin];
        }
        writeln(maxElement(w));
    }
}

import std;

int t,n,m;

void main()
{
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        scanf("%d %d", &n, &m);
        getchar();
        auto arr = readln.split.to!(int[]);
        int[] w = new int[](n);
        foreach (k; arr)
            w[--k]++;
        size_t prevMax, prevMin;
        prevMax = maxIndex(w);
        prevMin = minIndex(w);
        while(w[prevMax] - w[prevMin] > 2) {
            auto tmp = (w[prevMax] - w[prevMin]) / 3;
            w[prevMax] -= tmp;
            w[prevMin] += 2*tmp;
            prevMax = maxIndex(w);
            prevMin = minIndex(w);
        }
        writeln(maxElement(w));
    }
}


Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.

The first line contains a single number n (2 ≤ n ≤ 1000) — the number of the tram's stops.  Then n lines follow, each contains two integers ai and bi (0 ≤ ai, bi ≤ 1000) — the number of passengers that exits the tram at the i-th stop, and the number of passengers that enter the tram at the i-th stop. The stops are given from the first to the last stop in the order of tram's movement.   The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that a1 = 0.  At the last stop, all the passengers exit the tram and it becomes empty. More formally, .  No passenger will enter the train at the last stop. That is, bn = 0.

Print a single integer denoting the minimum possible capacity of the tram (0 is allowed).

NoteFor the first example, a capacity of 6 is sufficient:   At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3.  At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now.  At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now.  Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints. Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer.

import std.stdio;
import std.string;
import std.conv;
import std.algorithm;
import std.array;
// -----------------------

int[] scanLeft(int[][] arr, int[] acc = [0]){
  if(!arr.length) return acc;
  return scanLeft(arr[1..$], acc ~ (acc[$-1] - arr[0][0] + arr[0][1]));
}

void main(){
  auto n = readln.chomp.to!int;
  int[][] arr;
  foreach(i; 0..n){ arr ~= readln.chomp.split(" ").map!(to!int).array; }
  scanLeft(arr).reduce!max.writeln;
}

import std.stdio;

void main()
{
    readln; //discard first line

    auto maxPassengers = -1;

    auto numPassengers = 0;

    uint numLeaved, numEntered;

    while(!stdin.eof)
    {
        readf("%s %s\n", &numLeaved, &numEntered);

        numPassengers += numEntered - numLeaved;

        if (numPassengers > maxPassengers) maxPassengers = numPassengers;
    }

    maxPassengers.writeln;
}

import std.stdio, std.algorithm;

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

    int result = 0;
    int inside = 0;
    for (int i = 0; i < n; ++i) {
        int a, b;
        readf("%d %d\n", &a, &b);

        inside -= a;
        inside += b;

        result = max(result, inside);
    }

    writefln("%d", result);
}

import std.stdio;
import core.stdc.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int max = 0;
	int carriage = 0;
	foreach (int i; 0..n)
	{
		int a, b;
		scanf("%d %d", &a, &b);
		carriage += (b - a);
		if (carriage > max) max = carriage;
	}
	printf("%d", max);
    return 0;
}

//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,a,b,v;
    scanf("%d",&n);
    uint ans=0;
    while(n--){
        scanf("%d %d",&a,&b);
        v+=b-a;
        ans=max(ans,v);
    }
    writeln(ans);
}

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

void main() {
  readln;

  int ans = 0;
  int cap = 0;
  foreach (string s; stdin.lines) {
    auto pas = s.chomp.split.map!(to!int).array;
    cap -= pas[0];
    cap += pas[1];
    if (cap > ans) ans = cap;
  }

  ans.writeln;
}

//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,a,b;
    scanf("%d",&n);
    uint ans=0;
    while(n--){
        scanf("%d %d",&a,&b);
        ans=max(ans,ans+b-a);
    }
    writeln(ans);
}

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

void main() {
  readln;

  int ans = 0;
  int cap = 0;
  foreach (string s; stdin.lines) {
    auto pas = s.chomp.split.map!(to!int).array;
    pas.writeln;
    cap -= pas[0];
    cap += pas[1];
    cap.writeln;
    if (cap > ans) ans = cap;
  }

  ans.writeln;
}


The weight of a sequence is defined as the number of unordered pairs of indexes $$$(i,j)$$$ (here $$$i \lt j$$$) with same value ($$$a_{i} = a_{j}$$$). For example, the weight of sequence $$$a = [1, 1, 2, 2, 1]$$$ is $$$4$$$. The set of unordered pairs of indexes with same value are $$$(1, 2)$$$, $$$(1, 5)$$$, $$$(2, 5)$$$, and $$$(3, 4)$$$.You are given a sequence $$$a$$$ of $$$n$$$ integers. Print the sum of the weight of all subsegments of $$$a$$$. A sequence $$$b$$$ is a subsegment of a sequence $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer — the sum of the weight of all subsegments of $$$a$$$.

Note  In test case $$$1$$$, all possible subsegments of sequence $$$[1, 2, 1, 1]$$$ having size more than $$$1$$$ are:   $$$[1, 2]$$$ having $$$0$$$ valid unordered pairs;  $$$[2, 1]$$$ having $$$0$$$ valid unordered pairs;  $$$[1, 1]$$$ having $$$1$$$ valid unordered pair;  $$$[1, 2, 1]$$$ having $$$1$$$ valid unordered pairs;  $$$[2, 1, 1]$$$ having $$$1$$$ valid unordered pair;  $$$[1, 2, 1, 1]$$$ having $$$3$$$ valid unordered pairs.  Answer is $$$6$$$. In test case $$$2$$$, all elements of the sequence are distinct. So, there is no valid unordered pair with the same value for any subarray. Answer is $$$0$$$.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

long compress(in long[] arr, out long[long] zip, out long[] unzip)
{
	auto index = MAKE_IDX(arr);
	long last = arr[index[0]], x;
	zip[last] = x;
	unzip ~= last;
	foreach (i; index[1..$])
	{
		if (arr[i] == last) continue;
		last = arr[i];
		++x;
		zip[last] = x;
		unzip ~= last;
	}
	return x+1;
}

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

		long[long] zip;
		long[] unzip;
		auto len = cast(int)compress(a, zip, unzip);
		auto pos = new int[][](len);
		auto cnt = new long[](n+1);
		auto b = new int[](n);
		foreach (i; 0..n)
		{
			b[i] = cast(int)zip[a[i]];
			cnt[i+1] = cnt[i] + pos[b[i]].length;
			pos[b[i]] ~= i;
		}

		auto pos2 = new long[][](len);
		foreach (i; 0..len)
		{
			pos2[i].length = pos[i].length+1;
			foreach_reverse (j; 0..pos[i].length)
			{
				pos2[i][j] = pos2[i][j+1] + (n - pos[i][j]);
			}
		}

		auto tot = cnt.sum;
		ans[ti] = tot;
		foreach (i; 0..n)
		{
			tot -= pos2[b[i]][$-pos[b[i]].length];
			ans[ti] += tot;
			pos[b[i]].popFront;
		}
	}

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


Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.

The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements.

Print the only integer — the maximum value of f.

NoteIn the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].In the second case maximal value of f is reachable only on the whole array.

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

long fun (long [] b)
{
	auto n = b.length;
	long lo = 0;
	long res = long.min / 2;
	long cur = 0;
	foreach (i; 0..n)
	{
		cur += b[i] * ((i & 1) ? -1 : +1);
		debug {write (cur, " ");}
		if (i & 1)
		{
			lo = min (lo, cur);
		}
		res = max (res, cur - lo);
	}
	debug {writeln ();}
	return res;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.split.map !(to !(long)).array;
		auto b = new long [n - 1];
		foreach (i; 1..n)
		{
			b[i - 1] = abs (a[i] - a[i - 1]);
		}
		writeln (max (fun (b), fun (b[1..$])));
	}
}

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;
import std.datetime;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto B = new long[](N-1);
    foreach (i; 0..N-1) {
        B[i] = abs(A[i] - A[i+1]);
    }

    long ans = B[0];
    long tmp = B[0];
    foreach (i; 1..N-1) {
        tmp += (i % 2 == 0) ? B[i] : -B[i];
        ans = max(ans, tmp);
        if (tmp < 0) tmp = 0;
    }

    if (N <= 2) {
        ans.writeln;
        return;
    }

    ans = max(ans, B[1]);
    tmp = B[1];
    foreach (i; 2..N-1) {
        tmp += (i % 2 == 1) ? B[i] : -B[i];
        ans = max(ans, tmp);
        if (tmp < 0) tmp = 0;
    }

    ans.writeln;
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto B = new long[](N-1);
    foreach (i; 0..N-1) {
        B[i] = abs(A[i] - A[i+1]);
    }

    long ans = B[0];
    long tmp = B[0];
    foreach (i; 1..N-1) {
        tmp += (i % 2 == 0) ? B[i] : -B[i];
        ans = max(ans, tmp);
        if (ans < 0) tmp = 0;
    }

    if (N <= 2) {
        ans.writeln;
        return;
    }

    ans = max(ans, B[1]);
    tmp = B[1];
    foreach (i; 2..N-1) {
        tmp += (i % 2 == 1) ? B[i] : -B[i];
        ans = max(ans, tmp);
        if (ans < 0) tmp = 0;
    }

    ans.writeln;
}


One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.

Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.

NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".

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

int value (string s)
{
	int cur = 0;
	int low = 0;
	foreach (const ref char c; s)
	{
		if (c == '(')
		{
			cur += 1;
		}
		else
		{
			cur -= 1;
		}
		low = min (low, cur);
	}
	if (low < 0 && low < cur)
	{
		return int.min / 4;
	}
	return cur;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int [] v;
		readln;
		foreach (i; 0..n)
		{
			auto s = readln.strip;
			v ~= value (s);
		}
		sort (v);

		int res = 0;
		while (v.length >= 2)
		{
			auto x = v.front;
			auto y = v.back;
			if (x + y < 0)
			{
				v.popFront ();
			}
			else if (x + y > 0)
			{
				v.popBack ();
			}
			else if (x + y == 0)
			{
				res += 1;
				v.popFront ();
				v.popBack ();
			}
		}
		writeln (res);
	}
}

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

void main() {
    int n;
    scan(n);

    auto b = iota(n).map!(i => readln.chomp).array;

    int checkLeft(string s) {
        int h;

        foreach (ch ; s) {
            if (ch == '(') {
                h++;
            }
            else {
                h--;

                if (h < 0) {
                    return -1;
                }
            }
        }

        return h;
    }

    int checkRight(string s) {
        int h;

        foreach_reverse (ch ; s) {
            if (ch == ')') {
                h++;
            }
            else {
                h--;

                if (h < 0) {
                    return -1;
                }
            }
        }

        return h;
    }

    auto cnt = new int[](5 * 10^^5 + 1);
    int perfect;

    foreach (s ; b) {
        int h = checkLeft(s);
        if (h > 0) {
            cnt[h]++;
        }
        if (h == 0) {
            perfect++;
        }
    }

    int ans;

    foreach (s ; b) {
        int h = checkRight(s);
        if (h > 0 && cnt[h] > 0) {
            ans++;
            cnt[h]--;
        }
    }

    ans += perfect / 2;

    writeln(ans);
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}