It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?

The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.

Print the maximum total happiness that can be achieved.

NoteIn the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74.

/+ dub.sdl:
    name "B"
    dependency "dunkelheit" version=">=0.9.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dkh.foundation, dkh.scanner;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    int n; long S;
    sc.read(n, S);

    long[3][] av, bv;
    long ma = 0;
    long ssm, sasm, sbsm;
    foreach (i; 0..n) {
        long s, a, b;
        sc.read(s, a, b);
        ssm += s;
        ma += s * max(a, b);
        if (a >= b) {
            sasm += s;
            av ~= [s, a, b];
        } else {
            sbsm += s;
            bv ~= [s, a, b];
        }
    }

    if (sasm % S + sbsm % S > S) {
        writeln(ma);
        return 0;
    }

    sasm %= S; sbsm %= S;
    av.sort!"a[1]-a[2]<b[1]-b[2]";
    bv.sort!"a[2]-a[1]<b[2]-b[1]";

    long[3][] mid;
    foreach (i; 0..sasm) {
        if (av[0][0] == 0) {
            av = av[1..$];
        }
        ma -= av[0][1];
        mid ~= [1L, av[0][1], av[0][2]];
        av[0][0]--;
    }

    foreach (i; 0..sbsm) {
        if (bv[0][0] == 0) {
            bv = bv[1..$];
        }
        ma -= bv[0][2];
        mid ~= [1L, bv[0][1], bv[0][2]];
        bv[0][0]--;
    }

    long m1, m2;
    foreach (p; mid) {
        m1 += p[1];
        m2 += p[2];
    }

    writeln(ma + max(m1, m2));
    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

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;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(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);
        }
    }
    void read(Args...)(auto ref Args args) {
        import std.exception;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }
    bool hasNext() {
        return succ();
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/

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 R = readLong();
      auto S = new long[N];
      auto A = new long[N];
      auto B = new long[N];
      foreach (i; 0 .. N) {
        S[i] = readLong();
        A[i] = readLong();
        B[i] = readLong();
      }

      long sumS, sumS0, sumS1;
      long ansBase;
      alias Entry = Tuple!(long, "d", long, "s");
      Entry[] es0, es1;
      foreach (i; 0 .. N) {
        sumS += S[i];
        if (A[i] >= B[i]) {
          sumS0 += S[i];
          ansBase += S[i] * A[i];
          es0 ~= Entry(A[i] - B[i], S[i]);
        } else {
          sumS1 += S[i];
          ansBase += S[i] * B[i];
          es1 ~= Entry(B[i] - A[i], S[i]);
        }
      }
      es0.sort;
      es1.sort;

      const k = (sumS + R - 1) / R;
      long ans;
      foreach (l; sumS0 / R - 2 .. sumS0 / R + 2 + 1) {
        if (0 <= l && l <= k) {
          long score = ansBase;
          {
            long lot = max(sumS0 - R * l, 0);
            foreach (ref e; es0) {
              const tmp = min(e.s, lot);
              score -= e.d * tmp;
              lot -= tmp;
            }
          }
          {
            long lot = max(sumS1 - R * (k - l), 0);
            foreach (ref e; es1) {
              const tmp = min(e.s, lot);
              score -= e.d * tmp;
              lot -= tmp;
            }
          }
          debug {
            writeln(l, " ", k - l, ": ", score);
          }
          chmax(ans, score);
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $$$q$$$ questions about this song. Each question is about a subsegment of the song starting from the $$$l$$$-th letter to the $$$r$$$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $$$k$$$ times, where $$$k$$$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is $$$10$$$. Vasya is interested about the length of the resulting string.Help Petya find the length of each string obtained by Vasya.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1\leq n\leq 100\,000$$$, $$$1\leq q \leq 100\,000$$$) — the length of the song and the number of questions.  The second line contains one string $$$s$$$ — the song, consisting of $$$n$$$ lowercase letters of English letters. Vasya's questions are contained in the next $$$q$$$ lines. Each line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) — the bounds of the question.

Print $$$q$$$ lines: for each question print the length of the string obtained by Vasya.

NoteIn the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to $$$4$$$. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is $$$7$$$. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length $$$11$$$.

// Vicfred
// https://codeforces.com/contest/1539/problem/B
//
import std.stdio;
import std.string;

void main() {
    int n, q;
    readf("%s %s\n", &n, &q);
    string s = readln.strip;

    int[][] index = new int[][](26, n + 1);
    foreach(ch; 0 .. 26) {
        int count = 0;
        foreach(i; 0 .. n) {
            if(s[i] == 'a' + ch) {
                count += 1;
            }
            index[ch][i + 1] = count;
        }
    }

    for(int i = 0; i < q; ++i) {
        int l, r;
        readf("%s %s\n", &l, &r);
        int ans = 0;
        foreach(ch; 0 .. 26) {
            int letter = index[ch][r] - index[ch][l - 1];
            ans += letter * (ch + 1);
        }
        ans.writeln;
    }
}

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

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

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

void main() {
  int n, q;
  read(n, q);

  string s = readln;

  auto table = new int[][](26, n + 1);

  foreach (c; 0 .. 26) {
    int t = 0;
    foreach (i; 0 .. n) {
      if (s[i] == 'a' + c) t++;
      table[c][i + 1] = t;
    }
  }

  foreach (i; 0 .. q) {
    int l, r;
    read(l, r);

    long total = 0;

    foreach (c; 0 .. 26) {
      auto rep = table[c][r] - table[c][l - 1];
      total += rep * (c + 1);
    }

    writeln(total);
  }
}

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

void main()
{
  int n, q;
  readf!" %d %d "(n, q);
  string s = readln.strip;
  ulong[] a;
  ulong sum = 0;
  a ~= 0;
  foreach (ch ; s) {
    sum += ch - 'a' + 1;
    a ~= sum;
  }
  while (q--) {
    int l, r;
    readf!" %d %d "(l, r);
    writeln(a[r] - a[l - 1]);
  }
}


You have k pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has n1 washing machines, n2 drying machines and n3 folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before it is dried. Moreover, after a piece of laundry is washed, it needs to be immediately moved into a drying machine, and after it is dried, it needs to be immediately moved into a folding machine.It takes t1 minutes to wash one piece of laundry in a washing machine, t2 minutes to dry it in a drying machine, and t3 minutes to fold it in a folding machine. Find the smallest number of minutes that is enough to wash, dry and fold all the laundry you have.

The only line of the input contains seven integers: k, n1, n2, n3, t1, t2, t3 (1 ≤ k ≤ 104; 1 ≤ n1, n2, n3, t1, t2, t3 ≤ 1000).

Print one integer — smallest number of minutes to do all your laundry.

NoteIn the first example there's one instance of each machine, each taking 5 minutes to complete. You have only one piece of laundry, so it takes 15 minutes to process it.In the second example you start washing first two pieces at moment 0. If you start the third piece of laundry immediately, then by the time it is dried, there will be no folding machine available, so you have to wait, and start washing third piece at moment 2. Similarly, you can't start washing next piece until moment 5, since otherwise there will be no dryer available, when it is washed. Start time for each of the eight pieces of laundry is 0, 0, 2, 5, 10, 10, 12 and 15 minutes respectively. The last piece of laundry will be ready after 15 + 10 + 5 + 2 = 32 minutes.

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 k;
	int [3] n;
	int [3] t;
	while (readf (" %s", &k) > 0)
	{
		readf (" %s %s %s", &n[0], &n[1], &n[2]);
		readf (" %s %s %s", &t[0], &t[1], &t[2]);

		long res = 0;
		int [] [3] s =
		    [new int [n[0]], new int [n[1]], new int [n[2]]];

		foreach (i; 0..k)
		{
			int r0 = n[0] - minPos (s[0]).length;
			int r1 = n[1] - minPos (s[1]).length;
			int r2 = n[2] - minPos (s[2]).length;

			int v1 = max (s[1][r1], s[0][r0] + t[0]);
			int v2 = max (s[2][r2], v1 + t[1]);
			int v3 = v2 + t[2];

			int x2 = v3 - t[2];
			int x1 = x2 - t[1];
			int x0 = x1 - t[0];

			assert (x0 >= r0 && x1 >= r1 && x2 >= r2);

			s[0][r0] = x0 + t[0];
			s[1][r1] = x1 + t[1];
			s[2][r2] = x2 + t[2];

			res = max (res, s[2][r2]);
		}

		writeln (res);
	}
}


A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.

Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.

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

int fixed(int[] c) {
    int p = 0;
    for (int i = 0; i < c.length; i++) {
        if (i == c[i]) {
            p++;
        }
    }
    return p;
}

void main() {
    int n; readf("%d\n", &n);
    int[] c = stdin.readln.chomp.split.map!(to!int).array;
    int ans = fixed(c);
    if (ans == n) {
        writeln(ans);
        return;
    }
    int f = 1;
    for (int i = 0; i < n; i++) {
        int j = c[i];
        if (i != j && i == c[j]) {
            f = 2;
        }
    }
    writeln(ans + f);
}

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

int fixed(int[] c) {
    int p = 0;
    for (int i = 0; i < c.length; i++) {
        if (i == c[i]) {
            p++;
        }
    }
    return p;
}

void main() {
    int n; readf("%d\n", &n);
    int[] c = stdin.readln.chomp.split.map!(to!int).array;
    int ans = fixed(c);
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            auto c_ = c.dup;
            swap(c[i], c[j]);
            ans = max(ans, fixed(c_));
        }
    }
    ans.writeln;
}


This problem is same as the next one, but has smaller constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 50$$$) — the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.

Print a single integer — the number of pairs of wires that are intersecting.

NoteIn the first example:  In the second example:  Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example:

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

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

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

	int n = read.to!int;
	long[] xs, ys;
	foreach(i; 0 .. n) xs ~= read.to!int, ys ~= read.to!int;

	print!1("xs:", xs);
	print!1("ys:", ys);

	long[long] kcnt;
	bool[long] mset;
	foreach(i; 0 .. n) foreach(j; 0 .. i){
		long dx = xs[i] - xs[j];
		long dy = ys[i] - ys[j];
		long c = dx * ys[i] - dy * xs[i];
		print!1("dx:", dx, " dy:", dy, " c:", c);

		if(dx == 0){
			if(dy < 0) dy = -dy, c = -c;
			long g = gcd(dy, c);
			dy /= g, c /= g;
		}
		else if(dy == 0){
			if(dx < 0) dx = -dx, c = -c;
			long g = gcd(dx, c);
			dx /= g, c /= g;
		}
		else if(c == 0){
			if(dx < 0) dx = -dx, dy = -dy;
			long g = gcd(dx, dy);
			dx /= g, dy /= g;
		}
		else{
			if(dx < 0) dx = -dx, dy = -dy, c = -c;
			long g = gcd(gcd(dx, dy), c);
			dx /= g, dy /= g, c /= g;
		}

		print!1(" -> dx:", dx, " dy:", dy, " c:", c);

		long k = 100000 * dy + dx;
		long m = k * 10000000 + c;
		if(m !in mset){
			if(k !in kcnt) kcnt[k] = 0;
			mset[m] = 1;
			kcnt[k] += 1;
		}
	}
	print!1("kcnt:", kcnt);
	print!1("mset:", mset);

	long[] ks = kcnt.keys;
	long[] ms = mset.keys;
	long ans = ms.length * (ms.length - 1) / 2;
	foreach(k; ks) ans -= kcnt[k] * (kcnt[k] - 1) / 2;
	ans.writeln;

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

/*

"How many different direction vectors can we have?"

(x1, y1), (x2, y2) -> (x1 - x2, y1 - y2).
here x1 - x2 and y1 - y2 are relatively prime and x1 - x2 > 0,
or (1, 0), or (0, 1).

O(N^2) = 1000 x 1000.

(y1 - y2)(x - x1) - (x1 - x2)(y - y1) = 0
dy x - dx y + dx y1 - dy x1 = 0

*/

import std.typecons;
import std.stdio;
T gcd(T)(T a, T b) {
	if (a % b == 0) return b;
	return gcd(b, a % b);
}
struct Rat(T) {
	import std.math : abs;
	T n, d;
	this(T n_, T d_) {
		if (d_ == 0) {
			n = 1;
			d = 0;
		} else if (n_ == 0) {
			d = 1;
			n = 0;
		} else {
			auto c = gcd(abs(n_), abs(d_));
			bool neg = (n_ < 0) ^ (d_ < 0);
			n = abs(n_ / c);
			d = abs(d_ / c);
			if (neg) {
				n = -n;
			}
		}
	}
	Rat!T opBinary(string op)(T o) if (op == "*"){
		if (d == 0) {
			return this;
		}
		return Rat!T(n * o, d);
	}
	Rat!T opBinary(string op)(T o) if (op == "/"){
		if (d == 0) {
			return this;
		}
		return Rat!T(n, d * o);
	}
	Rat!T opBinary(string op)(T o) if (op == "+"){
		if (d == 0) {
			return this;
		}
		return Rat!T(n + d * o, d);
	}
	bool opEqual(Rat!T o) {
		return n == o.n && d == o.d;
	}
}
int[2][50] points;
void main() {
	bool[Tuple!(Rat!long, Rat!long)] lines;
	int n;
	scanf("%d ", &n);

	foreach(i; 0..n) {
		scanf("%d %d ", &points[i][0], &points[i][1]);
	}

	debug writeln(points);

	foreach(i; 0..n) {
		foreach(j; 0..i) {
			auto t = Rat!long(points[i][1]-points[j][1], points[i][0]-points[j][0]);
			auto d = t.d ? (t * -points[i][0]) + points[i][1] : Rat!long(points[i][0], 1);
			debug writeln(t, d, t == d);
			lines[tuple(t, d)] = true;
		}
	}

	debug writeln(lines);
	int[Rat!long] tgroup;
	foreach(t, d; lines.byKey) {
		tgroup[t]++;
	}
	long ans = lines.length * (lines.length - 1) / 2;
	foreach(t; tgroup.byKey) {
		ans -= tgroup[t] * (tgroup[t]-1) / 2;
	}
	writeln(ans);
}

void main() {
import std.stdio;
writeln(long.sizeof);
}


You are given an array $$$a_1, a_2, \dots, a_n$$$ and an array $$$b_1, b_2, \dots, b_n$$$.For one operation you can sort in non-decreasing order any subarray $$$a[l \dots r]$$$ of the array $$$a$$$.For example, if $$$a = [4, 2, 2, 1, 3, 1]$$$ and you choose subbarray $$$a[2 \dots 5]$$$, then the array turns into $$$[4, 1, 2, 2, 3, 1]$$$. You are asked to determine whether it is possible to obtain the array $$$b$$$ by applying this operation any number of times (possibly zero) to the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) — the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). The third line of each query contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le n$$$). It is guaranteed that $$$\sum n \le 3 \cdot 10^5$$$ over all queries in a test.

For each query print YES (in any letter case) if it is possible to obtain an array $$$b$$$ and NO (in any letter case) otherwise.

NoteIn first test case the can sort subarray $$$a_1 \dots a_5$$$, then $$$a$$$ will turn into $$$[1, 1, 4, 4, 7, 5, 6]$$$, and then sort subarray $$$a_5 \dots a_6$$$.

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.container.rbtree;

class SegmentTree(T = int, alias op="a+b", T zero = T.init) {
  private:
  T [] t;
  size_t n;
  final void build () pure nothrow @nogc {
    foreach_reverse (i; 1 .. n) {
      immutable k = i << 1;
      t[i] = binaryFun!op (t[k], t[k+1]);
    }
  }
  public:
  final void update (size_t p, T v) pure nothrow @nogc {
    for (t[p += n] = v; p > 1; p >>= 1) {
      t[p>>1] = binaryFun!op (t[p], t[p ^ 1]);
    }
  }
  final T reduce (size_t l, size_t r) const pure nothrow @nogc {
    T res = zero;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
      if (l & 1) {
        res = binaryFun!op (res, t[l++]);
      }
      if (r & 1) {
        res = binaryFun!op (t[--r], res);
      }
    }
    return res;
  }
  this (const T[] a) pure nothrow {
    n = a.length;
    t = uninitializedArray!(T[])(n) ~ a;
    build ();
  }
}

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  immutable nt = r.next!uint;
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint;
    auto a = r.nextA!uint (n);
    auto b = r.nextA!uint (n);
    bool test () {
      debug stderr.writeln ("TEST");
      auto idx = new int[][n+1];
      foreach (i; 0 .. n) {
        idx[a[i]] ~= i;
      }
      auto st = new SegmentTree!(uint, min, int.max) (a);
      auto t = new RedBlackTree!(uint) (iota (0, n));
      foreach (i; 0 .. n) {
        debug stderr.writefln ("i = %d, b[i] = %d", i, b[i]);
        debug stderr.writeln (t);
        auto k = t.front;
        debug stderr.writeln ("k = ", k);
        debug stderr.writeln ("a[k] = ", a[k]);
        if (a[k] < b[i]) {
          debug stderr.writeln ("CHECK: a[k] < b[i]");
          return false;
        } else if (a[k] == b[i]) {
          t.removeFront ();
          st.update (k, uint.max);
        } else {
          while (true) {
            if (idx[b[i]].empty) {
              debug stderr.writeln ("CHECK: idx[b[i]].empty");
              return false;
            }
            int j = idx[b[i]].front;
            debug stderr.writeln ("j = ", j);
            idx[b[i]].popFront ();
            if (j !in t) {
              continue;
            }
            if (st.reduce (0, j) < b[i]) {
              debug stderr.writefln ("CHECK: st.reduce (0, %d) = %d", j, st.reduce (0, j));
              return false;
            }
            t.removeKey (j);
            st.update (j, uint.max);
            break;
          }
        }
      }
      return true;
    }
    writeln (test () ? "YES" : "NO");
  }
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.container.rbtree;

class SegmentTree(T = int, alias op="a+b", T zero = T.init) {
  private:
  T [] t;
  size_t n;
  final void build () pure nothrow @nogc {
    foreach_reverse (i; 1 .. n) {
      immutable k = i << 1;
      t[i] = binaryFun!op (t[k], t[k+1]);
    }
  }
  public:
  final void update (size_t p, T v) pure nothrow @nogc {
    for (t[p += n] = v; p > 1; p >>= 1) {
      t[p>>1] = binaryFun!op (t[p], t[p ^ 1]);
    }
  }
  final T reduce (size_t l, size_t r) const pure nothrow @nogc {
    T res = zero;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
      if (l & 1) {
        res = binaryFun!op (res, t[l++]);
      }
      if (r & 1) {
        res = binaryFun!op (t[--r], res);
      }
    }
    return res;
  }
  this (const T[] a) pure nothrow {
    n = a.length;
    t = uninitializedArray!(T[])(n) ~ a;
    build ();
  }
}

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  immutable nt = r.next!uint;
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint;
    auto a = r.nextA!uint (n);
    auto b = r.nextA!uint (n);
    bool test () {
      debug stderr.writeln ("TEST");
      auto idx = new int[][n+1];
      foreach (i; 0 .. n) {
        idx[a[i]] ~= i;
      }
      auto st = new SegmentTree!(uint, min) (a);
      auto t = new RedBlackTree!(uint) (iota (0, n));
      foreach (i; 0 .. n) {
        debug stderr.writefln ("i = %d, b[i] = %d", i, b[i]);
        debug stderr.writeln (t);
        auto k = t.front;
        debug stderr.writeln ("k = ", k);
        debug stderr.writeln ("a[k] = ", a[k]);
        if (a[k] < b[i]) {
          return false;
        } else if (a[k] == b[i]) {
          t.removeFront ();
          st.update (k, uint.max);
        } else {
          while (true) {
            if (idx[b[i]].empty) return false;
            int j = idx[b[i]].front;
            debug stderr.writeln ("j = ", j);
            idx[b[i]].popFront ();
            if (j !in t) {
              continue;
            }
            debug stderr.writefln ("st.reduce (0, %d) = %d", j, st.reduce (0, j));
            if (st.reduce (0, j) < b[i]) {
              return false;
            }
            t.removeKey (j);
            st.update (j, uint.max);
            break;
          }
        }
      }
      return true;
    }
    writeln (test () ? "YES" : "NO");
  }
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.container.rbtree;

class SegmentTree(T = int, alias op="a+b", T zero = T.init) {
  private:
  T [] t;
  size_t n;
  final void build () pure nothrow @nogc {
    foreach_reverse (i; 1 .. n) {
      immutable k = i << 1;
      t[i] = binaryFun!op (t[k], t[k+1]);
    }
  }
  public:
  final void update (size_t p, T v) pure nothrow @nogc {
    for (t[p += n] = v; p > 1; p >>= 1) {
      t[p>>1] = binaryFun!op (t[p], t[p ^ 1]);
    }
  }
  final T reduce (size_t l, size_t r) const pure nothrow @nogc {
    T res = zero;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
      if (l & 1) {
        res = binaryFun!op (res, t[l++]);
      }
      if (r & 1) {
        res = binaryFun!op (t[--r], res);
      }
    }
    return res;
  }
  this (const T[] a) pure nothrow {
    n = a.length;
    t = uninitializedArray!(T[])(n) ~ a;
    build ();
  }
}

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  immutable nt = r.next!uint;
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint;
    auto a = r.nextA!uint (n);
    auto b = r.nextA!uint (n);
    bool test () {
      auto idx = new int[][n+1];
      foreach (i; 0 .. n) {
        idx[a[i]] ~= i;
      }
      auto st = new SegmentTree!(uint, max) (a);
      auto t = new RedBlackTree!(uint) (iota (0, n));
      foreach (i; 0 .. n) {
        auto k = t.front;
        if (a[k] < b[i]) {
          return false;
        } else if (a[k] == b[i]) {
          t.removeFront ();
          st.update (k, uint.max);
        } else {
          while (true) {
            if (idx[b[i]].empty) return false;
            int j = idx[b[i]].front;
            idx[b[i]].popFront ();
            if (j !in t) {
              continue;
            }
            if (st.reduce (0, j) < b[i]) {
              return false;
            }
            t.removeKey (j);
            st.update (j, uint.max);
            break;
          }
        }
      }
      return true;
    }
    writeln (test () ? "YES" : "NO");
  }
}


Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil.  Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \dots, i$$$ by $$$1$$$.  Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \dots, n$$$ by $$$1$$$.  Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$)  — the number of test cases. The description of $$$t$$$ test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the initial levels of trees moisture.  It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.

For each test case output a single integer — the minimum number of actions. It can be shown that the answer exists.

NoteIn the first test case it's enough to apply the operation of adding $$$1$$$ to the whole array $$$2$$$ times. In the second test case you can apply the operation of decreasing $$$4$$$ times on the prefix of length $$$3$$$ and get an array $$$6, 0, 3$$$. After that apply the operation of decreasing $$$6$$$ times on the prefix of length $$$1$$$ and $$$3$$$ times on the suffix of length $$$1$$$. In total, the number of actions will be $$$4 + 6 + 3 = 13$$$. It can be shown that it's impossible to perform less actions to get the required array, so the answer is $$$13$$$.

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

struct LazySegmentTree(T, F) {
    static assert(hasMember!(T, "binop"));
    static assert(isCallable!(T.binop));
    static assert(hasMember!(T, "unit"));
    static assert(hasMember!(F, "composite"));
    static assert(isCallable!(F.composite));
    static assert(hasMember!(F, "id"));
    int n;
    T[] dat;
    F[] laz; // composition of all uniformly applied `F`s
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n-1];
        dat[] = T.unit;
        laz = new F[2*n-1];
        laz[] = F.id;
    }
    this(T[] xs) {
        this(cast(int)(xs.length));
        for (int i = 0; i < xs.length; i++) { this.dat[this.n - 1 + i] = xs[i]; }
        for (int k = this.n-2; k >= 0; k--) { this.dat[k] = T.binop(this.dat[2*k+1], this.dat[2*k+2]); }
    }
    void push(int k) {
        if (laz[k] == F.id) return;
        if (k < n - 1) {
            laz[k*2+1] = laz[k].composite(laz[k*2+1]);
            laz[k*2+2] = laz[k].composite(laz[k*2+2]);
        }
        dat[k] = laz[k](dat[k]);
        laz[k] = F.id;
    }
    // apply `f` to range [a, b). i.e. x[a] <- f(x[a]), ..., x[b-1] <- f(x[b-1])
    void apply(int a, int b, F f) { apply(a, b, f, 0, 0, n); }
    void apply(int a, int b, F f, int k, int l, int r) {
        push(k);
        if (a <= l && r <= b) {
            laz[k] = f.composite(laz[k]);
        } else if (l < b && a < r) {
            apply(a, b, f, k*2+1, l, (l+r)/2);
            apply(a, b, f, k*2+2, (l+r)/2, r);
            dat[k] = T.binop(dat[k*2+1], dat[k*2+2]);
        }
    }
    // return x[a] + x[a+1] + ... + x[b-1] (here '+' corresponds to `T.binop`)
    T query(int a, int b) { return query(a, b, 0, 0, n); }
    T query(int a, int b, int k, int l, int r) {
        push(k);
        if (b <= l || r <= a) return T.unit;
        else if (a <= l && r <= b) return dat[k];
        else {
            auto lres = query(a, b, k*2+1, l, (l+r)/2);
            auto rres = query(a, b, k*2+2, (l+r)/2, r);
            return T.binop(lres, rres);
        }
    }
    // for debugging. apply all propagated function to leaves.
    void push_all() {
        for (int k = 0; k < n-1; k++) push(k);
    }
}

struct RSQ(Integer) {
    struct T {
        Integer x;
        Integer len;
        static T binop(T a, T b) { return T(a.x + b.x, a.len + b.len); }
        enum T unit = T(0, 0);
    }
    struct F {
        Integer x;
        this(Integer x) { this.x = x; }
        T opCall(T t) { return T(x * t.len + t.x, t.len); }
        F composite(F g) { return F(x + g.x); }
        enum F id = F(0);
    }
    LazySegmentTree!(T, F) lst;
    this(int n_) { lst = LazySegmentTree!(T, F)(n_); }
    this(Integer[] xs) {
        lst = LazySegmentTree!(T, F)(xs.map!((x) => T(x, 1)).array);
    }
    void add(int a, int b, Integer x) {
        lst.apply(a, b, F(x));
    }
    Integer query(int a, int b) {
        return lst.query(a, b).x;
    }
}

void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!long).array;
    auto rsq = RSQ!long(A);
    long ans = 0;
    for (int i = 0; i+1 < N; i++) {
        long a = rsq.query(i, i+1);
        long b = rsq.query(i+1, i+2);
        if (a > b) {
            long d = a - b;
            ans += d;
            rsq.add(0, i+1, -d);
        } else if (a < b) {
            long d = b - a;
            ans += d;
            rsq.add(i+1, N, -d);
        }
    }
    ans += abs(rsq.query(0, 1));
    writeln(ans);
}

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


Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $$$0$$$ or $$$1$$$. For example, $$$1\,010\,111$$$ is a binary decimal, while $$$10\,201$$$ and $$$787\,788$$$ are not.Given a number $$$n$$$, you are asked to represent $$$n$$$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$), denoting the number to be represented.

For each test case, output the smallest number of binary decimals required to represent $$$n$$$ as a sum.

NoteIn the first test case, $$$121$$$ can be represented as $$$121 = 110 + 11$$$ or $$$121 = 111 + 10$$$.In the second test case, $$$5$$$ can be represented as $$$5 = 1 + 1 + 1 + 1 + 1$$$.In the third test case, $$$1\,000\,000\,000$$$ is a binary decimal itself, thus the answer is $$$1$$$.

import std.stdio;
import std.ascii;
import std.algorithm;
import std.range;
import core.stdc.stdio;

void main()
{
	int t = readInt!int;
	while (t--) solve;
}
void solve()
{
	auto n = readInt!long;
	int md = int.min;
	while (n)
	{
		md = cast(int)max(md, n % 10);
		n /= 10;
	}
	md.writeln;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
		popChar;
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else
			static assert(text("Operator ", operator, " not supported"));
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}

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

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

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

void main() {
  int t;
  read(t);

  while (t--) {
    string s;
    read(s);

    char c = s[0];
    foreach (e; s) {
      c = max(c, e);
    }

    writeln(c);
  }
}

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    auto s = readln.strip;
    writeln(s.maxElement);
  }

} // main

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()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    writeln(n.text.split("").map!(to!int).maxElement);
  }
}

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

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

		foreach (c; n)
		{
			ans[ti].chmax(c-'0');
		}
	}

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

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readToken();
        int ans;
        foreach (c; N) {
          chmax(ans, c - '0');
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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 s = readln.strip;
		writeln (s.maxElement);
	}
}


The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.Find any longest k-good segment.As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·105) — the number of elements in a and the parameter k. The second line contains n integers ai (0 ≤ ai ≤ 106) — the elements of the array a.

Print two integers l, r (1 ≤ l ≤ r ≤ n) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.

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

void solve(int[] a, int k)
{
    auto n = cast(int)a.length;
    int[int] cnt;
    auto longest = 0;
    auto left = -1, right = -1;
    auto i = 0, j = 0;
    auto count = 0;
    while (j < n)
    {
        if (!(a[j] in cnt) || cnt[a[j]] == 0)
        {
            ++ count;
        }
        if (!(a[j] in cnt))
        {
            cnt[a[j]] = 0;
        }
        ++ cnt[a[j]];
        if (count <= k)
        {
            if (j - i + 1 > longest)
            {
                left = i + 1;
                right = j + 1;
                longest = j - i + 1;
            }
        }
        else
        {
            while (i <= j && count > k)
            {
                -- cnt[a[i]];
                if (cnt[a[i]] == 0)
                {
                    -- count;
                }
                ++ i;
            }
        }
        ++ j;
    }
    writeln(left, " ", right);
}

int main(string[] args)
{
    int n, k;
    while (readf("%d %d\n", &n, &k) == 2)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            readf(" %d", &a[i]);
        }
        readln;
        solve(a, k);
    }
    return 0;
}

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

void solve(int[] a, int k)
{
    auto n = cast(int)a.length;
    auto m = reduce!(max)(a);
    auto cnt = new int[m + 1];
    auto longest = 0;
    auto left = -1, right = -1;
    auto i = 0, j = 0;
    auto count = 0;
    while (j < n)
    {
        if (cnt[a[j]] == 0)
        {
            ++ count;
        }
        ++ cnt[a[j]];
        if (count <= k)
        {
            if (j - i + 1 > longest)
            {
                left = i + 1;
                right = j + 1;
                longest = j - i + 1;
            }
        }
        else
        {
            while (i <= j && count > k)
            {
                -- cnt[a[i]];
                if (cnt[a[i]] == 0)
                {
                    -- count;
                }
                ++ i;
            }
        }
        ++ j;
    }
    writeln(left, " ", right);
}

int main(string[] args)
{
    int n, k;
    while (readf("%d %d\n", &n, &k) == 2)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            readf(" %d", &a[i]);
        }
        readln;
        solve(a, k);
    }
    return 0;
}

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

void solve(int[] a, int k)
{
    auto n = cast(int)a.length;
    int[int] cnt;
    auto longest = 0;
    auto left = -1, right = -1;
    auto i = 0, j = 0;
    auto count = 0;
    while (j < n)
    {
        if (!(a[j] in cnt) || cnt[a[j]] == 0)
        {
            ++ count;
        }
        if (!a[j] in cnt)
        {
            cnt[a[j]] = 0;
        }
        ++ cnt[a[j]];
        if (count <= k)
        {
            if (j - i + 1 > longest)
            {
                left = i + 1;
                right = j + 1;
                longest = j - i + 1;
            }
        }
        else
        {
            while (i <= j && count > k)
            {
                -- cnt[a[i]];
                if (cnt[a[i]] == 0)
                {
                    -- count;
                }
                ++ i;
            }
        }
        ++ j;
    }
    writeln(left, " ", right);
}

int main(string[] args)
{
    int n, k;
    while (readf("%d %d\n", &n, &k) == 2)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            readf(" %d", &a[i]);
        }
        readln;
        solve(a, k);
    }
    return 0;
}


A rectangle with its opposite corners in $$$(0, 0)$$$ and $$$(w, h)$$$ and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that:   exactly two of them belong to the same side of a rectangle;  the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.

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 $$$w$$$ and $$$h$$$ ($$$3 \le w, h \le 10^6$$$) — the coordinates of the corner of a rectangle. The next two lines contain the description of the points on two horizontal sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$x_1 < x_2 < \dots < x_k$$$ ($$$0 < x_i < w$$$) — the $$$x$$$ coordinates of the points in the ascending order. The $$$y$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$h$$$. The next two lines contain the description of the points on two vertical sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$y_1 < y_2 < \dots < y_k$$$ ($$$0 < y_i < h$$$) — the $$$y$$$ coordinates of the points in the ascending order. The $$$x$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$w$$$. The total number of points on all sides in all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side.

import std;

alias MinMax = Tuple!(long, "min", long, "max");

long
readLong () {
    long a;
    readf!" %s"(a);
    return a;
}

MinMax
minMax () {
    immutable nb_to_read = readLong();
    long min = long.max, max = long.min;
    foreach (i; 0 .. nb_to_read) {
        immutable x = readLong();

        if (x < min)
            min = x;
        if (x > max)
            max = x;
    }
    return MinMax(min, max);
}

long
base_length (in MinMax seg) {
    return seg.max - seg.min;
}

void main () {
    immutable t = readLong();

    foreach (test_index; 0 .. t) {
        immutable w = readLong(), h = readLong();

        long area = -1;
        area = max(area, base_length(minMax()) * h);
        area = max(area, base_length(minMax()) * h);
        area = max(area, base_length(minMax()) * w);
        area = max(area, base_length(minMax()) * w);

        writeln(area);
    }
}

// ""

immutable multi = true;

void solve(int tc)
{
  auto w = readInt!long;
  auto h = readInt!long;
  auto x1n = readInt!int;
  auto x1 = ma(x1n, readInt!long);
  auto x2n = readInt!int;
  auto x2 = ma(x2n, readInt!long);
  auto y1n = readInt!int;
  auto y1 = ma(y1n, readInt!long);
  auto y2n = readInt!int;
  auto y2 = ma(y2n, readInt!long);
  max((x1.back - x1.front) * h,
      (x2.back - x2.front) * h,
      (y1.back - y1.front) * w,
      (y2.back - y2.front) * w).writeln;
}

// main {{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
// }}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
		popChar;
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

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 w, h;
    readf!" %d %d "(w, h);
    auto h1 = readln.splitter.map!(to!long).array[1 .. $];
    auto h2 = readln.splitter.map!(to!long).array[1 .. $];
    auto v1 = readln.splitter.map!(to!long).array[1 .. $];
    auto v2 = readln.splitter.map!(to!long).array[1 .. $];
    writeln(max((h1.maxElement - h1.minElement) * h,
                (h2.maxElement - h2.minElement) * h,
                (v1.maxElement - v1.minElement) * w,
                (v2.maxElement - v2.minElement) * w));
  }
}

import std;

alias MinMax = Tuple!(int, "min", int, "max");

int
readInt () {
    int a;
    readf!" %s"(a);
    return a;
}

MinMax
minMax () {
    immutable nb_to_read = readInt();
    int min = int.max, max = int.min;
    foreach (i; 0 .. nb_to_read) {
        immutable x = readInt();

        if (x < min)
            min = x;
        if (x > max)
            max = x;
    }
    return MinMax(min, max);
}

int
base_length (in MinMax seg) {
    return seg.max - seg.min;
}

void main () {
    immutable t = readInt();

    foreach (test_index; 0 .. t) {
        immutable w = readInt(), h = readInt();

        int area = -1;
        area = max(area, base_length(minMax()) * h);
        area = max(area, base_length(minMax()) * h);
        area = max(area, base_length(minMax()) * w);
        area = max(area, base_length(minMax()) * w);

        writeln(area);
    }
}

// ""

immutable multi = true;

void solve(int tc)
{
  auto w = readInt!long;
  auto h = readInt!long;
  auto x1n = readInt!int;
  auto x1 = ma(x1n, readInt!long);
  auto x2n = readInt!int;
  auto x2 = ma(x2n, readInt!long);
  auto y1n = readInt!int;
  auto y1 = ma(y1n, readInt!long);
  auto y2n = readInt!int;
  auto y2 = ma(y2n, readInt!long);
  max((x1.back - x1.front) * h,
      (x2.back - x2.front) * h,
      (y1.back - x1.front) * w,
      (y2.back - y2.front) * w).writeln;
}

// main {{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
// }}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
		popChar;
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}


Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house.

Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.

import std.stdio: writeln, stdin;
import std.regex: split, regex;
import std.string: strip;
import std.conv: to;
import std.algorithm.iteration: map;

void main()
{
  auto nm = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto as = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto n = nm[0], m = nm[1];
  int b;
  long time = 0;
  foreach(a; as )
  {
    if (a<b) time+=n;
    b=a;
  }
  writeln(time+as[$-1]-1);
}

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

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
		tasks[i]--;
	}

	int cp = 0;
	long steps = 0;
	foreach (int i; 0..m)
	{
		int ts = tasks[i] - cp;
		ts = ts < 0 ? n + ts : ts;
		steps += ts;
		cp = tasks[i];
	}
	printf("%lld", steps);
	return 0;
}

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

string[] tokens;
int tokenId = 0;
string readToken() { for (; tokenId == tokens.length; ) tokens = readln.split, tokenId = 0; return tokens[tokenId++]; }
int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

const long MOD = 100007;

void main () {
	long n = readInt(), m = readInt();
	long[100007] arr = 0;
	for(uint i = 0; i < m; i++) {
		arr[i] = readLong();
	}
	long cost = 0;
	for(int i = 0; i < m - 1; i++) {
		if(arr[i] <= arr[i + 1]) cost += arr[i + 1] - arr[i];
		else cost += n - arr[i] + arr[i + 1];
	}
	writeln(cost + arr[0] - 1);
}

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

immutable int mod = 10^^9 + 7;

void main(){
    long n, m;
    readVars(n, m);
    auto a = readln.split.to!(int[]).map!(a => a - 1);

    //stderr.writeln(a);

    long ans;
    int pos;

    foreach(ai ; a){
        ans += (ai - pos + n) % n;
        pos = ai;
    }

    writeln(ans);
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

import std.stdio: writeln, stdin;
import std.regex: split, regex;
import std.string: strip;
import std.conv: to;
import std.algorithm.iteration: map;

void main()
{
  auto nm = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto as = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto n = nm[0], m = nm[1];
  int b, time = 0;
  foreach(a; as )
  {
    if (a<b) time+=n;
    b=a;

  }
  writeln(time+as[$-1]-1);
}

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

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
	}
	int s = 0;
	int ts = 0;
	int t = 0;
	while (t < m)
	{
		while (t < m && tasks[t] == s+1)
		{
			tasks[t] = 0;
			t++;
		}
		if (t >= m)
			continue;

		if (tasks[t] - 1 >= s)
		{
			ts += (tasks[t] - 1 - s);
			s = tasks[t] - 1;
		} else {
			ts += n - (s - tasks[t] + 1);
			s = tasks[t] - 1;
		}
	}
	printf("%d", ts);
	return 0;
}

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

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
	}
	int s = 0;
	long ts = 0;
	int t = 0;
	while (t < m)
	{
		while (t < m && tasks[t] == s+1)
		{
			tasks[t] = 0;
			t++;
		}
		if (t >= m)
			continue;

		if (tasks[t] - 1 >= s)
		{
			ts += (tasks[t] - 1 - s);
			s = tasks[t] - 1;
		} else {
			ts += n - (s - tasks[t] + 1);
			s = tasks[t] - 1;
		}
	}
	printf("%d", ts);
	return 0;
}

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

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
	}
	int s = 0;
	int ts = 0;
	int t = 0;
	while (t < m)
	{
		while (t < m && tasks[t] == s+1)
		{
			tasks[t] = 0;
			t++;
		}
		if (t >= m)
			continue;

		if (tasks[t] - 1 >= s)
		{
			ts += (tasks[t] - 1 - s);
			s = tasks[t] - 1;
		} else {
			ts += (n - s) + (s - tasks[t] + 1);
			s = tasks[t] - 1;
		}
	}
	printf("%d", ts);
	return 0;
}

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

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
	}
	int s = 0;
	long ts = 0;
	int t = 0;
	while (t < m)
	{
		while (t < m && tasks[t] == s+1)
		{
			tasks[t] = 0;
			t++;
		}
		if (t >= m)
			continue;

		if (tasks[t] - 1 >= s)
		{
			ts += (tasks[t] - 1 - s);
			s = tasks[t] - 1;
		} else {
			ts += n - s + tasks[t] - 1;
			s = tasks[t] - 1;
		}
	}
	printf("%d", ts);
	return 0;
}

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

int main(string[] argv)
{
	int n, m;
	scanf("%d %d", &n, &m);
	int[] tasks; tasks.length = m;
	foreach (int i; 0..m)
	{
		scanf("%d", &tasks[i]);
		tasks[i]--;
	}

	int cp = 0;
	long steps = 0;
	foreach (int i; 0..m)
	{
		int ts = tasks[i] - cp;
		ts = ts < 0 ? n + ts : ts;
		steps += ts;
		cp = tasks[i];
	}
	printf("%d", steps);
	return 0;
}


Adieu l'ami.Koyomi is helping Oshino, an acquaintance of his, to take care of an open space around the abandoned Eikou Cram School building, Oshino's makeshift residence.The space is represented by a rectangular grid of n × m cells, arranged into n rows and m columns. The c-th cell in the r-th row is denoted by (r, c).Oshino places and removes barriers around rectangular areas of cells. Specifically, an action denoted by "1 r1 c1 r2 c2" means Oshino's placing barriers around a rectangle with two corners being (r1, c1) and (r2, c2) and sides parallel to squares sides. Similarly, "2 r1 c1 r2 c2" means Oshino's removing barriers around the rectangle. Oshino ensures that no barriers staying on the ground share any common points, nor do they intersect with boundaries of the n × m area.Sometimes Koyomi tries to walk from one cell to another carefully without striding over barriers, in order to avoid damaging various items on the ground. "3 r1 c1 r2 c2" means that Koyomi tries to walk from (r1, c1) to (r2, c2) without crossing barriers.And you're here to tell Koyomi the feasibility of each of his attempts.

The first line of input contains three space-separated integers n, m and q (1 ≤ n, m ≤ 2 500, 1 ≤ q ≤ 100 000) — the number of rows and columns in the grid, and the total number of Oshino and Koyomi's actions, respectively. The following q lines each describes an action, containing five space-separated integers t, r1, c1, r2, c2 (1 ≤ t ≤ 3, 1 ≤ r1, r2 ≤ n, 1 ≤ c1, c2 ≤ m) — the type and two coordinates of an action. Additionally, the following holds depending on the value of t:    If t = 1: 2 ≤ r1 ≤ r2 ≤ n - 1, 2 ≤ c1 ≤ c2 ≤ m - 1;  If t = 2: 2 ≤ r1 ≤ r2 ≤ n - 1, 2 ≤ c1 ≤ c2 ≤ m - 1, the specified group of barriers exist on the ground before the removal.  If t = 3: no extra restrictions.

For each of Koyomi's attempts (actions with t = 3), output one line — containing "Yes" (without quotes) if it's feasible, and "No" (without quotes) otherwise.

NoteFor the first example, the situations of Koyomi's actions are illustrated below.

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

immutable int logHalf = 12;
immutable int half = 1 << logHalf;
immutable int limit = half + 2505;

ulong [] [] v;

ulong tGet (int r0, int c0)
{
	r0 += half;
	c0 += half;
	ulong res = 0;
	for (int r = r0; r > 0; r >>= 1)
	{
		for (int c = c0; c > 0; c >>= 1)
		{
			res ^= v[r][c];
		}
	}
	return res;
}

void tMark (int r1, int c1, int r2, int c2, ulong h)
{
	r1 += half;
	c1 += half;
	r2 += half;
	c2 += half;
	for (int rLo = r1, rHi = r2; rLo < rHi; rLo >>= 1, rHi >>= 1)
	{
		if ((rHi & 1) == 1)
		{
			rHi -= 1;
			for (int cLo = c1, cHi = c2; cLo < cHi;
			    cLo >>= 1, cHi >>= 1)
			{
				if ((cHi & 1) == 1)
				{
					cHi -= 1;
					v[rHi][cHi] ^= h;
				}
				if ((cLo & 1) == 1)
				{
					v[rHi][cLo] ^= h;
					cLo += 1;
				}
			}
		}
		if ((rLo & 1) == 1)
		{
			for (int cLo = c1, cHi = c2; cLo < cHi;
			    cLo >>= 1, cHi >>= 1)
			{
				if ((cHi & 1) == 1)
				{
					cHi -= 1;
					v[rLo][cHi] ^= h;
				}
				if ((cLo & 1) == 1)
				{
					v[rLo][cLo] ^= h;
					cLo += 1;
				}
			}
			rLo += 1;
		}
	}
}

void main ()
{
	int n, m, q;
	while (readf (" %s %s %s", &n, &m, &q) > 0)
	{
		v = new ulong [] [] (limit, limit);
		ulong [int [4]] h;
		foreach (r; 0..q)
		{
			int t, r1, c1, r2, c2;
			readf (" %s %s %s %s %s", &t, &r1, &c1, &r2, &c2);
			if (t == 3)
			{
				r1 -= 1;
				c1 -= 1;
				r2 -= 1;
				c2 -= 1;
				writeln (tGet (r1, c1) == tGet (r2, c2) ?
				    "Yes" : "No");
			}
			else
			{
				r1 -= 1;
				c1 -= 1;
				int [4] c = [r1, c1, r2, c2];
				if (c !in h)
				{
					h[c] = uniform !(ulong) ();
				}
				tMark (r1, c1, r2, c2, h[c]);
			}
		}
	}
}

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

immutable int logHalf = 12;
immutable int half = 1 << logHalf;
immutable int limit = half + 2505;

ulong [] [] v;

ulong tGet (int r0, int c0)
{
	r0 += half;
	c0 += half;
	ulong res = 0;
	for (int r = r0; r > 0; r >>= 1)
	{
		for (int c = c0; c > 0; c >>= 1)
		{
			res ^= v[r][c];
		}
	}
	return res;
}

void tMark (int r1, int c1, int r2, int c2, ulong h)
{
	r1 += half;
	c1 += half;
	r2 += half;
	c2 += half;
	for (int rLo = r1, rHi = r2; rLo < rHi; rLo >>= 1, rHi >>= 1)
	{
		if ((rHi & 1) == 1)
		{
			rHi -= 1;
			for (int cLo = c1, cHi = c2; cLo < cHi;
			    cLo >>= 1, cHi >>= 1)
			{
				if ((cHi & 1) == 1)
				{
					cHi -= 1;
					v[rHi][cHi] ^= h;
				}
				if ((cLo & 1) == 1)
				{
					v[rHi][cLo] ^= h;
					cLo += 1;
				}
			}
		}
		if ((rLo & 1) == 1)
		{
			for (int cLo = c1, cHi = c2; cLo < cHi;
			    cLo >>= 1, cHi >>= 1)
			{
				if ((cHi & 1) == 1)
				{
					cHi -= 1;
					v[rLo][cHi] ^= h;
				}
				if ((cLo & 1) == 1)
				{
					v[rLo][cLo] ^= h;
					cLo += 1;
				}
			}
			rLo += 1;
		}
	}
}

void main ()
{
	int n, m, q;
	while (readf (" %s %s %s", &n, &m, &q) > 0)
	{
		v = new ulong [] [] (limit, limit);
		ulong [int [4]] h;
		foreach (r; 0..q)
		{
			int t, r1, c1, r2, c2;
			readf (" %s %s %s %s %s", &t, &r1, &c1, &r2, &c2);
			if (t == 3)
			{
				writeln (tGet (r1, c1) == tGet (r2, c2) ?
				    "Yes" : "No");
			}
			else
			{
				r1 -= 1;
				c1 -= 1;
				int [4] c = [r1, c1, r2, c2];
				if (c !in h)
				{
					h[c] = uniform !(ulong) ();
				}
				tMark (r1, c1, r2, c2, h[c]);
			}
		}
	}
}


We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.

The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$  — 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\le 2 \cdot 10^5)$$$  — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$

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

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

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

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

int N;
long[] A;

bool solve() {
  long b;
  foreach (i; 0 .. N) {
    const c = A[i] + b;
    if (c < 0) {
      return false;
    } else if (c == 0) {
      foreach (j; i + 1 .. N) {
        if (A[j] != 0) {
          return false;
        }
      }
      return true;
    } else {
      b = c;
    }
  }
  return (b == 0);
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        N = readInt;
        A = new long[N];
        foreach (i; 0 .. N) {
          A[i] = readLong;
        }

        const ans = solve;
        writeln(ans ? "Yes" : "No");
      }
    }
  } catch (EOFException e) {
  }
}

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;
		while (!a.empty && !a.back)
		{
			a.popBack ();
		}
		long cur = 0;
		int good = 0;
		int bad = 0;
		foreach (ref x; a)
		{
			cur += x;
			good += (cur >= 0);
			bad += (cur == 0);
		}
		auto res = (good == a.length && bad <= 1 && cur == 0);
		writeln (res ? "YES" : "NO");
	}
}