Wherever the destination is, whoever we meet, let's render this song together.On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups:   Vertical: stands at (xi, 0), moves in positive y direction (upwards);  Horizontal: stands at (0, yi), moves in positive x direction (rightwards).   According to choreography, the i-th dancer should stand still for the first ti milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on.  Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.

The first line of input contains three space-separated positive integers n, w and h (1 ≤ n ≤ 100 000, 2 ≤ w, h ≤ 100 000) — the number of dancers and the width and height of the stage, respectively. The following n lines each describes a dancer: the i-th among them contains three space-separated integers gi, pi, and ti (1 ≤ gi ≤ 2, 1 ≤ pi ≤ 99 999, 0 ≤ ti ≤ 100 000), describing a dancer's group gi (gi = 1 — vertical, gi = 2 — horizontal), position, and waiting time. If gi = 1 then pi = xi; otherwise pi = yi. It's guaranteed that 1 ≤ xi ≤ w - 1 and 1 ≤ yi ≤ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.

Output n lines, the i-th of which contains two space-separated integers (xi, yi) — the stopping position of the i-th dancer in the input.

NoteThe first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure.  In the second example, no dancers collide.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto W = s[1];
    auto H = s[2];

    auto P = new Tuple!(int, int)[](N);
    Tuple!(int, int, int)[][int] tate;
    Tuple!(int, int, int)[][int] yoko;

    foreach (i; 0..N) {
        s = readln.split.map!(to!int);
        if (s[0] == 1) {
            P[i] = tuple(s[1], H);
            tate[s[1] - s[2]] ~= tuple(i, s[1], -s[2]);
        } else {
            P[i] = tuple(W, s[1]);
            yoko[s[1] - s[2]] ~= tuple(i, -s[2], s[1]);
        }
    }

    foreach (k; tate.keys)
        tate[k].sort!"a[1] < b[1]";

    foreach (k; yoko.keys)
        yoko[k].sort!"a[2] < b[2]";

    auto ans = new int[](N);

    foreach (k; tate.keys) {
        if (!(k in yoko)) {
            foreach (v; tate[k])
                ans[v[0]] = v[0];
            continue;
        }

        DList!(int) queue;
        foreach (v; yoko[k])
            queue.insertFront(v[0]);

        foreach (v; tate[k]) {
            auto n = queue.front;
            queue.removeFront;
            ans[n] = v[0];
            queue.insertBack(v[0]);
        }

        for (int i = yoko[k].length.to!int - 1; !queue.empty; i--) {
            auto n = queue.front;
            queue.removeFront;
            ans[n] = yoko[k][i][0];
        }
    }

    foreach (k; yoko.keys) {
        if (!(k in tate)) {
            foreach (v; yoko[k]) {
                ans[v[0]] = v[0];
            }
        }
    }

    ans.each!(a => writeln(P[a][0], " ", P[a][1]));
}

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

struct Dancer {
  int g, p, t;
  int id;
  int diff;
}

struct Pt {
  int x, y;
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const W = readInt();
      const H = readInt();
      auto D = new Dancer[N];
      foreach (i; 0 .. N) {
        D[i].g = readInt();
        D[i].p = readInt();
        D[i].t = readInt();
        D[i].id = i;
      }

      foreach (i; 0 .. N) {
        D[i].diff = D[i].t - D[i].p;
      }
      D.sort!((a, b) =>
          (a.diff != b.diff) ? (a.diff < b.diff)
                             : (a.g != b.g) ? (a.g > b.g)
                                            : (a.g == 2) ? (a.p > b.p) : (a.p < b.p));

      auto ans = new Pt[N];
      for (int i = 0, j; i < N; i = j) {
        for (j = i; j < N && D[i].diff == D[j].diff; ++j) {}
        debug {
          writeln("D[i .. j] = ", D[i .. j]);
        }
        Pt[] ps;
        foreach (k; i .. j) {
          ps ~= (D[k].g == 1) ? Pt(D[k].p, H) : Pt(W, D[k].p);
        }
        ps.sort!((p, q) => (p.x != q.x) ? (p.x < q.x) : (p.y > q.y));
        debug {
          writeln("ps = ", ps);
        }
        foreach (k; i .. j) {
          ans[D[k].id] = ps[k - i];
        }
      }

      foreach (i; 0 .. N) {
        writeln(ans[i].x, " ", ans[i].y);
      }
    }
  } catch (EOFException e) {
  }
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  struct InputData
  {
    int g, p, t;
  }
  struct Point
  {
    long x, y;
  }
  auto n = next!int;
  auto w = next!int;
  auto h = next!int;
  auto idata = new InputData[](n);
  auto point = new Point[](n);
  foreach(p; 0 .. n)
    {
      idata[p].g = next!int;
      idata[p].p = next!int;
      idata[p].t = next!int;
      if (idata[p].g == 1)
	{
	  point[p].x = idata[p].p;
	  point[p].y = -idata[p].t;
	}
      else
	{
	  point[p].y = idata[p].p;
	  point[p].x = -idata[p].t;
	}
    }
  int[][long] lineids;
  foreach(i, p; point)
    {
      lineids.require(p.y + p.x, null) ~= cast(int) i;
    }
  foreach(ref line; lineids)
    {
      sort!((i, j) => point[i].x < point[j].x)(line);
      debug writeln(line);
    }
  auto endid = new int[](n);
  foreach(ref line; lineids)
    {
      int nH = 0;
      foreach(id; line)
	{
	  if (idata[id].g == 1) break;
	  nH++;
	}
      int nV = cast(int) line.length - nH;
      foreach(k; 0 .. nV)
	{
	  endid[line[k]] = line[$ - nV + k];
	}
      foreach(k; 0 .. nH)
	{
	  endid[line[nV + k]] = line[k];
	}
    }
  Point endPos(int id)
  {
    if (idata[id].g == 1)
      {
	return Point(idata[id].p, h);
      }
    return Point(w, idata[id].p);
  }

  foreach(i; 0 .. n)
    {
      auto p = endPos(endid[i]);
      writeln(p.x, " ", p.y);
    }
  writeln;
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. The dragon has a hit point of $$$x$$$ initially. When its hit point goes to $$$0$$$ or under $$$0$$$, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells.  Void Absorption Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will become $$$\left\lfloor \frac{h}{2} \right\rfloor + 10$$$. Here $$$\left\lfloor \frac{h}{2} \right\rfloor$$$ denotes $$$h$$$ divided by two, rounded down. Lightning Strike This spell will decrease the dragon's hit point by $$$10$$$. Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will be lowered to $$$h-10$$$.Due to some reasons Kana can only cast no more than $$$n$$$ Void Absorptions and $$$m$$$ Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — the number of test cases. The next $$$t$$$ lines describe test cases. For each test case the only line contains three integers $$$x$$$, $$$n$$$, $$$m$$$ ($$$1\le x \le 10^5$$$, $$$0\le n,m\le30$$$)  — the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.

If it is possible to defeat the dragon, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteOne possible casting sequence of the first test case is shown below: Void Absorption $$$\left\lfloor \frac{100}{2} \right\rfloor + 10=60$$$. Lightning Strike $$$60-10=50$$$. Void Absorption $$$\left\lfloor \frac{50}{2} \right\rfloor + 10=35$$$. Void Absorption $$$\left\lfloor \frac{35}{2} \right\rfloor + 10=27$$$. Lightning Strike $$$27-10=17$$$. Lightning Strike $$$17-10=7$$$. Lightning Strike $$$7-10=-3$$$.

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto xnm = readln.split.to!(int[]);
        auto X = xnm[0];
        auto N = xnm[1];
        auto M = xnm[2];

        while (N > 0 && X/2 >= 10) {
            X = X/2 + 10;
            --N;
        }
        writeln(X <= M*10 ? "YES" : "NO");
    }
}

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

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in 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) {
    int x = r.next!uint;
    const n = r.next!uint;
    const m = r.next!uint;
    foreach (i; 0 .. n) {
      const y = (x / 2) + 10;
      if (y >= x) break;
      x = y;
    }
    x -= m * 10;
    writeln (x > 0 ? "NO" : "YES");
  }
}

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 bool[](t);
	foreach (ti; 0..t)
	{
		auto x = RD;
		auto n = RD!int;
		auto m = RD!int;

		foreach (i; 0..n)
		{
			if (x <= 19) break;
			x = x / 2 + 10;
		}
		ans[ti] = x <= m*10;
	}

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


You are given three multisets of pairs of colored sticks:   $$$R$$$ pairs of red sticks, the first pair has length $$$r_1$$$, the second pair has length $$$r_2$$$, $$$\dots$$$, the $$$R$$$-th pair has length $$$r_R$$$;  $$$G$$$ pairs of green sticks, the first pair has length $$$g_1$$$, the second pair has length $$$g_2$$$, $$$\dots$$$, the $$$G$$$-th pair has length $$$g_G$$$;  $$$B$$$ pairs of blue sticks, the first pair has length $$$b_1$$$, the second pair has length $$$b_2$$$, $$$\dots$$$, the $$$B$$$-th pair has length $$$b_B$$$; You are constructing rectangles from these pairs of sticks with the following process:   take a pair of sticks of one color;  take a pair of sticks of another color different from the first one;  add the area of the resulting rectangle to the total area. Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.What is the maximum area you can achieve?

The first line contains three integers $$$R$$$, $$$G$$$, $$$B$$$ ($$$1 \le R, G, B \le 200$$$) — the number of pairs of red sticks, the number of pairs of green sticks and the number of pairs of blue sticks. The second line contains $$$R$$$ integers $$$r_1, r_2, \dots, r_R$$$ ($$$1 \le r_i \le 2000$$$) — the lengths of sticks in each pair of red sticks. The third line contains $$$G$$$ integers $$$g_1, g_2, \dots, g_G$$$ ($$$1 \le g_i \le 2000$$$) — the lengths of sticks in each pair of green sticks. The fourth line contains $$$B$$$ integers $$$b_1, b_2, \dots, b_B$$$ ($$$1 \le b_i \le 2000$$$) — the lengths of sticks in each pair of blue sticks.

Print the maximum possible total area of the constructed rectangles.

NoteIn the first example you can construct one of these rectangles: red and green with sides $$$3$$$ and $$$5$$$, red and blue with sides $$$3$$$ and $$$4$$$ and green and blue with sides $$$5$$$ and $$$4$$$. The best area of them is $$$4 \times 5 = 20$$$.In the second example the best rectangles are: red/blue $$$9 \times 8$$$, red/blue $$$5 \times 5$$$, green/blue $$$2 \times 1$$$. So the total area is $$$72 + 25 + 2 = 99$$$.In the third example the best rectangles are: red/green $$$19 \times 8$$$ and red/blue $$$20 \times 11$$$. The total area is $$$152 + 220 = 372$$$. Note that you can't construct more rectangles because you are not allowed to have both pairs taken to be the same color.

// Vicfred
// https://codeforces.com/contest/1398/problem/D
//
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    uint R, G, B;
    readf("%s %s %s", &R, &G, &B);
    readln;

    long[] r = readln.split.map!(to!long).array;
    long[] g = readln.split.map!(to!long).array;
    long[] b = readln.split.map!(to!long).array;

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

    long[][][] dp = new long[][][](R+1, G+1, B+1);

    long ans = long.min;
    for(int i = 0; i <= R; i++) {
        for(int j = 0; j <= G; j++) {
            for(int k = 0; k <= B; k++) {
                if(i < R && j < G)
                    dp[i + 1][j + 1][k] = max(dp[i + 1][j + 1][k], dp[i][j][k] + r[i] * g[j]);
                if(i < R && k < B)
                    dp[i + 1][j][k + 1] = max(dp[i + 1][j][k + 1], dp[i][j][k] + r[i] * b[k]);
                if(j < G && k < B)
                    dp[i][j + 1][k + 1] = max(dp[i][j + 1][k + 1], dp[i][j][k] + g[j] * b[k]);
                ans = max(ans, dp[i][j][k]);
            }
        }
    }
    ans.writeln;
}

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

void main ()
{
	int nR, nG, nB;
	while (readf !(" %s %s %s") (nR, nG, nB) > 0)
	{
		readln;
		auto r = readln.splitter.map !(to !(int)).array;
		auto g = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		sort !(q{a > b}) (r);
		sort !(q{a > b}) (g);
		sort !(q{a > b}) (b);
		auto f = new int [] [] [] (nR + 1, nG + 1, nB + 1);
		int res = 0;
		foreach (i; 0..nR + 1)
		{
			foreach (j; 0..nG + 1)
			{
				foreach (k; 0..nB + 1)
				{
					if (i > 0 && j > 0)
					{
						f[i][j][k] = max (f[i][j][k],
						    f[i - 1][j - 1][k] +
						    r[i - 1] * g[j - 1]);
					}
					if (j > 0 && k > 0)
					{
						f[i][j][k] = max (f[i][j][k],
						    f[i][j - 1][k - 1] +
						    g[j - 1] * b[k - 1]);
					}
					if (i > 0 && k > 0)
					{
						f[i][j][k] = max (f[i][j][k],
						    f[i - 1][j][k - 1] +
						    r[i - 1] * b[k - 1]);
					}
					res = max (res, f[i][j][k]);
				}
			}
		}
		writeln (res);
	}
}

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 R = RD!int;
	auto G = RD!int;
	auto B = RD!int;
	auto r = RDA!int;
	auto g = RDA!int;
	auto b = RDA!int;
	r.sort!"a > b";
	g.sort!"a > b";
	b.sort!"a > b";

	long ans;
	auto dp = new long[][][](R+1, G+1, B+1);
	foreach (i; 0..(R+G+B)+2)
	{
		if (i % 2 == 1) continue;
		foreach (ri; 0..i)
		{
			if (ri > R) break;
			foreach (gi; 0..i-(ri+1))
			{
				if (gi > G) break;
				auto bi = i-(ri+1)-(gi+1);
				if (bi > B) continue;

				if (ri < R && gi < G)
				{
					dp[ri+1][gi+1][bi].chmax(dp[ri][gi][bi] + r[ri]*g[gi]);
					ans.chmax(dp[ri+1][gi+1][bi]);
				}
				if (ri < R && bi < B)
				{
					dp[ri+1][gi][bi+1].chmax(dp[ri][gi][bi] + r[ri]*b[bi]);
					ans.chmax(dp[ri+1][gi][bi+1]);
				}
				if (gi < G && bi < B)
				{
					dp[ri][gi+1][bi+1].chmax(dp[ri][gi][bi] + g[gi]*b[bi]);
					ans.chmax(dp[ri][gi+1][bi+1]);
				}
				debug writeln(ri, ",", gi, ",", bi, " ans:", ans);
			}
		}
	}

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

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

void main ()
{
	int nR, nG, nB;
	while (readf !(" %s %s %s") (nR, nG, nB) > 0)
	{
		readln;
		auto r = readln.splitter.map !(to !(int)).array ~ 0;
		auto g = readln.splitter.map !(to !(int)).array ~ 0;
		auto b = readln.splitter.map !(to !(int)).array ~ 0;
		sort !(q{a > b}) (r);
		sort !(q{a > b}) (g);
		sort !(q{a > b}) (b);
		int res = 0;
		foreach (rg; 0..min (nR, nG) + 1)
		{
			foreach (gb; 0..min (nG, nB) + 1)
			{
				foreach (br; 0..min (nB, nR) + 1)
				{
					if (rg + br > nR ||
					    rg + gb > nG ||
					    gb + br > nB)
					{
						break;
					}
					int temp = 0;
					int i = 0, j = 0, k = 0;
					int u = 0, v = 0, w = 0;
					while (true)
					{
						int cur = 0;
						int pos = -1;
						if (u < rg &&
						    cur < r[i] * g[j])
						{
							cur = r[i] * g[j];
							pos = 0;
						}
						if (v < gb &&
						    cur < g[j] * b[k])
						{
							cur = g[j] * b[k];
							pos = 1;
						}
						if (w < br &&
						    cur < b[k] * r[i])
						{
							cur = b[k] * r[i];
							pos = 2;
						}
						if (pos == -1)
						{
							break;
						}
						temp += cur;
						if (pos == 0)
						{
							u += 1;
							i += 1;
							j += 1;
						}
						if (pos == 1)
						{
							v += 1;
							j += 1;
							k += 1;
						}
						if (pos == 2)
						{
							w += 1;
							k += 1;
							i += 1;
						}
					}
					res = max (res, temp);
				}
			}
		}
		writeln (res);
	}
}

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 R = RD!int;
	auto G = RD!int;
	auto B = RD!int;
	auto r = RDA!int;
	auto g = RDA!int;
	auto b = RDA!int;
	r.sort!"a > b";
	g.sort!"a > b";
	b.sort!"a > b";

	long ans;
	auto dp = new long[][][](R+1, G+1, B+1);
	foreach (i; 0..(R+G+B)+1)
	{
		if (i % 2 == 1) continue;
		foreach (ri; 0..i)
		{
			if (ri > R) break;
			foreach (gi; 0..i-(ri+1))
			{
				if (gi > G) break;
				auto bi = i-(ri+1)-(gi+1);
				if (bi > B) break;

				if (ri < R && gi < G)
				{
					dp[ri+1][gi+1][bi].chmax(dp[ri][gi][bi] + r[ri]*g[gi]);
					ans.chmax(dp[ri+1][gi+1][bi]);
				}
				if (ri < R && bi < B)
				{
					dp[ri+1][gi][bi+1].chmax(dp[ri][gi][bi] + r[ri]*b[bi]);
					ans.chmax(dp[ri+1][gi][bi+1]);
				}
				if (gi < G && bi < B)
				{
					dp[ri][gi+1][bi+1].chmax(dp[ri][gi][bi] + g[gi]*b[bi]);
					ans.chmax(dp[ri][gi+1][bi+1]);
				}
				debug writeln(ri, ",", gi, ",", bi, " ans:", ans);
			}
		}
	}

	writeln(ans);
	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 R = RD!int;
	auto G = RD!int;
	auto B = RD!int;
	auto r = RDA!int;
	auto g = RDA!int;
	auto b = RDA!int;
	r.sort!"a > b";
	g.sort!"a > b";
	b.sort!"a > b";

	long ans;
	auto dp = new long[][][](R+1, G+1, B+1);
	foreach (i; 0..(R+G+B)+2)
	{
		if (i % 2 == 1) continue;
		foreach (ri; 0..i)
		{
			if (ri > R) break;
			foreach (gi; 0..i-(ri+1))
			{
				if (gi > G) break;
				auto bi = i-(ri+1)-(gi+1);
				if (bi > B) break;

				if (ri < R && gi < G)
				{
					dp[ri+1][gi+1][bi].chmax(dp[ri][gi][bi] + r[ri]*g[gi]);
					ans.chmax(dp[ri+1][gi+1][bi]);
				}
				if (ri < R && bi < B)
				{
					dp[ri+1][gi][bi+1].chmax(dp[ri][gi][bi] + r[ri]*b[bi]);
					ans.chmax(dp[ri+1][gi][bi+1]);
				}
				if (gi < G && bi < B)
				{
					dp[ri][gi+1][bi+1].chmax(dp[ri][gi][bi] + g[gi]*b[bi]);
					ans.chmax(dp[ri][gi+1][bi+1]);
				}
				debug writeln(ri, ",", gi, ",", bi, " ans:", ans);
			}
		}
	}

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


Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.

The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.

Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.

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 C = new int[N],
         T = new int[N];
    foreach (i; 0 .. N) {
        int c, t; scanf("%d %d\n", &c, &t);
        C[i] = c;
        T[i] = t;
    }
    auto qs = readln.chomp.split(" ").map!(to!int).array;

    int cur_time = 0;
    int index = 0;
    foreach (q; qs) {
first:;
        if (cur_time <= q && q <= cur_time + C[index] * T[index]) {
            writeln(index + 1);
        } else {
            cur_time += C[index] * T[index];
            index++;
            goto first;
        }
    }
}


There are $$$n$$$ bags with candies, initially the $$$i$$$-th bag contains $$$i$$$ candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: Choose $$$m$$$ such that $$$1 \le m \le 1000$$$Perform $$$m$$$ operations. In the $$$j$$$-th operation, you will pick one bag and add $$$j$$$ candies to all bags apart from the chosen one.Your goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies. It can be proved that for the given constraints such a sequence always exists.You don't have to minimize $$$m$$$.If there are several valid sequences, you can output any.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of each test case contains one integer $$$n$$$ ($$$2 \le n\le 100$$$).

For each testcase, print two lines with your answer.  In the first line print $$$m$$$ ($$$1\le m \le 1000$$$) — the number of operations you want to take.  In the second line print $$$m$$$ positive integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_i \le n$$$), where $$$a_j$$$ is the number of bag you chose on the $$$j$$$-th operation.

NoteIn the first case, adding $$$1$$$ candy to all bags except of the second one leads to the arrangement with $$$[2, 2]$$$ candies.In the second case, firstly you use first three operations to add $$$1+2+3=6$$$ candies in total to each bag except of the third one, which gives you $$$[7, 8, 3]$$$. Later, you add $$$4$$$ candies to second and third bag, so you have $$$[7, 12, 7]$$$, and $$$5$$$ candies to first and third bag  — and the result is $$$[12, 12, 12]$$$.

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 long[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		foreach (i; 0..n)
		{
			ans[ti] ~= i+1;
		}
	}

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


Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.Recently, she was presented with an array $$$a$$$ of the size of $$$10^9$$$ elements that is filled as follows:   $$$a_1 = -1$$$  $$$a_2 = 2$$$  $$$a_3 = -3$$$  $$$a_4 = 4$$$  $$$a_5 = -5$$$  And so on ... That is, the value of the $$$i$$$-th element of the array $$$a$$$ is calculated using the formula $$$a_i = i \cdot (-1)^i$$$.She immediately came up with $$$q$$$ queries on this array. Each query is described with two numbers: $$$l$$$ and $$$r$$$. The answer to a query is the sum of all the elements of the array at positions from $$$l$$$ to $$$r$$$ inclusive.Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you — the best programmer.Help her find the answers!

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^3$$$) — the number of the queries. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 10^9$$$) — the descriptions of the queries.

Print $$$q$$$ lines, each containing one number — the answer to the query.

NoteIn the first query, you need to find the sum of the elements of the array from position $$$1$$$ to position $$$3$$$. The sum is equal to $$$a_1 + a_2 + a_3 = -1 + 2 -3 = -2$$$.In the second query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$5$$$. The sum is equal to $$$a_2 + a_3 + a_4 + a_5 = 2 -3 + 4 - 5 = -2$$$.In the third query, you need to find the sum of the elements of the array from position $$$5$$$ to position $$$5$$$. The sum is equal to $$$a_5 = -5$$$.In the fourth query, you need to find the sum of the elements of the array from position $$$4$$$ to position $$$4$$$. The sum is equal to $$$a_4 = 4$$$.In the fifth query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$3$$$. The sum is equal to $$$a_2 + a_3 = 2 - 3 = -1$$$.

import std.stdio;
void main() {
  int n, l, r;
  readf!"%d\n"(n);
  foreach(_; 0..n) {
    readf!"%d %d\n"(l, r);
    --l;
    writeln(r/2 - r%2*r - l/2 + l%2*l);
  }
}

import std.stdio;
void main() {
  int n, l, r;
  scanf("%d", &n);
  foreach(_; 0..n) {
    scanf("%d %d", &l, &r);
    --l;
    writeln(r/2 - r%2*r - l/2 + l%2*l);
  }
}

import std.stdio;
void main() {
  int n, l, r;
  readf!"%d "(n);
  foreach(_; 0..n) {
    readf!" %d %d"(l, r);
    writeln(r/2 - r%2*r - (--l)/2 + l%2*l);
  }
}

import std.stdio;
void main() {
  int n, l, r;
  scanf("%d", &n);
  foreach(_; 0..n) {
    scanf("%d %d", &l, &r);
    writeln(r/2 - r%2*r - (--l)/2 + l%2*l);
  }
}

import std.stdio;
void main() {
  int n, l, r;
  readf!"%d\n"(n);
  foreach(_; 0..n) {
    readf!"%d %d\n"(l, r);
    writeln(r/2 - r%2*r - (--l)/2 + l%2*l);
  }
}


You are given two binary square matrices $$$a$$$ and $$$b$$$ of size $$$n \times n$$$. A matrix is called binary if each of its elements is equal to $$$0$$$ or $$$1$$$. You can do the following operations on the matrix $$$a$$$ arbitrary number of times (0 or more):   vertical xor. You choose the number $$$j$$$ ($$$1 \le j \le n$$$) and for all $$$i$$$ ($$$1 \le i \le n$$$) do the following: $$$a_{i, j} := a_{i, j} \oplus 1$$$ ($$$\oplus$$$ — is the operation xor (exclusive or)).  horizontal xor. You choose the number $$$i$$$ ($$$1 \le i \le n$$$) and for all $$$j$$$ ($$$1 \le j \le n$$$) do the following: $$$a_{i, j} := a_{i, j} \oplus 1$$$. Note that the elements of the $$$a$$$ matrix change after each operation.For example, if $$$n=3$$$ and the matrix $$$a$$$ is: $$$$$$ \begin{pmatrix} 1 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 1 & 0 \end{pmatrix} $$$$$$ Then the following sequence of operations shows an example of transformations:   vertical xor, $$$j=1$$$. $$$$$$ a= \begin{pmatrix} 0 & 1 & 0 \\ 1 & 0 & 1 \\ 0 & 1 & 0 \end{pmatrix} $$$$$$  horizontal xor, $$$i=2$$$. $$$$$$ a= \begin{pmatrix} 0 & 1 & 0 \\ 0 & 1 & 0 \\ 0 & 1 & 0 \end{pmatrix} $$$$$$  vertical xor, $$$j=2$$$. $$$$$$ a= \begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix} $$$$$$ Check if there is a sequence of operations such that the matrix $$$a$$$ becomes equal to the matrix $$$b$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the size of the matrices. The following $$$n$$$ lines contain strings of length $$$n$$$, consisting of the characters '0' and '1' — the description of the matrix $$$a$$$. An empty line follows. The following $$$n$$$ lines contain strings of length $$$n$$$, consisting of the characters '0' and '1' — the description of the matrix $$$b$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case, output on a separate line:    "YES", there is such a sequence of operations that the matrix $$$a$$$ becomes equal to the matrix $$$b$$$;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

NoteThe first test case is explained in the statements.In the second test case, the following sequence of operations is suitable:   horizontal xor, $$$i=1$$$;  horizontal xor, $$$i=2$$$;  horizontal xor, $$$i=3$$$; It can be proved that there is no sequence of operations in the third test case so that the matrix $$$a$$$ becomes equal to the matrix $$$b$$$.

// Cheese-Cracker: cheese-cracker.github.io

void solve(){
    int n = scan!int;
    dchar[][] mat;
    for(int i = 0; i < n; ++i){
        mat ~= scan!(dchar[]);
    }

    dchar[][] req;
    for(int i = 0; i < n; ++i){
        req ~= scan!(dchar[]);
    }
    /* show(req); */
    /* if(n == 1){ writeln("YES"); return;} */

    int[] s1, d1;
    for(int j = 0; j < n; ++j){
        if(mat[0][j] == req[0][j]){
            s1 ~= j;
        }else{
            d1 ~= j;
        }
    }

    for(int i = 1; i < n; ++i){
        int[] di;
        for(int j = 0; j < n; ++j){
            if(mat[i][j] != req[i][j]){
                di ~= j;
            }
        }
        if(di != s1 && di != d1){
            writeln("NO");
            return;
        }
    }
    writeln("YES");
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/**************    *****    That's All Folks!    *****    **************/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        int N; get(N);
        char[][] A, B;
        get_lines(N, A);
        readln;
        get_lines(N, B);

        auto M = new bool[][](N, N);
        foreach (i; 0..N) foreach (j; 0..N) if (A[i][j] != B[i][j]) M[i][j] = true;
        foreach (i; 1..N) if (M[i-1][0] != M[i][0]) foreach (j; 0..N) M[i][j] = !M[i][j];
        foreach (j; 0..N) foreach (i; 0..N) if (M[i][j] != M[0][j]) goto ng;
        writeln("YES");
        continue;
        ng:
        writeln("NO");
    }
}


You are given a program that consists of $$$n$$$ instructions. Initially a single variable $$$x$$$ is assigned to $$$0$$$. Afterwards, the instructions are of two types:   increase $$$x$$$ by $$$1$$$;  decrease $$$x$$$ by $$$1$$$. You are given $$$m$$$ queries of the following format:   query $$$l$$$ $$$r$$$ — how many distinct values is $$$x$$$ assigned to if all the instructions between the $$$l$$$-th one and the $$$r$$$-th one inclusive are ignored and the rest are executed without changing the order?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the description of $$$t$$$ testcases follows. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of $$$n$$$ characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next $$$m$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the description of the query. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print $$$m$$$ integers — for each query $$$l$$$, $$$r$$$ print the number of distinct values variable $$$x$$$ is assigned to if all the instructions between the $$$l$$$-th one and the $$$r$$$-th one inclusive are ignored and the rest are executed without changing the order.

NoteThe instructions that remain for each query of the first testcase are:   empty program — $$$x$$$ was only equal to $$$0$$$;  "-" — $$$x$$$ had values $$$0$$$ and $$$-1$$$;  "---+" — $$$x$$$ had values $$$0$$$, $$$-1$$$, $$$-2$$$, $$$-3$$$, $$$-2$$$ — there are $$$4$$$ distinct values among them;  "+--+--+" — the distinct values are $$$1$$$, $$$0$$$, $$$-1$$$, $$$-2$$$.

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

struct SegmentTree(T, T unit, alias binop) {
    int n;
    T[] dat;
    this(int n_) {
        n = 1;
        while (n < n_) n *= 2;
        dat = new T[2*n+2];
        dat[] = unit;
    }
    void update(int k, in T a) {
        k += n - 1;
        dat[k] = a;
        while (k > 0) {
            k = (k - 1) / 2;
            dat[k] = binop(dat[k * 2 + 1], dat[k * 2 + 2]);
        }
    }
    T query(int a, int b) const {
        return query(a, b, 0, 0, n);
    }
    T query(int a, int b, int k, int l, int r) const {
        if (r <= a || b <= l) return unit;
        if (a <= l && r <= b) return dat[k];
        T vl = query(a, b, k * 2 + 1, l, (l + r) / 2),
          vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return binop(vl, vr);
    }
}

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

void solve() {
    int N, M; readf("%d %d\n", &N, &M);
    auto S = read!string;
    auto L = new int[M];
    auto R = new int[M];
    foreach (q; 0 .. M) {
        readf("%d %d\n", &L[q], &R[q]);
        L[q]--; R[q]--;
    }

    auto T = new int[N];
    for (int i = 0; i < N; i++) {
        T[i] = (S[i] == '+' ? +1 : -1);
    }
    auto PS = new int[N+1]; {
        for (int i = 0; i < N; i++) {
            PS[i+1] = PS[i] + T[i];
        }
    }
    const int INF = 1<<30;
    auto minT = SegmentTree!(int,  INF, (a, b) => min(a, b))(N+1);
    auto maxT = SegmentTree!(int, -INF, (a, b) => max(a, b))(N+1);
    for (int i = 0; i <= N; i++) {
        minT.update(i, PS[i]);
        maxT.update(i, PS[i]);
    }
    foreach (q; 0 .. M) {
        int l = L[q], r = R[q];
        auto xm = minT.query(0, l+1);
        auto xM = maxT.query(0, l+1);
        auto ym = minT.query(r+1, N+1);
        auto yM = maxT.query(r+1, N+1);
        auto p = PS[r+1] - PS[l];
        /*
        writeln(S);
        writeln([l, r]);
        writeln([xm, xM, ym, yM, p]);
        */
        auto ans = max(xM, yM - p) - min(xm, ym - p) + 1;
        writeln(ans);
    }
}

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

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

    while (t--) {
        auto v = readln.splitter.map!(to!int).array;
        auto n = v[0], m = v[1];
        auto arr = readln.chomp.array;

        int[] top, bot, pos;
        top ~= 0, bot ~= 0, pos ~= 0;
        int cur = 0;
        foreach (e; arr) {
            if (e == '+') { cur += 1; }
            else { cur -= 1; }

            pos ~= cur;
            top ~= max(top.back, cur);
            bot ~= min(bot.back, cur);
        }

        int[] topdst, botdst;
        topdst ~= 0;
        botdst ~= 0;
        cur = 0;
        foreach_reverse (i, e; arr) {
            int fromtop = topdst.back;
            int frombot = botdst.back;
            if (e == '+') {
                frombot -= 1;
                fromtop += 1;
            } else {
                fromtop -= 1;
                frombot += 1;
            }

            fromtop = max(fromtop, 0);
            frombot = max(frombot, 0);

            topdst ~= fromtop;
            botdst ~= frombot;
        }

        topdst.reverse();
        botdst.reverse();

        debug { writeln(pos, top, bot); }
        debug { writeln(topdst, botdst); }

        while (m--) {
            v = readln.splitter.map!(to!int).array;
            auto x = v[0], y = v[1];

            int topmax = max(top[x-1], pos[x-1] + topdst[y]);
            int botmin = min(bot[x-1], pos[x-1] - botdst[y]);
            int dist = topmax - botmin + 1;

            dist.writeln;
        }
    }
}

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

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

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

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

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

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

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

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

void main()
{
    int T; get(T);
    while (T--) {
        int N, M; get(N, M);
        char[] ii; get(ii);
        auto ps = new int[](N + 1);
        auto max_s = new int[](N + 1);
        auto min_s = new int[](N + 1);
        int max_p, min_p, p;
        foreach (i; 0..N) {
            p += (ii[i] == '+' ? 1 : -1);
            ps[i+1] = p;
            max_p = max(max_p, p);
            min_p = min(min_p, p);
            max_s[i+1] = max_p;
            min_s[i+1] = min_p;
        }
        auto max_r = new int[](N + 1);
        auto min_r = new int[](N + 1);
        p = max_p = min_p = 0;
        foreach_reverse (i; 0..N) {
            p += (ii[i] == '+' ? -1 : 1);
            max_p = max(max_p, p);
            min_p = min(min_p, p);
            max_r[i+1] = max_p - p;
            min_r[i+1] = min_p - p;
        }

        while (M--) {
            int l, r; get(l, r);
            p = ps[l-1];
            max_p = max_s[l-1];
            min_p = min_s[l-1];
            if (r != N) {
                max_p = max(max_p, max_r[r+1] + p);
                min_p = min(min_p, min_r[r+1] + p);
            }
            writeln(max_p - min_p + 1);
        }
    }
}

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

alias State = Tuple !(int, q{lo}, int, q{hi}, int, q{cur});

auto fun (S) (S s)
{
	State [] res;
	auto v = State (0, 0, 0);
	res ~= v;
	foreach (ref c; s)
	{
		v.cur += (c == '+') ? +1 : -1;
		v.lo = min (v.lo, v.cur);
		v.hi = max (v.hi, v.cur);
		res ~= v;
	}
	return res;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto c = readln.strip;
		auto pref = fun (c);
		auto suff = fun (c.retro);
		reverse (suff);
		foreach (q; 0..m)
		{
			int l, r;
			readf !(" %s %s") (l, r);
			l -= 1;
			auto v = pref[l];
			auto w = suff[r];
			v.lo = min (v.lo, v.cur - (w.hi - w.cur));
			v.hi = max (v.hi, v.cur - (w.lo - w.cur));
			writeln (v.hi - v.lo + 1);
		}
	}
}


There are $$$n$$$ candies in a row, they are numbered from left to right from $$$1$$$ to $$$n$$$. The size of the $$$i$$$-th candy is $$$a_i$$$.Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).Alice makes the first move. During the first move, she will eat $$$1$$$ candy (its size is $$$a_1$$$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.For example, if $$$n=11$$$ and $$$a=[3,1,4,1,5,9,2,6,5,3,5]$$$, then:  move 1: Alice eats one candy of size $$$3$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3,5]$$$.  move 2: Alice ate $$$3$$$ on the previous move, which means Bob must eat $$$4$$$ or more. Bob eats one candy of size $$$5$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3]$$$.  move 3: Bob ate $$$5$$$ on the previous move, which means Alice must eat $$$6$$$ or more. Alice eats three candies with the total size of $$$1+4+1=6$$$ and the sequence of candies becomes $$$[5,9,2,6,5,3]$$$.  move 4: Alice ate $$$6$$$ on the previous move, which means Bob must eat $$$7$$$ or more. Bob eats two candies with the total size of $$$3+5=8$$$ and the sequence of candies becomes $$$[5,9,2,6]$$$.  move 5: Bob ate $$$8$$$ on the previous move, which means Alice must eat $$$9$$$ or more. Alice eats two candies with the total size of $$$5+9=14$$$ and the sequence of candies becomes $$$[2,6]$$$.  move 6 (the last): Alice ate $$$14$$$ on the previous move, which means Bob must eat $$$15$$$ or more. It is impossible, so Bob eats the two remaining candies and the game ends. Print the number of moves in the game and two numbers:  $$$a$$$ — the total size of all sweets eaten by Alice during the game;  $$$b$$$ — the total size of all sweets eaten by Bob during the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases in the input. The following are descriptions of the $$$t$$$ test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of candies. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — the sizes of candies in the order they are arranged from left to right. It is guaranteed that the sum of the values of $$$n$$$ for all sets of input data in a test does not exceed $$$2\cdot10^5$$$.

For each set of input data print three integers — the number of moves in the game and the required values $$$a$$$ and $$$b$$$.

void main() {
	auto t = ri;
	foreach(T; 0..t) {
		auto n = ri;
		auto a = readAs!(int[]);
		int last;
		bool[] visited = new bool[](n);
		long alice, bob;
		long lalice, lbob;
		uint pa, pb = n - 1;
		ulong move;
		ulong k;
		loop: foreach(i; 0..10000) {
			bool flag = false;
			debug visited.map!(v => v+0).writeln;
			debug writefln("%d %d", pa, pb);
			if(i % 2 == 0) {
				lalice = 0;
				while(lalice <= lbob) {
					if(pa < n && !visited[pa]) {
						if(!flag) { flag = true; k++; }
						visited[pa] = true;
						alice += a[pa];
						lalice += a[pa];
						pa++;
					} else break loop;
				}
			} else {
				lbob = 0;
				while(lbob <= lalice) {
					if(pb > 0 && !visited[pb]) {
						if(!flag) { flag = true; k++; }
						visited[pb] = true;
						bob += a[pb];
						lbob += a[pb];
						pb--;
					} else break loop;
				}
			}
		}
		writefln("%d %d %d", k, alice, bob);
	}
}

// ===================================

import std.stdio;
import std.string;
import std.functional;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;

T readAs(T)() if (isBasicType!T) {
	return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
	return readln.split.to!T;
}

T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		res[i] = readAs!(T[]);
	}
	return res;
}

T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		auto s = rs;
		foreach(j; 0..width) res[i][j] = s[j].to!T;
	}
	return res;
}

int ri() {
	return readAs!int;
}

long rl() {
	return readAs!long;
}

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto N = readln.chomp.to!int;
        auto as = readln.split.to!(long[]);
        long a, sa, b, sb;
        int c;
        while (!as.empty) {
            ++c;
            long d;
            if (c%2 == 1) {
                do {
                    d += as[0];
                    as = as[1..$];
                } while (!as.empty && d <= b);
                a = d;
                sa += d;
            } else {
                do {
                    d += as[$-1];
                    as = as[0..$-1];
                } while (!as.empty && d <= a);
                b = d;
                sb += d;
            }
        }
        writeln(c, " ", sa, " ", sb);
    }
}

// Author: Ivan Kazmenko (gassa@mail.ru)
// excessive array copying on each step, should exceed ML or TL
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;
		int moves = 0;
		int prev = 0;
		int totalA = 0;
		int totalB = 0;
		while (!a.empty)
		{
			moves += 1;
			int curA = 0;
			while (!a.empty && curA <= prev)
			{
				curA += a[0];
				a = a[1..$].dup;
			}
			totalA += curA;
			prev = curA;

			if (a.empty)
			{
				break;
			}

			moves += 1;
			int curB = 0;
			while (!a.empty && curB <= prev)
			{
				curB += a[$ - 1];
				a = a[0..$ - 1].dup;
			}
			totalB += curB;
			prev = curB;
		}
		writeln (moves, " ", totalA, " ", totalB);
	}
}

// Author: Ivan Kazmenko (gassa@mail.ru)
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;
		int moves = 0;
		int prev = 0;
		int totalA = 0;
		int totalB = 0;
		while (!a.empty)
		{
			moves += 1;
			int curA = 0;
			while (!a.empty && curA <= prev)
			{
				curA += a.front;
				a.popFront ();
			}
			totalA += curA;
			prev = curA;

			if (a.empty)
			{
				break;
			}

			moves += 1;
			int curB = 0;
			while (!a.empty && curB <= prev)
			{
				curB += a.back;
				a.popBack ();
			}
			totalB += curB;
			prev = curB;
		}
		writeln (moves, " ", totalA, " ", totalB);
	}
}

// Author: Ivan Kazmenko (gassa@mail.ru)
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;
		int [2] total;
		int prev = 0;
		int moves = 0;
		while (!a.empty)
		{
			moves += 1;
			int cur = 0;
			while (!a.empty && cur <= prev)
			{
				cur += a[0];
				a = a[1..$];
			}
			total[moves % 2] += cur;
			prev = cur;
			reverse (a);
		}
		writeln (moves, " ", total[1], " ", total[0]);
	}
}

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

T readNum(T)(){
  return readStr.to!T;
}

T[] readNums(T)(){
  return readStr.split.to!(T[]);
}

string readStr(){
  return readln.chomp;
}

void main(){
  auto t = readNum!int;

  foreach(i; 0 .. t){
    auto n = readNum!int;
    auto a = readNums!int;

    int apos = 0, bpos = n-1;
    int asum, bsum;
    int move, eaten, requirement = a[0];

  mainloop: while(true){
      move++;

      while(eaten < requirement){
        eaten += a[apos];
        asum += a[apos];
        apos++;

        if(bpos < apos) break mainloop;
      }

      requirement = eaten+1;
      eaten = 0;

      move++;

      while(eaten < requirement){
        eaten += a[bpos];
        bsum += a[bpos];
        bpos--;

        if(bpos < apos) break mainloop;
      }

      requirement = eaten+1;
      eaten = 0;
    }

    writeln(move, " ", asum, " ", bsum);
  }
}

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, 3);
	foreach (ti; 0..t)
	{
		auto n = RD;
		auto a = RDA;

		long last;
		while (true)
		{
			if (a.empty) break;
			long x;
			while (!a.empty)
			{
				x += a.front; a.popFront;
				if (x > last) break;
			}
			++ans[ti][0];
			ans[ti][1] += x;
			last = x;

			if (a.empty) break;
			long y;
			while (!a.empty)
			{
				y += a.back; a.popBack;
				if (y > last) break;
			}
			++ans[ti][0];
			ans[ti][2] += y;
			last = y;
		}
	}

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


Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters.

The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times.

Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.

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() {
    double a, d;
    int n;
    scanf("%lf %lf\n", &a, &d);
    scanf("%d\n", &n);
    foreach (i; 0 .. n) {
        double t = (i + 1) * d;
        double s = t % (a * 4);
        double y, x;
        if (s <= a) {
            y = s;
            x = 0;
        } else if (s <= 2 * a) {
            y = a;
            x = s - a;
        } else if (s <= 3 * a) {
            y = a - (s - 2 * a);
            x = a;
        } else {
            y = 0;
            x = a - (s - 3 * a);
        }
        printf("%.8f %.8f\n", y, x);
    }
}

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() {
    double a, d;
    int n;
    scanf("%lf %lf\n", &a, &d);
    scanf("%d\n", &n);
    double t = 0;
    foreach (i; 0 .. n) {
        t += d;
        double s = t % (a * 4);
        double y, x;
        if (s <= a) {
            y = s;
            x = 0;
        } else if (s <= 2 * a) {
            y = a;
            x = s - a;
        } else if (s <= 3 * a) {
            y = a - (s - 2 * a);
            x = a;
        } else {
            y = 0;
            x = a - (s - 3 * a);
        }
        printf("%.8f %.8f\n", y, x);
    }
}

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() {
    double a, d;
    int n;
    scanf("%lf %lf\n", &a, &d);
    scanf("%d\n", &n);
    foreach (i; 0 .. n) {
        double t = i * d;
        double s = t % (a * 4);
        double y, x;
        if (s <= a) {
            y = s;
            x = 0;
        } else if (s <= 2 * a) {
            y = a;
            x = s - a;
        } else if (s <= 3 * a) {
            y = a - (s - 2 * a);
            x = a;
        } else {
            y = 0;
            x = a - (s - 3 * a);
        }
        printf("%.8f %.8f\n", y, x);
    }
}


Let's call two strings $$$s$$$ and $$$t$$$ anagrams of each other if it is possible to rearrange symbols in the string $$$s$$$ to get a string, equal to $$$t$$$.Let's consider two strings $$$s$$$ and $$$t$$$ which are anagrams of each other. We say that $$$t$$$ is a reducible anagram of $$$s$$$ if there exists an integer $$$k \ge 2$$$ and $$$2k$$$ non-empty strings $$$s_1, t_1, s_2, t_2, \dots, s_k, t_k$$$ that satisfy the following conditions:  If we write the strings $$$s_1, s_2, \dots, s_k$$$ in order, the resulting string will be equal to $$$s$$$;  If we write the strings $$$t_1, t_2, \dots, t_k$$$ in order, the resulting string will be equal to $$$t$$$;  For all integers $$$i$$$ between $$$1$$$ and $$$k$$$ inclusive, $$$s_i$$$ and $$$t_i$$$ are anagrams of each other. If such strings don't exist, then $$$t$$$ is said to be an irreducible anagram of $$$s$$$. Note that these notions are only defined when $$$s$$$ and $$$t$$$ are anagrams of each other.For example, consider the string $$$s = $$$ "gamegame". Then the string $$$t = $$$ "megamage" is a reducible anagram of $$$s$$$, we may choose for example $$$s_1 = $$$ "game", $$$s_2 = $$$ "gam", $$$s_3 = $$$ "e" and $$$t_1 = $$$ "mega", $$$t_2 = $$$ "mag", $$$t_3 = $$$ "e":  On the other hand, we can prove that $$$t = $$$ "memegaga" is an irreducible anagram of $$$s$$$.You will be given a string $$$s$$$ and $$$q$$$ queries, represented by two integers $$$1 \le l \le r \le |s|$$$ (where $$$|s|$$$ is equal to the length of the string $$$s$$$). For each query, you should find if the substring of $$$s$$$ formed by characters from the $$$l$$$-th to the $$$r$$$-th has at least one irreducible anagram.

The first line contains a string $$$s$$$, consisting of lowercase English characters ($$$1 \le |s| \le 2 \cdot 10^5$$$). The second line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$)  — the number of queries. Each of the following $$$q$$$ lines contain two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le |s|$$$), representing a query for the substring of $$$s$$$ formed by characters from the $$$l$$$-th to the $$$r$$$-th.

For each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.

NoteIn the first sample, in the first and third queries, the substring is "a", which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand, in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose $$$s_1 = $$$ "a", $$$s_2 = $$$ "aa", $$$t_1 = $$$ "a", $$$t_2 = $$$ "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto s = RD!string;
	auto cnt = new int[][](s.length+1);
	cnt[0] = new int[](26);
	foreach (i; 0..s.length)
	{
		cnt[i+1] = cnt[i].dup;
		auto num = s[i]-'a';
		cnt[i+1][num] += 1;
	}
	auto q = RD!int;
	auto ans = new bool[](q);
	foreach (qi; 0..q)
	{
		auto l = RD!int-1;
		auto r = RD!int-1;
		if (l == r || s[l] != s[r])
		{
			ans[qi] = true;
			continue;
		}
		long c;
		auto tmp = cnt[r+1].dup;
		tmp[] -= cnt[l][];
		foreach (i; 0..26)
		{
			if (i == s[l]-'a') continue;
			if (tmp[i] > 0)
				++c;
		}
		ans[qi] = c >= 2;
	}

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

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

immutable int letters = 26;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto n = s.length.to !(int);
		auto f = new int [letters] [n + 1];
		foreach (i; 0..n)
		{
			f[i + 1][] = f[i][];
			f[i + 1][s[i] - 'a'] += 1;
		}
		int q;
		readf (" %s", &q);
		foreach (j; 0..q)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u -= 1;
			int [letters] cur;
			cur[] = f[v][] - f[u][];
			auto diff = cur[].count !(x => x != 0);
			bool ok = (v - u == 1) || (diff > 2) ||
			    ((diff == 2) && (s[u] != s[v - 1]));
			writeln (ok ? "Yes" : "No");
		}
		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() {
  debug {
    bool check(int[] as) {
      if (as.length == 1) {
        return true;
      }
      if (as[0] != as[$ - 1]) {
        return true;
      }
      if (as.dup.sort.group.array.length >= 3) {
        return true;
      }
      return false;
    }

    enum lim = 5;
    foreach (n; 1 .. lim + 1) {
      foreach (p; 0 .. lim^^n) {
        auto as = new int[n];
        foreach (i; 0 .. n) {
          as[i] = p / lim^^i % lim;
        }
        auto bs = as.dup;
        bs.sort;
        bool hasIrred;
        do {
          bool irred = true;
          foreach (i; 1 .. n) {
            irred = irred && (as[0 .. i].dup.sort != bs[0 .. i].dup.sort);
          }
          hasIrred = hasIrred || irred;
        } while (bs.nextPermutation);
        if (!hasIrred) {
          writeln(as);
        }
        assert(hasIrred == check(as));
      }
    }
  }

  try {
    for (; ; ) {
      const S = readToken();
      const Q = readInt();
      auto L = new int[Q];
      auto R = new int[Q];
      foreach (q; 0 .. Q) {
        L[q] = readInt() - 1;
        R[q] = readInt();
      }

      const N = cast(int)(S.length);
      auto cnt = new int[][](26, N + 1);
      foreach (a; 0 .. 26) {
        foreach (i; 0 .. N) {
          cnt[a][i + 1] = cnt[a][i] + ((S[i] - 'a' == a) ? 1 : 0);
        }
      }

      foreach (q; 0 .. Q) {
        bool ans;
        if (R[q] - L[q] == 1) {
          ans = true;
        }
        if (S[L[q]] != S[R[q] - 1]) {
          ans = true;
        }
        int num;
        foreach (a; 0 .. 26) {
          if (cnt[a][R[q]] - cnt[a][L[q]] > 0) {
            ++num;
          }
        }
        if (num >= 3) {
          ans = true;
        }
        writeln(ans ? "Yes" : "No");
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto s = RD!string;
	auto cnt = new int[][](s.length+1);
	cnt[0] = new int[](26);
	foreach (i; 0..s.length)
	{
		cnt[i+1] = cnt[i].dup;
		auto num = s[i]-'a';
		cnt[i+1][num] += 1;
	}
	auto q = RD!int;
	auto ans = new bool[](q);
	foreach (qi; 0..q)
	{
		auto l = RD!int;
		auto r = RD!int;
		if (l == r)
		{
			ans[qi] = true;
			continue;
		}
		long c;
		auto tmp = cnt[r].dup;
		tmp[] -= cnt[l-1][];
		foreach (i; 0..26)
		{
			if (tmp[i] > 0)
				++c;
		}
		ans[qi] = c >= 2;
	}

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


Ania has a large integer $$$S$$$. Its decimal representation has length $$$n$$$ and doesn't contain any leading zeroes. Ania is allowed to change at most $$$k$$$ digits of $$$S$$$. She wants to do it in such a way that $$$S$$$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — the number of digits in the decimal representation of $$$S$$$ and the maximum allowed number of changed digits. The second line contains the integer $$$S$$$. It's guaranteed that $$$S$$$ has exactly $$$n$$$ digits and doesn't contain any leading zeroes.

Output the minimal possible value of $$$S$$$ which Ania can end with. Note that the resulting integer should also have $$$n$$$ digits.

NoteA number has leading zeroes if it consists of at least two digits and its first digit is $$$0$$$. For example, numbers $$$00$$$, $$$00069$$$ and $$$0101$$$ have leading zeroes, while $$$0$$$, $$$3000$$$ and $$$1010$$$ don't have leading zeroes.

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n = RD!int;
	auto k = RD!int;
	auto s = RD!string;

	foreach (i; 0..n)
	{
		if (i == 0)
		{
			if (n == 1)
			{
				if (k != 0)
					write("0");
				else
					write(s[i]);
			}
			else
			{
				if (k == 0 || s[i] == '1')
					write(s[i]);
				else
				{
					--k;
					write("1");
				}
			}
		}
		else
		{
			if (k == 0 || s[i] == '0')
				write(s[i]);
			else
			{
				--k;
				write("0");
			}
		}
	}

	writeln();
	stdout.flush();
	debug readln();
}


The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively.Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separated by dots. For example, the record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In this problem an arbitrary group of four 8-bit numbers is a correct IP address.Having worked as an administrator for some time, Polycarpus learned that if you know the IP address, you can use the subnet mask to get the address of the network that has this IP addess.The subnet mask is an IP address that has the following property: if we write this IP address as a 32 bit string, that it is representable as "11...11000..000". In other words, the subnet mask first has one or more one bits, and then one or more zero bits (overall there are 32 bits). For example, the IP address 2.0.0.0 is not a correct subnet mask as its 32-bit record looks as 00000010000000000000000000000000.To get the network address of the IP address, you need to perform the operation of the bitwise "and" of the IP address and the subnet mask. For example, if the subnet mask is 255.192.0.0, and the IP address is 192.168.1.2, then the network address equals 192.128.0.0. In the bitwise "and" the result has a bit that equals 1 if and only if both operands have corresponding bits equal to one.Now Polycarpus wants to find all networks to which his IP addresses belong. Unfortunately, Polycarpus lost subnet mask. Fortunately, Polycarpus remembers that his IP addresses belonged to exactly k distinct networks. Help Polycarpus find the subnet mask, such that his IP addresses will belong to exactly k distinct networks. If there are several such subnet masks, find the one whose bit record contains the least number of ones. If such subnet mask do not exist, say so.

The first line contains two integers, n and k (1 ≤ k ≤ n ≤ 105) — the number of IP addresses and networks. The next n lines contain the IP addresses. It is guaranteed that all IP addresses are distinct.

In a single line print the IP address of the subnet mask in the format that is described in the statement, if the required subnet mask exists. Otherwise, print -1.

import std.stdio;
import std.algorithm;

int rev(int x) {
    int res = 0;
    for (int i = 0; i < 8; i++) {
        if (x & (1 << (7 - i)))
            res |= (1 << i);
    }
    return res;
}

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

    int[][] masks;
    masks.length = n;

    for (int i = 0; i < n; i++) {
        masks[i].length = 4;
        readf("%d.%d.%d.%d\n", &masks[i][0], &masks[i][1], &masks[i][2], &masks[i][3]);
    }

    for (int i = 0; i < 4; i++) {
        for (int jj = 1; jj < 256; jj = (jj << 1) | 1) {
            int j = rev(jj);
            int[] nets;
            nets.length = n;

            for (int k = 0; k < n; k++) {
                for (int l = 0; l < i; l++) {
                    nets[k] <<= 8;
                    nets[k] |= masks[k][l];
                }
                nets[k] <<= 8;
                nets[k] |= (j & masks[k][i]);
            }

            sort(nets);

            int cnt = 1;
            for (int k = 1; k < n; k++) {
                if (nets[k] != nets[k - 1])
                    ++cnt;
            }

            if (cnt == K) {
                for (int k = 0; k < i; k++) {
                    write("255.");
                }
                write(j);
                for (int k = 0; k < (4 - i - 1); k++) {
                    write(".0");
                }
                writeln();
                return;
            }
        }
    }

    writeln(-1);
}

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int k, n;
	while (readf (" %s %s", &n, &k) > 0)
	{
		int [] a;
		foreach (i; 0..n)
		{
			ubyte [4] v;
			readf (" %d.%d.%d.%d", &v[0], &v[1], &v[2], &v[3]);
			uint s = 0;
			foreach (j; 0..4)
			{
				s = (s << 8) | v[j];
			}
			debug {writefln ("%08X", s);}
			a ~= s;
		}

		uint m = 0;
		long res = -1;
		foreach (i; 1..32)
		{
			m |= 1u << (32 - i);
			debug {writefln ("%08X", m);}
			auto b = redBlackTree !(int);
			foreach (c; a)
			{
				b.insert (c & m);
			}
			if (b.length == k)
			{
				res = m;
				break;
			}
		}
		if (res == -1)
		{
			writeln (res);
		}
		else
		{
			ubyte [4] v;
			foreach (j; 0..4)
			{
				v[j] = res & 0xFF;
				res >>= 8;
			}
			reverse (v[]);
			writefln ("%(%s.%)", v);
		}
	}
}

module sigod.codeforces.p291C;

import std.stdio;

private
enum MASK_INCREMENT = 0x80000000;

void main()
{
	int n, k;
	stdin.readf(" %s %s", &n, &k);

	uint[] ips = new uint[n];

	foreach (ref ip; ips) {
		ubyte b1, b2, b3, b4;
		stdin.readf(" %s.%s.%s.%s", &b1, &b2, &b3, &b4);

		ip = (((((b1 << 8) | b2) << 8) | b3) << 8) | b4;
	}

	uint mask = 0;

	foreach (x; 0 .. 32) {
		mask = (mask >> 1) | MASK_INCREMENT;

		bool[uint] webs;

		foreach (ip; ips) {
			webs[ip & mask] = true;
		}

		if (webs.length == k) {
			stdout.writeln(toIP(mask));
			return;
		}
	}

	stdout.writeln("-1");
}

private
string toIP(uint mask)
{
	ubyte b1, b2, b3, b4;

	b4 = mask & 0xFF;
	mask >>= 8;

	b3 = mask & 0xFF;
	mask >>= 8;

	b2 = mask & 0xFF;
	mask >>= 8;

	b1 = mask & 0xFF;

	return std.string.format("%s.%s.%s.%s", b1, b2, b3, b4);
}


How many specific orders do you know? Ascending order, descending order, order of ascending length, order of ascending polar angle... Let's have a look at another specific order: d-sorting. This sorting is applied to the strings of length at least d, where d is some positive integer. The characters of the string are sorted in following manner: first come all the 0-th characters of the initial string, then the 1-st ones, then the 2-nd ones and so on, in the end go all the (d - 1)-th characters of the initial string. By the i-th characters we mean all the character whose positions are exactly i modulo d. If two characters stand on the positions with the same remainder of integer division by d, their relative order after the sorting shouldn't be changed. The string is zero-indexed. For example, for string 'qwerty':Its 1-sorting is the string 'qwerty' (all characters stand on 0 positions),Its 2-sorting is the string 'qetwry' (characters 'q', 'e' and 't' stand on 0 positions and characters 'w', 'r' and 'y' are on 1 positions),Its 3-sorting is the string 'qrwtey' (characters 'q' and 'r' stand on 0 positions, characters 'w' and 't' stand on 1 positions and characters 'e' and 'y' stand on 2 positions),Its 4-sorting is the string 'qtwyer',Its 5-sorting is the string 'qywert'.You are given string S of length n and m shuffling operations of this string. Each shuffling operation accepts two integer arguments k and d and transforms string S as follows. For each i from 0 to n - k in the increasing order we apply the operation of d-sorting to the substring S[i..i + k - 1]. Here S[a..b] represents a substring that consists of characters on positions from a to b inclusive.After each shuffling operation you need to print string S.

The first line of the input contains a non-empty string S of length n, consisting of lowercase and uppercase English letters and digits from 0 to 9.  The second line of the input contains integer m – the number of shuffling operations (1 ≤ m·n ≤ 106).  Following m lines contain the descriptions of the operations consisting of two integers k and d (1 ≤ d ≤ k ≤ n).

After each operation print the current state of string S.

NoteHere is detailed explanation of the sample. The first modification is executed with arguments k = 4, d = 2. That means that you need to apply 2-sorting for each substring of length 4 one by one moving from the left to the right. The string will transform in the following manner:qwerty  →  qewrty  →  qerwty  →  qertwyThus, string S equals 'qertwy' at the end of first query.The second modification is executed with arguments k = 6, d = 3. As a result of this operation the whole string S is replaced by its 3-sorting: qertwy  →  qtewryThe third modification is executed with arguments k = 5, d = 2. qtewry  →  qertwy  →  qetyrw

import std.stdio, std.getopt, std.random, std.range, std.string, std.conv;
import std.algorithm, std.container, std.datetime;

struct Permutation {
	int N;
	int[] d;
	alias d this;

	this(int _N) {
		N = _N;
		d = iota(N).array;
	}

	Permutation opBinary(string op) (Permutation r) {
		static if (op == "*") {
			assert(N == r.N);
			auto tmp = Permutation(N);
			foreach (i; 0..N) {
				tmp[i] = r[d[i]];
			}
			return tmp;
		} else {
			static assert(false);
		}
	}

	void opOpAssign(string op) (Permutation r) {
		static if (op == "*") {
			this = this*r;
		} else {
			static assert(false);
		}
	}

	Permutation opBinary(string op) (long n) {
		static if (op == "^^") {
			auto x = this;
			auto r = Permutation(N);
			while (n) {
				if (n & 1) r *= x;
				x *= x;
				n >>= 1;
			}
			return r;
		}
		assert(false);
	}
}

int main() {
	char[] s = readln.strip.dup;
	auto n = cast(int)s.length;
	char[] s2 = new char[](n);
	auto m = readln.strip.to!int;
	auto sh = Permutation(n);
	foreach (i; 0..n) {
		sh[i] = (i-1+n)%n;
	}
	foreach (_ ; 0..m) {
		auto ins = readln.split.map!(to!int).array;
		auto k = ins[0], d = ins[1];
		auto p = Permutation(n);
		int u = 0, b = 0;
		foreach (i; 0..k) {
			p[u] = i;
			u += d;
			if (u >= k) {
				b++;
				u = b;
			}
		}
		auto ps = (p*sh)^^(n-k) * p * sh^^k;
		foreach (i; 0..n) {
			s2[ps[i]] = s[i];
		}
		s[] = s2[];
		writeln(s);
	}
    return 0;
}