Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go.

The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.  It is guaranteed that the given set of edges specifies a tree.

A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.

NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test:  The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test:  The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.

// Vicfred
// https://codeforces.com/problemset/problem/580/C
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

int n, m, answer;
int[][] tree = new int[][](10^^5+5);
int[] a;

void dfs(int x, int parent, int cats, bool flag) {
    if(a[x] == 1)
        cats += 1;
    if(cats > m)
        flag = true;
    if(tree[x].length == 1 && x != 1 && !flag)
        answer += 1;
    foreach(item; tree[x])
        if(item != parent)
            dfs(item, x, cats*a[x], flag);
}

void main() {
    readf("%s %s", &n, &m);
    readln;
    a = 0~readln.split.map!(to!int).array;

    foreach(i; 1..n) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;
        tree[x] ~= y;
        tree[y] ~= x;
    }

    dfs(1, 0, 0, 0);
    answer.writeln;
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  long n, m;
  @Dim("n") long[] a;
  @Dim("n - 1") Tuple!(long, long)[] edges;

  void solve(long tc = -1)
  {
    foreach(ref edge; edges)
      edge[0]--, edge[1]--;
    auto alist = makeSlice!(long[])(n);
    auto visited = makeSlice!(bool)(n);
    foreach(edge; edges)
      {
        alist.at(edge[0]) ~= edge[1];
        alist.at(edge[1]) ~= edge[0];
      }
    long cnt = 0;
    void dfs(long node, long cats, bool good)
    {
      visited.at(node) = true;
      bool isLeaf = true;
      cats += a.at(node);
      if (cats > m)
        good = false;
      foreach(w; alist.at(node))
        if (!visited.at(w))
          {
            isLeaf = false;
            if (a.at(node) == 0)
              dfs(w, 0, good);
            else
              dfs(w, cats, good);
          }
      if (isLeaf && good)
        {
          cnt++;
        }
    }
    dfs(0, 0, true);
    writeln(cnt);
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}


Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:  Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).  The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries.

The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).

Print m integers — the responses to Eugene's queries in the order they occur in the input.

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

void main() {
    int N, M; scanf("%d %d\n", &N, &M);
    auto xs = readln.chomp.split(" ").map!(to!int).array;
    sort(xs);
    int a, b;
    foreach (x; xs) {
        if (x == -1) {
            a++;
        } else {
            b++;
        }
    }
    foreach (i; 0 .. M) {
        int s, t; scanf("%d %d\n", &s, &t);
        int l = t - s + 1;
        if (l % 2 != 0) {
            writeln(0); continue;
        }
        if (a >= l / 2 && b >= l / 2) {
            writeln(1);
        } else {
            writeln(0);
        }
    }
}

import std.stdio;
import std.array;

void main() {
  int n, m, l, r, ones = 0, mones = 0;
  "%d %d\n".readf(&n, &m);

  string[] a = readln.split;

  foreach(string i; a) {
    if(i == "1")
      ones++;
    else if(i == "-1")
      mones++;
  }

  foreach(_; 0 .. m) {
    "%d %d\n".readf(&l, &r);
    if(
      (r-l) % 2 == 1 &&
      (r-l+1) / 2 <= ones &&
      (r-l+1) / 2 <= mones
    )
      1.writeln;
    else
      0.writeln;
  }

}

import std.stdio;
import std.array;
import std.string;

void main() {
  int n, m, l, r, ones = 0, mones = 0;
  "%d %d\n".readf(&n, &m);

  string[] a = readln.split.array;

  foreach(string i; a) {
    if(i == "1")
      ones++;
    else if(i == "-1")
      mones++;
  }

  foreach(_; 0 .. m) {
    "%d %d\n".readf(&l, &r);
    if(
      (r-l) % 2 == 1 &&
      (r-l+1) / 2 <= ones &&
      (r-l+1) / 2 <= mones
    )
      1.writeln;
    else
      0.writeln;
  }

}

// unihernandez22
// https://codeforces.com/contest/302/problem/A
// greedy

import std.stdio;
import std.array;

void main() {
  int n, m, l, r, ones = 0, mones = 0;
  "%d %d\n".readf(&n, &m);

  int x;
  for(int i = 0; i < n; i++) {
    "%d ".readf(&x);
    if(x == 1)
      ones++;
    else if(x == -1)
      mones++;
  }

  for(int i = 0; i < m; i++) {
    "%d %d\n".readf(&l, &r);
    if(
      (r-l) % 2 == 1 &&
      (r-l+1) / 2 <= ones &&
      (r-l+1) / 2 <= mones
    )
      1.writeln;
    else
      0.writeln;
  }

}


Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place:   A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars.  Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it. Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally.

The first input line contains number n (1 ≤ n ≤ 5000) — amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0 ≤ x ≤ 2000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0 ≤ x ≤ 2000).

Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time.

7
win 10
win 5
win 3
sell 5
sell 3
win 10
sell 10

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

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

//	chmin/chmax
void chmin(T)(ref T t, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int N;
string[] T;
int[] X;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		T = new string[N];
		X = new int[N];
		foreach (i; 0 .. N) {
			T[i] = readToken;
			X[i] = readInt;
		}

		int[][int] sellPoss;
		foreach (i; 0 .. N) {
			if (T[i] == "sell") {
				sellPoss[X[i]] ~= i;
			}
		}

		BigInt[] dp = new BigInt[N + 1];
		foreach (i; 0 .. N) {
			// chmax(dp[i + 1], dp[i]);
			if (dp[i + 1] < dp[i]) {
				dp[i + 1] = dp[i];
			}
			if (T[i] == "win") {
				if (X[i] in sellPoss) {
					const poss = sellPoss[X[i]];
					const idx = poss.lowerBound(i);
					if (idx < poss.length) {
						// chmax(dp[poss[idx] + 1], dp[i] + (BigInt(1) << X[i]));
						if (dp[poss[idx] + 1] < dp[i] + (BigInt(1) << X[i])) {
							dp[poss[idx] + 1] = dp[i] + (BigInt(1) << X[i]);
						}
					}
				}
			}
		}
// writeln(dp);
		writeln(dp[N]);

	}
	} catch (EOFException) {}
}


ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.

The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... < tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.

Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.

NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 > 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.

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

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

        int read_int() {
                return read_string.to!int;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // int t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                int c = cin.read_int;

                int[] arr = new int[n];

                foreach(ref x; arr) {
                        x = cin.read_int;
                }

                int count = 0;
                for (int i = 0; i < n - 1; i++) {
                        if (arr[i + 1] - arr[i] <= c) {
                                count++;
                        } else count = 0;
                }

                writeln(count + 1);
                //plus one since the first word is always added
        }
}

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

void read(out long n, out long c, out long[] arr) {

	readf(" %s %s\n", &n, &c);

	arr = readln.split.map!(to!long).array;
}

long solv(out long res, in long c, in long[] arr) {

	res = 1;
	foreach (idx, el; arr[0 .. $ - 1]) {
		if (arr[idx + 1] - el > c) {
			res = 1;
		} else {
			++res;
		}
	}

	return res;
}

void main() {

	long n, c;
	long[] arr;

	read(n, c, arr);

	long res;
	writeln(solv(res, c, arr));
}

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

void read(out long n, out long c, out long[] arr) {

	readf(" %s %s\n", &n, &c);

	arr = readln.split.map!(to!long).array;
}

long solv(out long res, in long c, in long[] arr) {

	foreach (idx, el; arr[0 .. $ - 1]) {
		if (arr[idx + 1] - el > c) {
			res = 1;
		} else {
			++res;
		}
	}

	return res;
}

void main() {

	long n, c;
	long[] arr;

	read(n, c, arr);

	long res;
	writeln(solv(res, c, arr));
}


You are given an array $$$a_1, a_2, \ldots, a_n$$$ consisting of $$$n$$$ positive integers and a positive integer $$$m$$$.You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.Let's call an array $$$m$$$-divisible if for each two adjacent numbers in the array (two numbers on the positions $$$i$$$ and $$$i+1$$$ are called adjacent for each $$$i$$$) their sum is divisible by $$$m$$$. An array of one element is $$$m$$$-divisible.Find the smallest number of $$$m$$$-divisible arrays that $$$a_1, a_2, \ldots, a_n$$$ is possible to divide into.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \le n \le 10^5, 1 \le m \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$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.

For each test case print the answer to the problem.

NoteIn the first test case we can divide the elements as follows:  $$$[4, 8]$$$. It is a $$$4$$$-divisible array because $$$4+8$$$ is divisible by $$$4$$$.  $$$[2, 6, 2]$$$. It is a $$$4$$$-divisible array because $$$2+6$$$ and $$$6+2$$$ are divisible by $$$4$$$.  $$$[9]$$$. It is a $$$4$$$-divisible array because it consists of one element.

// Vicfred
// https://codeforces.com/contest/1497/problem/B
// modular arithmetic, math, greedy
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    long t = readln.chomp.to!long;

while(t--) {
    uint n, m;
    readf("%s %s\n", &n, &m);
    long[] a = readln.split.map!(to!long).map!(x => x % m).array;

    long[] counter = new long[m];
    foreach(number; a) {
        counter[cast(uint)number] += 1L;
    }

    //a.writeln;
    //counter.writeln;

    long ans = 0L;
    if(counter[0L] > 0L)
        ans += 1L;

    for(uint i = 1L; i*2 <= m; i++) {
        if(counter[i] == 0L && counter[m - i] == 0L)
            continue;
        ans += 1L;
        if(2*i == m)
            continue;
        //writefln("ans: %s", ans);

        long take = min(counter[i], counter[m - i]);
        //writefln("counter[%s] = %s", i, counter[i]);
        //writefln("counter[%s] = %s", m - i, counter[m - i]);

        counter[i] -= take;
        counter[m - i] -= take;

        if(counter[i] > 0L)
            counter[i] -= 1L;
        if(counter[m - i] > 0L)
            counter[m - i] -= 1L;
        ans += counter[i] + counter[m - i];
    }
    ans.writeln;
}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto cnt = new long[](m);
		foreach (e; a)
			++cnt[e%m];

		foreach (i; 1..(m+1)/2)
		{
			auto x = cnt[i];
			auto y = cnt[m-i];
			auto z = min(x, y);
			x -= z;
			y -= z;
			if (z == 0)
				ans[ti] += max(x, y);
			else
				ans[ti] += max(max(x, y), 1);
			debug writeln("i:", i, " ans:", ans[ti]);
		}
		if (cnt[0] != 0)
			++ans[ti];
		if (m % 2 == 0 && cnt[m/2] != 0)
			++ans[ti];
	}

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

// Vicfred
// https://codeforces.com/contest/1497/problem/B
// modular arithmetic, math, greedy
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    long t = readln.chomp.to!long;

while(t--) {
    uint n, m;
    readf("%s %s\n", &n, &m);
    long[] a = readln.split.map!(to!long).map!(x => x % m).array;

    long[] counter = new long[m];
    foreach(number; a) {
        counter[cast(uint)number] += 1L;
    }

    //a.writeln;
    //counter.writeln;

    long ans = 0L;
    if(counter[0L] > 0L)
        ans += 1L;

    for(uint i = 1L; i*2 < m; i++) {
        if(counter[i] == 0L && counter[m - i] == 0L)
            continue;
        ans += 1L;
        //writefln("ans: %s", ans);

        long take = min(counter[i], counter[m - i]);
        //writefln("counter[%s] = %s", i, counter[i]);
        //writefln("counter[%s] = %s", m - i, counter[m - i]);

        counter[i] -= take;
        counter[m - i] -= take;

        if(counter[i] > 0L)
            counter[i] -= 1L;
        if(counter[m - i] > 0L)
            counter[m - i] -= 1L;
        ans += counter[i] + counter[m - i];
    }
    if(counter[m/2] > 1) {
        ans += 1L;
    }
    ans.writeln;
}
}

// Vicfred
// https://codeforces.com/contest/1497/problem/B
// modular arithmetic, math, greedy
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    long t = readln.chomp.to!long;

while(t--) {
    uint n, m;
    readf("%s %s\n", &n, &m);
    long[] a = readln.split.map!(to!long).map!(x => x % m).array;

    long[] counter = new long[m];
    foreach(number; a) {
        counter[cast(uint)number] += 1L;
    }

    //a.writeln;
    //counter.writeln;

    long ans = 0L;
    if(counter[0L] > 0L)
        ans += 1L;

    for(uint i = 1L; i*2 < m; i++) {
        if(counter[i] == 0L && counter[m - i] == 0L)
            continue;
        ans += 1L;
        //writefln("ans: %s", ans);

        long take = min(counter[i], counter[m - i]);
        //writefln("counter[%s] = %s", i, counter[i]);
        //writefln("counter[%s] = %s", m - i, counter[m - i]);

        counter[i] -= take;
        counter[m - i] -= take;

        if(counter[i] > 0L)
            counter[i] -= 1L;
        if(counter[m - i] > 0L)
            counter[m - i] -= 1L;
        ans += counter[i] + counter[m - i];
    }
    if(m%2 == 0 && counter[m/2] > 1) {
        ans += 1L;
    }
    ans.writeln;
}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto cnt = new long[](m);
		foreach (e; a)
			++cnt[e%m];

		foreach (i; 1..(m+1)/2)
		{
			auto x = cnt[i];
			auto y = cnt[m-i];
			auto z = min(x, y);
			++ans[ti];
			x -= z;
			y -= z;
			if (z == 0)
				ans[ti] += max(x, y);
			else
				ans[ti] += max(max(x, y) - 1, 0);
		}
		if (cnt[0] != 0)
			++ans[ti];
		if (m % 2 == 0 && cnt[m/2] != 0)
			++ans[ti];
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto cnt = new long[](m);
		foreach (e; a)
			++cnt[e%m];

		foreach (i; 1..(m+1)/2)
		{
			auto x = cnt[i];
			auto y = cnt[m-i];
			auto z = min(x, y);
			++ans[ti];
			x -= z;
			y -= z;
			ans[ti] += max(max(x, y) - 1, 0);
		}
		if (cnt[0] != 0)
			++ans[ti];
		if (m % 2 == 0 && cnt[m/2] != 0)
			++ans[ti];
	}

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


You are given two arrays $$$a$$$ and $$$b$$$ both consisting of $$$n$$$ positive (greater than zero) integers. You are also given an integer $$$k$$$.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) and swap $$$a_i$$$ and $$$b_j$$$ (i.e. $$$a_i$$$ becomes $$$b_j$$$ and vice versa). Note that $$$i$$$ and $$$j$$$ can be equal or different (in particular, swap $$$a_2$$$ with $$$b_2$$$ or swap $$$a_3$$$ and $$$b_9$$$ both are acceptable moves).Your task is to find the maximum possible sum you can obtain in the array $$$a$$$ if you can do no more than (i.e. at most) $$$k$$$ such moves (swaps).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 30; 0 \le k \le n$$$) — the number of elements in $$$a$$$ and $$$b$$$ and the maximum number of moves you can do. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 30$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 30$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$.

For each test case, print the answer — the maximum possible sum you can obtain in the array $$$a$$$ if you can do no more than (i.e. at most) $$$k$$$ swaps.

NoteIn the first test case of the example, you can swap $$$a_1 = 1$$$ and $$$b_2 = 4$$$, so $$$a=[4, 2]$$$ and $$$b=[3, 1]$$$.In the second test case of the example, you don't need to swap anything.In the third test case of the example, you can swap $$$a_1 = 1$$$ and $$$b_1 = 10$$$, $$$a_3 = 3$$$ and $$$b_3 = 10$$$ and $$$a_2 = 2$$$ and $$$b_4 = 10$$$, so $$$a=[10, 10, 10, 4, 5]$$$ and $$$b=[1, 9, 3, 2, 9]$$$.In the fourth test case of the example, you cannot swap anything.In the fifth test case of the example, you can swap arrays $$$a$$$ and $$$b$$$, so $$$a=[4, 4, 5, 4]$$$ and $$$b=[1, 2, 2, 1]$$$.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		sort (a);
		sort (b);
		reverse (b);
		foreach (i; 0..k)
		{
			if (a[i] < b[i])
			{
				swap (a[i], b[i]);
			}
		}
		writeln (sum (a));
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		a.sort!"a > b"();
		b.sort!"a > b"();

		foreach (i; 0..n-k)
		{
			ans[ti] += a.front; a.popFront;
		}
		foreach (i; 0..k)
		{
			if (a.front > b.front)
			{
				ans[ti] += a.front; a.popFront;
			}
			else
			{
				ans[ti] += b.front; b.popFront;
			}
		}
	}

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


You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.As 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. Don't use the function input() in Python2 instead of it use the function raw_input().

The first line contains a non-negative integer a. The second line contains a non-negative integer b. The numbers a, b may contain leading zeroes. Each of them contains no more than 106 digits.

Print the symbol "<" if a < b and the symbol ">" if a > b. If the numbers are equal print the symbol "=".

module foo2;

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

//import foo1;

void main()
{
    string a = strip(readln());
    string b = strip(readln());
    int i;
    while(a[i .. i+1] == "0")
        i++;
    a = a[i .. $];
    i = 0;
    while(b[i .. i+1] == "0")
        i++;
    b = b[i .. $];
    if (a.length > b.length)
        writeln(">");
    else if (a.length < b.length)
        writeln("<");
    else
    {
        i = 0;
        while(i < a.length && a[i .. i+1] == b[i .. i+1])
            i++;
        if(i == a.length)
            writeln("=");
        else if(a[i .. i+1] > b[i .. i+1])
            writeln(">");
        else
            writeln("<");
    }
}


This is the easier version of the problem. In this version, $$$1 \le n \le 10^5$$$ and $$$0 \le a_i \le 1$$$. You can hack this problem only if you solve and lock both problems.Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $$$n$$$ boxes of chocolate, numbered from $$$1$$$ to $$$n$$$. Initially, the $$$i$$$-th box contains $$$a_i$$$ chocolate pieces.Since Bob is a typical nice guy, he will not send Alice $$$n$$$ empty boxes. In other words, at least one of $$$a_1, a_2, \ldots, a_n$$$ is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $$$k > 1$$$ such that the number of pieces in each box is divisible by $$$k$$$. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $$$i$$$ and put it into either box $$$i-1$$$ or box $$$i+1$$$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of chocolate boxes. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) — the number of chocolate pieces in the $$$i$$$-th box. It is guaranteed that at least one of $$$a_1, a_2, \ldots, a_n$$$ is positive.

If there is no way for Charlie to make Alice happy, print $$$-1$$$. Otherwise, print a single integer $$$x$$$ — the minimum number of seconds for Charlie to help Bob make Alice happy.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto total = sum (a, 0L);
		if (total == 1)
		{
			writeln (-1);
			continue;
		}

		long [] p;
		for (long d = 2; d * d <= total; d++)
		{
			if (total % d == 0)
			{
				p ~= d;
				while (total % d == 0)
				{
					total /= d;
				}
			}
		}
		if (total > 1)
		{
			p ~= total;
		}

		long solve (long d)
		{
			long cur = 0;
			long res = 0;
			foreach (i; 0..n - 1)
			{
				cur += a[i];
				cur %= d;
				res += min (cur, d - cur);
			}
			return res;
		}

		long res = total * n;
		foreach (ref c; p)
		{
			res = min (res, solve (c));
		}
		writeln (res);
	}
}

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

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

void solve(){
	int n = rint;
	long[] as = rlong(n);

	long sum = as.sum;
	long[] ds;
	for(long d = 1; d * d <= sum; d ++) if(sum % d == 0) ds ~= d, ds ~= sum / d;
	log("as:", as, "sum:", sum, "ds:", ds);
	// ※素数に絞っても良いはず

	long ans = as.sum * n;
	foreach(d; ds){
		if(d == 1) continue;
		long leftover;
		long tempans;
		long q;
		foreach(i, a; as){
			q += a, q %= d;
			if(q < d - q) tempans += q;
			else tempans += d - q;
			log("i:", i, "q:", q, "tempans:", tempans);
		}
		ans = min(ans, tempans);
		log("tempans:", tempans, "ans:", ans);
	}
	if(ans >= as.sum * n) ans = -1;
	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.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 INF = 10L^^18;

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

      const S = A.sum;
      long[] ps;
      long s = S;
      for (long p = 2; p * p <= s; ++p) {
        if (s % p == 0) {
          do {
            s /= p;
          } while (s % p == 0);
          ps ~= p;
        }
      }
      if (s > 1) {
        ps ~= s;
      }
      debug {
        writeln("ps = ", ps);
      }

      long ans = INF;
      foreach (p; ps) {
        long cost;
        long now;
        foreach (i; 0 .. N) {
          now += A[i];
          now %= p;
          cost += min(now, p - now);
        }
        debug {
          writeln(p, ": ", cost);
        }
        chmin(ans, cost);
      }
      writeln((ans >= INF) ? -1 : ans);
    }
  } catch (EOFException e) {
  }
}


Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:#define macro_name macro_valueAfter the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.One of the main problems arising while using macros — the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.Let's consider the following example. Say, we declared such a #define construction:#define sum x + yand further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise — suspicious.Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".

The first line contains the only number n (0 ≤ n ≤ 100) — the amount of #define constructions in the given program. Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax: #define name expression where   name — the macro name,  expression — the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.  All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction. Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions. The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol. The length of any line from the input file does not exceed 100 characters.

Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".

4
#define sum  x + y
#define mul  a * b
#define div  a / b
#define expr sum + mul * div * mul
expr

3
#define SumSafe   (a+b)
#define DivUnsafe  a/b
#define DenominatorUnsafe  a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

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

//	chmin/chmax
void chmin(T)(ref T t, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int isDigit(char c) {
	return ('0' <= c && c <= '9');
}
int isAlpha(char c) {
	return (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'));
}

int N;
string[] S;
string T;

/*
	0: ()
	1-4: op
	8: (), suspicious
	9-12: op, suspicious
*/
int[string] macros;

int oper(char op, int a, int b) {
	int ret;
	ret |= a & 8;
	ret |= b & 8;
	a &= 7;
	b &= 7;
	switch (op) {
		case '+': {
			ret |= 1;

		} break;
		case '-': {
			ret |= 2;
			if (b == 1 || b == 2) {
				ret |= 8;
			}
		} break;
		case '*': {
			ret |= 3;
			if (a == 1 || a == 2 || b == 1 || b == 2) {
				ret |= 8;
			}
		} break;
		case '/': {
			ret |= 4;
			if (a == 1 || a == 2 || b == 1 || b == 2 || b == 3 || b == 4) {
				ret |= 8;
			}
		} break;
		default: assert(false);
	}
	return ret;
}

int parse(string s) {
	s = s.removechars("\n\t ") ~ "$";
// writeln("s = ",s);
	int c;
	struct Parser {
		int expr() {
			int ret = factor;
			for (; s[c] == '+' || s[c] == '-'; ) {
				char op = s[c];
				++c;
				int tmp = factor;
				ret = oper(op, ret, tmp);
			}
			return ret;
		}
		int factor() {
			int ret = term;
			for (; s[c] == '*' || s[c] == '/'; ) {
				char op = s[c];
				++c;
				int tmp = term;
				ret = oper(op, ret, tmp);
			}
			return ret;
		}
		int term() {
			int ret;
			if (s[c] == '(') {
				++c;
				ret = expr;
				assert(s[c] == ')');
				++c;
				ret &= 8;
			} else if (isDigit(s[c])) {
				for (; isDigit(s[c]); ) {
					++c;
				}
				ret = 0;
			} else {
				string name;
				for (; isAlpha(s[c]); ) {
					name ~= s[c];
					++c;
				}
				if (name in macros) {
					ret = macros[name];
				} else {
					ret = 0;
				}
			}
			return ret;
		}
	}
	const res = Parser().expr;
	assert(s[c] == '$');
	return res;
}

void main(string[] args) {
	for (string line; (line = readln) != null; ) {
		N = line.chomp.to!int;
		S = new string[N];
		foreach (i; 0 .. N) {
			S[i] = readln.chomp;
		}
		T = readln.chomp;

		macros.clear;
		foreach (i; 0 .. N) {
			// auto captures = S[i].matchFirst(`^\s*#\s*define\s+([A-Za-z]+)\s+(.*)$`).captures;
			auto captures = S[i].match(`^\s*#\s*define\s+([A-Za-z]+)\s+(.*)$`).captures;
// writeln(captures);
			assert(captures.length == 3);
			assert(captures[1] !in macros);
			const res = parse(captures[2]);
// writeln("  ",res);
			macros[captures[1]] = res;
		}

		const ans = parse(T);
		writeln((ans & 8) ? "Suspicious" : "OK");

	}
}


You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with $$$a$$$ cans in a pack with a discount and some customer wants to buy $$$x$$$ cans of cat food. Then he follows a greedy strategy:   he buys $$$\left\lfloor \frac{x}{a} \right\rfloor$$$ packs with a discount;  then he wants to buy the remaining $$$(x \bmod a)$$$ cans one by one. $$$\left\lfloor \frac{x}{a} \right\rfloor$$$ is $$$x$$$ divided by $$$a$$$ rounded down, $$$x \bmod a$$$ is the remainer of $$$x$$$ divided by $$$a$$$.But customers are greedy in general, so if the customer wants to buy $$$(x \bmod a)$$$ cans one by one and it happens that $$$(x \bmod a) \ge \frac{a}{2}$$$ he decides to buy the whole pack of $$$a$$$ cans (instead of buying $$$(x \bmod a)$$$ cans). It makes you, as a marketer, happy since the customer bought more than he wanted initially.You know that each of the customers that come to your shop can buy any number of cans from $$$l$$$ to $$$r$$$ inclusive. Can you choose such size of pack $$$a$$$ that each customer buys more cans than they wanted initially?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 10^9$$$) — the range of the number of cans customers can buy.

For each test case, print YES if you can choose such size of pack $$$a$$$ that each customer buys more cans than they wanted initially. Otherwise, print NO. You can print each character in any case.

NoteIn the first test case, you can take, for example, $$$a = 5$$$ as the size of the pack. Then if a customer wants to buy $$$3$$$ cans, he'll buy $$$5$$$ instead ($$$3 \bmod 5 = 3$$$, $$$\frac{5}{2} = 2.5$$$). The one who wants $$$4$$$ cans will also buy $$$5$$$ cans.In the second test case, there is no way to choose $$$a$$$.In the third test case, you can take, for example, $$$a = 80$$$.

// Vicfred
// https://codeforces.com/contest/1437/problem/A
// math
import std.stdio;

void main() {
    long t;
    readf("%s\n", &t);

    long l, r;
    while(t--) {
        readf("%s %s\n", &l, &r);
        if(2L * l > r)
            "YES".writeln;
        else
            "NO".writeln;
    }
}

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)
	{
		int lo, hi;
		readf !(" %s %s") (lo, hi);
		auto mod = hi + 1;
		writeln ((lo % mod) * 2 >= mod ? "YES" : "NO");
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto l = RD;
		auto r = RD;
		auto a = r+1;
		ans[ti] = l*2 >= a;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto l = RD;
		auto r = RD;
		auto a = (l-1)*2 + 1;
		ans[ti] = a > r;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto l = RD;
		auto r = RD;
		auto a = r + 1;
		ans[ti] = l * 2 > a;
	}

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


DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:  where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:  ;  edge  if and only if , and edge ;  the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.

The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.

Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.

NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal.

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

void main() {
    int N, M;
    scanf("%d %d\n", &N, &M);
    int[] X = readln.chomp.split(" ").map!(to!int).array;
    double Ans = 0;
    for (int i = 0; i < M; i++) {
        int a, b, c; scanf("%d %d %d\n", &a, &b, &c);
        a--; b--;
        Ans = max(Ans, cast(double)(X[a] + X[b]) / c);
    }
    writefln("%.12f", Ans);
}

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

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

//	chmin/chmax
void chmin(T)(ref T t, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int N, M;
real[] X;
int[] A, B;
real[] C;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		M = readInt;
		X = new real[N];
		foreach (u; 0 .. N) {
			X[u] = readReal;
		}
		A = new int[M];
		B = new int[M];
		C = new real[M];
		foreach (i; 0 .. M) {
			A[i] = readInt - 1;
			B[i] = readInt - 1;
			C[i] = readReal;
		}

		real ans = 0.0;
		foreach (i; 0 .. M) {
			if (C[i] > 0) {
				chmax(ans, (X[A[i]] + X[B[i]]) / C[i]);
			}
		}
		writefln("%.10f", ans);

	}
	} catch (EOFException) {}
}


After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).If a carrier with d ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take d ice cream packs comes to the house, then Kay and Gerda will give him d packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.

The first line contains two space-separated integers n and x (1 ≤ n ≤ 1000, 0 ≤ x ≤ 109). Each of the next n lines contains a character '+' or '-', and an integer di, separated by a space (1 ≤ di ≤ 109). Record "+ di" in i-th line means that a carrier with di ice cream packs occupies i-th place from the start of the queue, and record "- di" means that a child who wants to take di packs stands in i-th place.

Print two space-separated integers — number of ice cream packs left after all operations, and number of kids that left the house in distress.

NoteConsider the first sample.  Initially Kay and Gerda have 7 packs of ice cream.  Carrier brings 5 more, so now they have 12 packs.  A kid asks for 10 packs and receives them. There are only 2 packs remaining.  Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed.  Carrier bring 40 packs, now Kay and Gerda have 42 packs.  Kid asks for 20 packs and receives them. There are 22 packs remaining.

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

class Ice_Cream {

    this(long x) { this.x = x; }

    void setX(long d) { x += d; }

    protected static long x;
}

class Kay : Ice_Cream {

    this() { super(x); }
    void setRest(long d) { Kay.x -= d; }

    @property long rest() { return Kay.x; }
}

class Gerda : Ice_Cream {

    this() { super(x); }

    void setSad() { _sad++; }

    @property long sad() { return _sad; }

    private long _sad;
}

void main() {

    long n, x;

    readf(" %s %s ", &n, &x);

    Ice_Cream ice = new Ice_Cream(x);
    Kay kay = new Kay();
    Gerda gerda = new Gerda();

    long d;
    char child_work;

    foreach (idx; 0 .. n) {

        readf(" %s %s ", &child_work, &d);

        if (child_work == '+') {
            ice.setX(d);
        } else {
            if (ice.x < d) {
                gerda.setSad();
            } else {
                kay.setRest(d);
            }
        }
    }

    writeln(kay.rest, ' ', gerda.sad);
}

import std.stdio, std.array, std.algorithm : sort, copy;
import std.conv;
import std.string;

int main(string[] argv)
{
	auto input = stdin.readln().chomp().split();
	auto leng = to!int(input[0]);
	auto curCountIceCream = to!long(input[1]);

    string line;
	int notSatisfiedCount = 0;
	int curLen = 0;
    while ((line = readln().chomp()) !is null)
	{
		auto newLine = removechars(line, ['\x20']);
		auto curInput = to!long(newLine);
		if ( curCountIceCream + curInput >= 0 )
			curCountIceCream += curInput;
		else
			notSatisfiedCount++;
		curLen++;
		if ( curLen == leng)
			break;
	}

	writeln( curCountIceCream , " " , notSatisfiedCount);

    return 0;
}

import std.stdio, std.array, std.algorithm : sort, copy;
import std.conv;
import std.string;

int main(string[] argv)
{
	auto input = stdin.readln().chomp().split();
	auto leng = to!int(input[0]);
	auto curCountIceCream = to!int(input[1]);

    string line;
	int notSatisfiedCount = 0;
	int curLen = 0;
    while ((line = readln().chomp()) !is null)
	{
		auto newLine = removechars(line, ['\x20']);
		auto curInput = to!int(newLine);
		if ( curCountIceCream + curInput >= 0 )
			curCountIceCream += curInput;
		else
			notSatisfiedCount++;
		curLen++;
		if ( curLen == leng)
			break;
	}

	writeln( curCountIceCream , " " , notSatisfiedCount);

    return 0;
}

import std.stdio, std.array, std.algorithm : sort, copy;
import std.conv;
import std.string;

int main(string[] argv)
{
	auto input = stdin.readln().chomp().split();
	auto leng = to!int(input[0]);
	auto curCountIceCream = to!int(input[1]);

    string line;
	int notSatisfiedCount = 0;
	long curLen = 0;
    while ((line = readln().chomp()) !is null)
	{
		auto newLine = removechars(line, ['\x20']);
		auto curInput = to!long(newLine);
		if ( curCountIceCream + curInput >= 0 )
			curCountIceCream += curInput;
		else
			notSatisfiedCount++;
		curLen++;
		if ( curLen == leng)
			break;
	}

	writeln( curCountIceCream , " " , notSatisfiedCount);

    return 0;
}


There is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i, j) (i < j) exists such that  or , where  denotes intersection of sets, and  denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and columns of the grid, respectively. Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup.

If the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes). You can print each character in any case (upper or lower).

NoteFor the first example, the desired setup can be produced by 3 operations, as is shown below.  For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column.

/+ dub.sdl:
    name "A"
    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 h, w;
    sc.read(h, w);

    bool[][] g = new bool[][](h, w);
    foreach (i; 0..h) {
        string s;
        sc.read(s);
        foreach (j; 0..w) {
            g[i][j] = (s[j] == '#');
        }
    }

    bool[][] g2 = new bool[][](h, w);

    foreach (i; 0..h) {
        foreach (j; 0..w) {
            if (!g[i][j]) continue;
            int[] hv, wv;
            foreach (i2; 0..h) {
                if (g[i2][j]) hv ~= i2;
            }
            foreach (j2; 0..w) {
                if (g[i][j2]) wv ~= j2;
            }

            foreach (i2; hv) {
                foreach (j2; wv) {
                    g2[i2][j2] = true;
                }
            }
        }
    }

    foreach (i; 0..h) {
        foreach (j; 0..w) {
            if (g[i][j] != g2[i][j]) {
                writeln("No");
                return 0;
            }
        }
    }
    writeln("Yes");

    // foreach (v; g2) {
    //     writeln(v.map!(x => x ? '#' : '.'));
    // }
    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)); }

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const M = readInt();
      const N = readInt();
      auto A = new string[M];
      foreach (x; 0 .. M) {
        A[x] = readToken();
      }

      auto uf = new int[M + N];
      uf[] = -1;
      foreach (x; 0 .. M) foreach (y; 0 .. N) {
        if (A[x][y] == '#') {
          uf.connect(x, M + y);
        }
      }
      auto board = new char[][](M, N);
      foreach (x; 0 .. M) foreach (y; 0 .. N) {
        board[x][y] = (uf.root(x) == uf.root(M + y)) ? '#' : '.';
      }
      bool ans = true;
      foreach (x; 0 .. M) foreach (y; 0 .. N) {
        ans = ans && (A[x][y] == board[x][y]);
      }
      writeln(ans ? "Yes" : "No");
    }
  } catch (EOFException e) {
  }
}

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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T t){t=new T(n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(ElementType!T);r.popFront;}}
void readM(T...)(size_t n,ref T t){foreach(ref v;t)v=new typeof(v)(n);foreach(i;0..n){auto r=readln.splitter;foreach(ref v;t){v[i]=r.front.to!(ElementType!(typeof(v)));r.popFront;}}}
void readS(T)(size_t n,ref T t){t=new T(n);foreach(ref v;t){auto r=readln.splitter;foreach(ref j;v.tupleof){j=r.front.to!(typeof(j));r.popFront;}}}

void main()
{
  int n, m; readV(n, m);
  string[] s; readM(n, s);

  s = s.sort().uniq.array;

  auto b = new int[](m);
  foreach (si; s)
    b[] += si.map!(c => c == '#' ? 1 : 0).array[];

  writeln(b.all!"a<=1" ? "Yes" : "No");
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readC(T...)(size_t n,ref T t){foreach(ref v;t)v=new typeof(v)(n);foreach(i;0..n){auto r=rdsp;foreach(ref v;t)pick(r,v[i]);}}

void main()
{
  int n, m; readV(n, m);
  string[] s; readC(n, s);

  s = s.sort().uniq.array;

  auto b = new int[](m);
  foreach (si; s)
    b[] += si.map!(c => c == '#' ? 1 : 0).array[];

  writeln(b.all!"a<=1" ? "Yes" : "No");
}