Reminder: the median of the array $$$[a_1, a_2, \dots, a_{2k+1}]$$$ of odd number of elements is defined as follows: let $$$[b_1, b_2, \dots, b_{2k+1}]$$$ be the elements of the array in the sorted order. Then median of this array is equal to $$$b_{k+1}$$$.There are $$$2n$$$ students, the $$$i$$$-th student has skill level $$$a_i$$$. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the $$$2$$$ classes such that each class has odd number of students (not divisible by $$$2$$$). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of students halved. The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2 n}$$$ ($$$1 \le a_i \le 10^9$$$) — skill levels of students. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.

NoteIn the first test, there is only one way to partition students — one in each class. The absolute difference of the skill levels will be $$$|1 - 1| = 0$$$.In the second test, one of the possible partitions is to make the first class of students with skill levels $$$[6, 4, 2]$$$, so that the skill level of the first class will be $$$4$$$, and second with $$$[5, 1, 3]$$$, so that the skill level of the second class will be $$$3$$$. Absolute difference will be $$$|4 - 3| = 1$$$.Note that you can't assign like $$$[2, 3]$$$, $$$[6, 5, 4, 1]$$$ or $$$[]$$$, $$$[6, 5, 4, 1, 2, 3]$$$ because classes have even number of students.$$$[2]$$$, $$$[1, 3, 4]$$$ is also not possible because students with skills $$$5$$$ and $$$6$$$ aren't assigned to a class.In the third test you can assign the students in the following way: $$$[3, 4, 13, 13, 20], [2, 5, 8, 16, 17]$$$ or $$$[3, 8, 17], [2, 4, 5, 13, 13, 16, 20]$$$. Both divisions give minimal possible absolute difference.

import std.algorithm : max, maxElement;
import std.container : Array;
import std.stdio : stdin, write, writeln;
import std.typecons : Tuple, tuple;

struct IO {
    string readToken() {
        import std.range : empty, front, popFront, split;
        import std.stdio : readln;

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

    int readInt() {
        import std.conv : to;

        return readToken.to!int;
    }

    string[] tokens;
}

void main() {
    import std.math : abs;
    import std.algorithm : min, sort;

    IO io;
    int T = io.readInt;
    while (T--) {
        int n = io.readInt;
        int[] a = new int[n << 1];
        for (int i = 0; i < n << 1; ++i) {
            a[i] = io.readInt;
        }
        sort(a);
        int result = a[(n << 1) - 1] - a[0], half = n - 1;
        for (int i = 0; i < n << 1; ++i) {
            result = min(result, abs(a[i] - a[half + (half >= i)]));
        }
        writeln(result);
    }
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

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

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

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

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

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

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

    }
}

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

E[] makeSlice(E, S)(S size, lazy E value)
{
  auto a = new E[size.ind];
  foreach(ref ai; a)
    ai = value();
  return a;
}

E[] makeSlice(E, S)(S size = 0)
{
  return new E[size.ind];
}

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

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

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

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

void main()
{
 testCase:foreach(tc; 0 .. next!long)
    {
      auto n = next!long;
      auto a = makeSlice(2 * n, next!long);
      sort(a);
      writeln(abs(a.at(n - 1) - a.at(n)));
    }
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

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

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

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

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

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

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

    }
}

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

E[] makeSlice(E, S)(S size, lazy E value)
{
  auto a = new E[size.ind];
  foreach(ref ai; a)
    ai = value();
  return a;
}

E[] makeSlice(E, S)(S size = 0)
{
  return new E[size.ind];
}

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

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

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

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

void main()
{
  ()
  {
    auto n = next!long;
    auto a = makeSlice(2 * n, next!long);
    sort(a);
    writeln(abs(a.at(n - 1) - a.at(n)));
  }.rep(next!long);
}

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 t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;
		a.sort();

		ans[ti] = a[$/2] - a[$/2-1];
	}

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


Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are $$$n$$$ cards with $$$k$$$ features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with $$$k = 4$$$.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.

The first line of each test contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 1500$$$, $$$1 \le k \le 30$$$) — number of cards and number of features. Each of the following $$$n$$$ lines contains a card description: a string consisting of $$$k$$$ letters "S", "E", "T". The $$$i$$$-th character of this string decribes the $$$i$$$-th feature of that card. All cards are distinct.

Output a single integer — the number of ways to choose three cards that form a set.

NoteIn the third example test, these two triples of cards are sets:  "SETT", "TEST", "EEET"  "TEST", "ESTE", "STES"

import std.stdio;
import std.string: chomp;

enum Res { Unusable, Same, Different }

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

  string[] arr = new string[n];
  bool[][] pairs = new bool[][n];
  int[string] set;

  for(int i = 0; i < n; i++) {
    string s = readln().chomp();
    arr[i] = s;
    set[s] = i;

    pairs[i] = new bool[n];
  }

  int count = 0;

  for(int i = 0; i < (n - 1); i++) {
    for(int j = i + 1; j < n; j++) {
      if(pairs[i][j]) continue;
      pairs[i][j] = pairs[j][i] = true;
      string t = third(arr[i], arr[j], k);
      if(t in set) {
        count++;
        int x = set[t];
        pairs[i][x] = pairs[x][i] = true;
        pairs[j][x] = pairs[x][j] = true;
        // writeln(arr[i] ~ " " ~ arr[j] ~ " " ~ t);
      }
    }
  }

  writeln(count);
}

string third(string first, string second, int k) {
  char[] res = new char[k];
  for(int i = 0; i < k; i++) {
    res[i] = thirdChar(first[i], second[i]);
  }

  return cast(string)res;
}

char thirdChar(char first, char second) {
  if(first == 'S') {
    if(second == 'S') return 'S';
    if(second == 'E') return 'T';
    return 'E';
  }
  if(first == 'E') {
    if(second == 'E') return 'E';
    if(second == 'S') return 'T';
    return 'S';
  }
  if(second == 'T') return 'T';
  if(second == 'E') return 'S';
  return 'E';
}

import std.algorithm;
import std.conv : to;
import std.container;
import std.numeric : gcd;
import std.range;
import std.stdio;
import std.string;
import std.typecons : Tuple, tuple;

void main() {
    int n, m;
    readf!"%d %d\n"(n, m);
    auto s = new string[n];
    int res = 0;
    int[string] set;
    auto buf = new char[m];
    for (int i = 0; i < n; ++i) {
        s[i] = readln.chomp;
        for (int j = 0; j < i; ++j) {
            for (int k = 0; k < m; ++k) {
                buf[k] = s[i][k] == s[j][k] ? s[i][k] : 66 ^ s[i][k] ^ s[j][k];
            }
            res += set.get(cast(string) buf, 0);
        }
        set[s[i]] = 1;
    }
    writeln(res / 2);
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

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

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

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

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

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

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

    }
}

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

void main()
{
  int n, k;
  read(n, k);
  auto cards = makeArray!string(n, next!string);
  bool[string] hasCard;
  foreach(card; cards)
    hasCard[card] = true;
  char other(char c1, char c2)
  {
    if (c1 == c2)
      return c1;
    foreach(c; "SET")
      if (c1 != c && c2 != c)
        return c;
    assert(0);
  }
  int cnt = 0;
  foreach(i; 0 .. n)
    foreach(j; i + 1 .. n)
      {
        char[] otherString;
        foreach(ki; 0 .. k)
          otherString ~= other(cards.at(i).at(ki), cards.at(j).at(ki));
        if (otherString in hasCard)
          {
            cnt++;
          }
      }
  writeln(cnt/3);
}

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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void 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 main()
{
	auto n = RD!int;
	auto k = RD!int;
	auto s = new string[](n);
	foreach (i; 0..n)
		s[i] = RD!string;

	auto toNum = ['S':0, 'E':1, 'T':2];
	int[long] set;
	foreach (i; 0..n)
	{
		long key;
		foreach (j; 0..k)
		{
			auto num = toNum[s[i][j]];
			key += num * (3^^j);
		}
		++set[key];
		debug writeln("i:", i, " key:", key);
	}
	debug writeln(set);

	long ans;
	foreach (i; 0..n)
	{
		foreach (j; i+1..n)
		{
			long key;
			foreach (l; 0..k)
			{
				if (s[i][l] == s[j][l])
					key += toNum[s[i][l]] * (3^^l);
				else
				{
					auto num = 3 - (toNum[s[i][l]] + toNum[s[j][l]]);
					key += num * (3^^l);
				}
			}
			ans += set.get(key, 0);
			debug writeln("i:", i, " j:", j, " ans:", ans);
		}
	}

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


ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal —  and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?

The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0.

Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output  - 1 instead. If there are multiple solutions, you may print any of them.

NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square.

import std.stdio;

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

	long[500][500] m;
	int r, c;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			scanf("%lld", &m[i][j]);

			if (m[i][j] == 0) {
				r = i;
				c = j;
			}
		}
	}

	long sum = 0;
	long s = 1;
	if (n > 1) {
		int g = 0;
		if (r == 0) {
			g++;
		}

		for (int i = 0; i < n; i++) {
			sum += m[g][i];
		}

		s = sum;
		for (int i = 0; i < n; i++) {
			s -= m[r][i];
		}
	}
	else {
		sum = 1;
	}

	m[r][c] = s;

	long sumDiagL = 0;
	long sumDiagR = 0;
	for (int i = 0; i < n; i++) {
		long sumRow = 0;
		long sumCol = 0;

		for (int j = 0; j < n; j++) {
			sumRow += m[i][j];
			sumCol += m[j][i];
		}

		sumDiagL += m[i][i];
		sumDiagR += m[n - 1 - i][i];
		if (sumRow != sum || sumCol != sum) {
			s = -1;
		}
	}
	if (sumDiagL != sum || sumDiagR != sum) {
		s = -1;
	}

	if (s <= 0) {
		printf("-1\n");
	}
	else {
		printf("%lld\n", s);
	}
}

import std.stdio;

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

	long[50][50] m;
	int r, c;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			scanf("%lld", &m[i][j]);

			if (m[i][j] == 0) {
				r = i;
				c = j;
			}
		}
	}

	long sum = 0;
	long s = 1;
	if (n > 1) {
		int g = 0;
		if (r == 0) {
			g++;
		}

		for (int i = 0; i < n; i++) {
			sum += m[g][i];
		}

		s = sum;
		for (int i = 0; i < n; i++) {
			s -= m[r][i];
		}
	}

	m[r][c] = s;

	long sumDiagL = 0;
	long sumDiagR = 0;
	for (int i = 0; i < n; i++) {
		long sumRow = 0;
		long sumCol = 0;

		for (int j = 0; j < n; j++) {
			sumRow += m[i][j];
			sumCol += m[j][i];
		}

		sumDiagL += m[i][i];
		sumDiagR += m[n - 1 - i][i];
		if (sumRow != sum || sumCol != sum) {
			s = -1;
		}
	}
	if (sumDiagL != sum || sumDiagR != sum) {
		s = -1;
	}

	if (s <= 0) {
		printf("-1\n");
	}
	else {
		printf("%lld\n", s);
	}
}


Another Codeforces Round has just finished! It has gathered $$$n$$$ participants, and according to the results, the expected rating change of participant $$$i$$$ is $$$a_i$$$. These rating changes are perfectly balanced — their sum is equal to $$$0$$$.Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.There are two conditions though:   For each participant $$$i$$$, their modified rating change $$$b_i$$$ must be integer, and as close to $$$\frac{a_i}{2}$$$ as possible. It means that either $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$ or $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. In particular, if $$$a_i$$$ is even, $$$b_i = \frac{a_i}{2}$$$. Here $$$\lfloor x \rfloor$$$ denotes rounding down to the largest integer not greater than $$$x$$$, and $$$\lceil x \rceil$$$ denotes rounding up to the smallest integer not smaller than $$$x$$$.  The modified rating changes must be perfectly balanced — their sum must be equal to $$$0$$$. Can you help with that?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 13\,845$$$), denoting the number of participants. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$-336 \le a_i \le 1164$$$), denoting the rating change of the $$$i$$$-th participant. The sum of all $$$a_i$$$ is equal to $$$0$$$.

Output $$$n$$$ integers $$$b_i$$$, each denoting the modified rating change of the $$$i$$$-th participant in order of input. For any $$$i$$$, it must be true that either $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$ or $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. The sum of all $$$b_i$$$ must be equal to $$$0$$$. If there are multiple solutions, print any. We can show that a solution exists for any valid input.

NoteIn the first example, $$$b_1 = 5$$$, $$$b_2 = -3$$$ and $$$b_3 = -2$$$ is another correct solution.In the second example there are $$$6$$$ possible solutions, one of them is shown in the example output.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}
		auto b = new int [n];
		b[] = a[] / 2;
		auto delta = sum (b);
		foreach (i; 0..n)
		{
			if (delta > 0 && a[i] < 0 && a[i] % 2 != 0)
			{
				delta -= 1;
				b[i] -= 1;
			}
			if (delta < 0 && a[i] > 0 && a[i] % 2 != 0)
			{
				delta += 1;
				b[i] += 1;
			}
		}
		foreach (ref x; b)
		{
			writeln (x);
		}
	}
}

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

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

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

	int cntpos, cntneg;
	foreach(a; as){
		if(a % 2 == 0) (a / 2).writeln;
		else if(a > 0){
			cntpos += 1;
			if(cntpos % 2 == 0) ((a - 1) / 2).writeln;
			else ((a + 1) / 2).writeln;
		}
		else{
			cntneg += 1;
			if(cntneg % 2 == 0) ((a + 1) / 2).writeln;
			else ((a - 1) / 2).writeln;
		}
	}

}

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

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

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

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

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

      auto ans = new int[N];
      int cnt;
      foreach (i; 0 .. N) {
        if (A[i] % 2 == 0) {
          ans[i] = A[i] / 2;
        } else {
          if (cnt++ % 2 == 0) {
            ans[i] = (A[i] + 1) / 2;
          } else {
            ans[i] = (A[i] - 1) / 2;
          }
        }
      }
      foreach (i; 0 .. N) {
        writeln(ans[i]);
      }
    }
  } 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.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 ans = new long[](n);
	int cnt;
	foreach (i; 0..n)
	{
		auto a = RD!int;
		if (a % 2 == 0)
			ans[i] = a/2;
		else if (cnt == 0)
		{
			ans[i] = a/2;
			if (a < 0)
				--ans[i];
			++cnt;
		}
		else
		{
			ans[i] = a/2;
			if (a > 0)
				++ans[i];
			--cnt;
		}
	}

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


At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly $$$k$$$ flowers.The work material for the wreaths for all $$$n$$$ citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence $$$a_1$$$, $$$a_2$$$, ..., $$$a_m$$$, where $$$a_i$$$ is an integer that denotes the type of flower at the position $$$i$$$. This year the liana is very long ($$$m \ge n \cdot k$$$), and that means every citizen will get a wreath.Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts $$$k$$$ flowers from the beginning of the liana, then another $$$k$$$ flowers and so on. Each such piece of $$$k$$$ flowers is called a workpiece. The machine works until there are less than $$$k$$$ flowers on the liana.Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, $$$k$$$ flowers must contain flowers of types $$$b_1$$$, $$$b_2$$$, ..., $$$b_s$$$, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least $$$n$$$ workpieces?

The first line contains four integers $$$m$$$, $$$k$$$, $$$n$$$ and $$$s$$$ ($$$1 \le n, k, m \le 5 \cdot 10^5$$$, $$$k \cdot n \le m$$$, $$$1 \le s \le k$$$): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively. The second line contains $$$m$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_m$$$ ($$$1 \le a_i \le 5 \cdot 10^5$$$)  — types of flowers on the liana. The third line contains $$$s$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_s$$$ ($$$1 \le b_i \le 5 \cdot 10^5$$$)  — the sequence in Diana's schematic.

If it's impossible to remove some of the flowers so that there would be at least $$$n$$$ workpieces and at least one of them fullfills Diana's schematic requirements, output $$$-1$$$. Otherwise in the first line output one integer $$$d$$$  — the number of flowers to be removed by Diana. In the next line output $$$d$$$ different integers  — the positions of the flowers to be removed. If there are multiple answers, print any.

NoteIn the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$. Those workpieces don't fit Diana's schematic. But if you remove flower on $$$4$$$-th place, the machine would output workpieces $$$[1, 2, 3]$$$ and $$$[2, 1, 2]$$$. The second workpiece fits Diana's schematic.In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs.

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

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

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

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

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

      const lim = max(A.maxElement, B.maxElement) + 1;
      auto cnt = new int[lim];

      B.sort;
      const BGroup = B.group.array;

      const width = M - K * (N - 1);
      foreach (i; 0 .. width) {
        ++cnt[A[i]];
      }

      int[] ans;
      foreach (x; 0 .. N) {
        // K x to the left, K (N - 1 - x) to the right
        bool ok = true;
        foreach (g; BGroup) {
          ok = ok && (cnt[g[0]] >= g[1]);
        }
        if (ok) {
          debug {
            writeln("found x = ", x);
          }
          auto need = new int[lim];
          foreach (g; BGroup) {
            need[g[0]] += g[1];
          }
          foreach (i; K * x .. K * x + width) {
            if (need[A[i]] > 0) {
              --need[A[i]];
            } else {
              ans ~= i;
            }
          }
          if (ans.length >= width - K) {
            ans.length = width - K;
          }
          writeln(ans.length);
          foreach (index, i; ans) {
            if (index > 0) write(" ");
            write(i + 1);
          }
          writeln();
          goto found;
        }
        if (x + 1 < N) {
          foreach (i; K * x .. K * (x + 1)) {
            --cnt[A[i]];
            ++cnt[A[i + width]];
          }
        }
      }
      writeln(-1);
     found:
    }
  } 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]);
  auto m = next!int;
  auto k = next!int;
  auto n = next!int;
  auto s = next!int;
  auto a = next!int(m);
  auto b = next!int(s);
  auto reqCnt = b.getCnt;
  uint[int] cnt;
  auto pendingFulfill = redBlackTree!int(b);
  int i = 0;
  while(i < m && !pendingFulfill.empty)
    {
      cnt.require(a[i], 0)++;
      if (a[i] in pendingFulfill)
	if (cnt[a[i]] >= reqCnt[a[i]])
	    pendingFulfill.removeKey(a[i]);
      i++;
    }
  if (!pendingFulfill.empty) return (-1).writeln;
  i--;
  void dosol(int l, int h)
  {
    int toremove = h - l + 1 - k;
    debug writeln("solving with ", l, " ", h);
    writeln(toremove + l % k + (m - h - 1) % k);
    foreach(i; 1 .. l % k + 1) write(i, " ");
    {
      int i = l;
      while(toremove > 0)
	{
	  if (a[i] !in reqCnt || cnt[a[i]] - 1 >= reqCnt[a[i]])
	    {
	      write(i + 1, " ");
	      cnt[a[i]]--;
	      toremove--;
	    }
	  i++;
	}
    }
    foreach(i; h + 2 .. h + 2 + (m - h - 1) % k) write(i, " ");
    writeln;
  }
  int l = 0;
  while(a[l] !in reqCnt || cnt[a[l]] - 1 >= reqCnt[a[l]])
    {
      cnt[a[l]]--;
      l++;
    }

  while(i < m)
    {
      debug writeln("trying ", l, " ", i, " ");
      int len = i - l + 1;
      if (len < k)
	{
	  int rest = k - len;
	  int ll = l - rest;
	  if (ll >= 0)
	    {
	      auto toleft = ll / k;
	      auto toright = (m - i - 1) / k;
	      if (toleft + toright + 1 >= n)
		{
		  return dosol(ll, i);
		}
	    }
	}
      if (len >= k)
	{
	  auto toleft = l / k;
	  auto toright = (m - i - 1) / k;
	  debug writeln("r = ", toright, " l = ", toleft);
	  if (toleft + toright + 1 >= n)
	    {
	      return dosol(l, i);
	    }
	}

      i++; if (i >= m) break;
      cnt.require(a[i], 0)++;
      while(a[l] !in reqCnt || cnt[a[l]] - 1 >= reqCnt[a[l]])
	{
	  cnt[a[l]]--;
	  l++;
	}
    }
  return (-1).writeln;
}

auto getCnt(T)(T[] arr)
{
  uint[T] cnt;
  foreach(a; arr) cnt.require(a, 0)++;
  return cnt;
}

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

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

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

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

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

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

      const lim = max(A.maxElement, B.maxElement) + 1;
      auto cnt = new int[lim];

      B.sort;
      const BGroup = B.group.array;

      const width = M - K * (N - 1);
      foreach (i; 0 .. width) {
        ++cnt[A[i]];
      }
      int[] ans;
      foreach (x; 0 .. N) {
        // K x to the left, K (N - 1 - x) to the right
        bool ok = true;
        foreach (g; BGroup) {
          ok = ok && (cnt[g[0]] >= g[1]);
        }
        if (ok) {
          debug {
            writeln("found x = ", x);
          }
          auto need = new int[lim];
          foreach (g; BGroup) {
            need[g[0]] += g[1];
          }
          foreach (i; K * x .. K * x + width) {
            if (need[A[i]] > 0) {
              --need[A[i]];
            } else {
              ans ~= i;
              if (ans.length >= width - K) {
                break;
              }
            }
          }
          break;
        }
        if (x + 1 < N) {
          foreach (i; K * x .. K * (x + 1)) {
            --cnt[A[i]];
            ++cnt[A[i + width]];
          }
        }
      }

      if (!ans.empty) {
        writeln(ans.length);
        foreach (index, i; ans) {
          if (index > 0) write(" ");
          write(i + 1);
        }
        writeln();
      } else {
        writeln(-1);
      }
    }
  } catch (EOFException e) {
  }
}


You and your $$$n - 1$$$ friends have found an array of integers $$$a_1, a_2, \dots, a_n$$$. You have decided to share it in the following way: All $$$n$$$ of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the $$$m$$$-th position in the line. Before the process starts, you may choose up to $$$k$$$ different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer $$$x$$$ such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to $$$x$$$?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains three space-separated integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le m \le n \le 3500$$$, $$$0 \le k \le n - 1$$$)  — the number of elements in the array, your position in line and the number of people whose choices you can fix. The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3500$$$.

For each test case, print the largest integer $$$x$$$ such that you can guarantee to obtain at least $$$x$$$.

NoteIn the first test case, an optimal strategy is to force the first person to take the last element and the second person to take the first element.  the first person will take the last element ($$$5$$$) because he or she was forced by you to take the last element. After this turn the remaining array will be $$$[2, 9, 2, 3, 8]$$$;  the second person will take the first element ($$$2$$$) because he or she was forced by you to take the first element. After this turn the remaining array will be $$$[9, 2, 3, 8]$$$;  if the third person will choose to take the first element ($$$9$$$), at your turn the remaining array will be $$$[2, 3, 8]$$$ and you will take $$$8$$$ (the last element);  if the third person will choose to take the last element ($$$8$$$), at your turn the remaining array will be $$$[9, 2, 3]$$$ and you will take $$$9$$$ (the first element). Thus, this strategy guarantees to end up with at least $$$8$$$. We can prove that there is no strategy that guarantees to end up with at least $$$9$$$. Hence, the answer is $$$8$$$.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with $$$4$$$.

import std.algorithm : max, maxElement;
import std.container : Array;
import std.stdio : stdin, write, writeln;
import std.typecons : Tuple, tuple;

struct IO {
    string readToken() {
        import std.range : empty, front, popFront, split;
        import std.stdio : readln;

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

    int readInt() {
        import std.conv : to;

        return readToken.to!int;
    }

    long readLong() {
        import std.conv : to;

        return readToken.to!long;
    }

    string[] tokens;
}

void main() {
    import std.algorithm : max, min;

    IO io;
    int T = io.readInt;
    while (T--) {
        int n = io.readInt;
        int m = io.readInt - 1;
        int k = min(m, io.readInt);
        int[] a = new int[n];
        for (int i = 0; i < n; ++i) {
            a[i] = io.readInt();
        }
        int result = 0;
        for (int ctr = 0; ctr <= k; ++ctr) {
            int worst = cast(int) 1e9;
            for (int arb = 0; arb <= m - k; ++arb) {
                worst = min(worst, max(a[ctr + arb], a[n - 1 - (m - (ctr + arb))]));
            }
            result = max(result, worst);
        }
        writeln(result);
    }
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

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

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

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

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

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

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

    }
}

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

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

void main()
{
  auto t = next!long;
  foreach(tc; 0 .. t)
    {
      long n, m, k;
      read(n, m, k);
      auto a = makeArray(n, next!long);
      long rem = m - 1;
      k = min(k, rem);
      long r = rem - k;

      long minValue(long i, long j)
      {
        if (i > j)
          swap(i, j);
        if (i == j)
          return a.at(i);
        return min(mem!minValue(i, j - 1), a.at(j));
      }
      long partAns(long i, long j)
      {
        long res = long.max;
        assert(i >= 0 && i < n && j >= 0 && j < n);
        foreach(s; 0 .. r + 1)
          {
            res = min(res, max(a.at(i + s), a.at(j + s - r)));
          }
        return res;
      }
      long ans = long.min;
      foreach(s; 0 .. k + 1)
        {
          ans = max(ans, partAns(s, s + n - 1 - k));
        }
      writeln(ans);
    }
}

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 t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int-1;
		auto k = RD!int;
		auto a = RDA;

		auto l = min(m, k);
		auto len = n - m;
		foreach (i; 0..l+1)
		{
			long tmp1 = long.max;
			foreach (j; 0..m-l+1)
			{
				long tmp2;
				tmp2.chmax(a[i+j]);
				tmp2.chmax(a[i+j+len-1]);
				//debug writeln(i, ":", j, " ", tmp2);
				tmp1.chmin(tmp2);
			}
			ans[ti].chmax(tmp1);
		}
	}

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

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n, m, k;
		readf !(" %s %s %s") (n, m, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		k = min (k, m - 1);

		int res = int.min;
		foreach (i; 0..k + 1)
		{
			int cur = int.max;
			foreach (j; 0..m - k)
			{
				int temp = max (a[i + j], a[n - m + i + j]);
				cur = min (cur, temp);
			}
			res = max (res, cur);
		}
		writeln (res);
	}
}

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

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

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

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

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

        const int k = min(K, M - 1);
        const int l = M - 1 - k;

        int ans = int.min;
        foreach (x; 0 .. k + 1) {
          int mn = int.max;
          foreach (y; 0 .. l + 1) {
            chmin(mn, max(A[x + y], A[N - (k - x) - (l - y) - 1]));
          }
          chmax(ans, mn);
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n, m, k;
		readf !(" %s %s %s") (n, m, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		k = min (k, m - 1);

		int res = int.min;
		foreach (i; 0..k + 1)
		{
			int cur = int.max;
			foreach (j; 0..m - k)
			{
				writeln (i, " ", j, " ", i + j, " ",
				    n - m - i - j);
				int temp = max (a[i + j], a[n - m + i + j]);
				cur = min (cur, temp);
			}
			res = max (res, cur);
		}
		writeln (res);
	}
}


Vlad came home and found out that someone had reconfigured the old thermostat to the temperature of $$$a$$$.The thermostat can only be set to a temperature from $$$l$$$ to $$$r$$$ inclusive, the temperature cannot change by less than $$$x$$$. Formally, in one operation you can reconfigure the thermostat from temperature $$$a$$$ to temperature $$$b$$$ if $$$|a - b| \ge x$$$ and $$$l \le b \le r$$$.You are given $$$l$$$, $$$r$$$, $$$x$$$, $$$a$$$ and $$$b$$$. Find the minimum number of operations required to get temperature $$$b$$$ from temperature $$$a$$$, or say that it is impossible.

The first line of input data contains the single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each case contains three integers $$$l$$$, $$$r$$$ and $$$x$$$ ($$$-10^9 \le l \le r \le 10^9$$$, $$$1 \le x \le 10^9$$$) — range of temperature and minimum temperature change. The second line of each case contains two integers $$$a$$$ and $$$b$$$ ($$$l \le a, b \le r$$$) — the initial and final temperatures.

Output $$$t$$$ numbers, each of which is the answer to the corresponding test case. If it is impossible to achieve the temperature $$$b$$$, output -1, otherwise output the minimum number of operations.

NoteIn the first example, the thermostat is already set up correctly.In the second example, you can achieve the desired temperature as follows: $$$4 \rightarrow 10 \rightarrow 5$$$.In the third example, you can achieve the desired temperature as follows: $$$3 \rightarrow 8 \rightarrow 2 \rightarrow 7$$$.In the fourth test, it is impossible to make any operation.

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

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

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

void solve() {
    auto lrx = readarray!long;
    auto ab = readarray!long;
    if (ab[0] == ab[1]) {
            writeln(0);
            return;
    }
    else if ((lrx[0] + lrx[2] > ab[1]) && (lrx[1] - lrx[2] < ab[1])) {
        writeln(-1);
        return;
    }
    else {
        if (abs(ab[0] - ab[1]) >= lrx[2])
            writeln(1);
        else {
            if (abs(ab[0] - lrx[0]) >= lrx[2])
                if (lrx[2] + lrx[0] <= ab[1]) { //left
                    writeln(2);
                    return;
                }
            if (abs(lrx[1] - ab[0]) >= lrx[2])
                if (lrx[1] - lrx[2] >= ab[1]) { //right
                    writeln(2);
                    return;
                }
            if (abs(ab[0] - lrx[0]) >= lrx[2])
                if (lrx[2] + lrx[0] > ab[1]) { //left
                    writeln(3);
                    return;
                }
            if (abs(lrx[1] - ab[0]) >= lrx[2])
                if (lrx[1] - lrx[2] < ab[1]) { //right
                    writeln(3);
                    return;
                }
            writeln(-1);
        }
    }
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long l, r, x, a, b;
    readf!" %d %d %d "(l, r, x);
    readf!" %d %d "(a, b);
    if (a == b) {
      writeln(0);
      continue;
    }
    if (abs(a - b) >= x) {
      writeln(1);
    } else if ((abs(a - l) >= x && abs(b - l) >= x) || (abs(a - r) >= x && abs(b - r) >= x)) {
      writeln(2);
    } else if ((abs(a - l) >= x && abs(b - r) >= x) || (abs(a - r) >= x && abs(b - l) >= x)) {
      writeln(3);
    } else {
      writeln(-1);
    }
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int lo, hi, x;
		readf !(" %s %s %s") (lo, hi, x);
		int a, b;
		readf !(" %s %s") (a, b);

		auto delta = abs (a - b);
		if (a == b)
		{
			writeln (0);
		}
		else if (x <= delta)
		{
			writeln (1);
		}
		else if (x <= hi - b && x <= hi - a)
		{
			writeln (2);
		}
		else if (x <= b - lo && x <= a - lo)
		{
			writeln (2);
		}
		else if (x <= hi - b && x <= hi - lo && x <= a - lo)
		{
			writeln (3);
		}
		else if (x <= b - lo && x <= hi - lo && x <= hi - a)
		{
			writeln (3);
		}
		else
		{
			writeln (-1);
		}
	}
}

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

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

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

void solve() {
    auto lrx = readarray!long;
    auto ab = readarray!long;
    if (ab[0] == ab[1]) {
            writeln(0);
            return;
    }
    else if ((lrx[0] + lrx[2] > ab[1]) && (lrx[1] - lrx[2] < ab[1])) {
        writeln(-1);
        return;
    }
    else {
        if (abs(ab[0] - ab[1]) >= lrx[2])
            writeln(1);
        else {
            if (abs(ab[0] - lrx[0]) >= lrx[2]) {
                if (lrx[0] + lrx[2] <= ab[1]) //left
                    writeln(2);
                else
                    writeln(3);
            }
            else if (abs(lrx[1] - ab[0]) >= lrx[2]) {
                if (lrx[1] - lrx[2] >= ab[1]) //right
                    writeln(2);
                else
                    writeln(3);
            }
            else
                writeln(-1);
        }
    }
}

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


When you play the game of thrones, you win, or you die. There is no middle ground.Cersei Lannister, A Game of Thrones by George R. R. MartinThere are $$$n$$$ nobles, numbered from $$$1$$$ to $$$n$$$. Noble $$$i$$$ has a power of $$$i$$$. There are also $$$m$$$ "friendships". A friendship between nobles $$$a$$$ and $$$b$$$ is always mutual.A noble is defined to be vulnerable if both of the following conditions are satisfied:   the noble has at least one friend, and  all of that noble's friends have a higher power. You will have to process the following three types of queries.   Add a friendship between nobles $$$u$$$ and $$$v$$$.  Remove a friendship between nobles $$$u$$$ and $$$v$$$.  Calculate the answer to the following process. The process: all vulnerable nobles are simultaneously killed, and all their friendships end. Then, it is possible that new nobles become vulnerable. The process repeats itself until no nobles are vulnerable. It can be proven that the process will end in finite time. After the process is complete, you need to calculate the number of remaining nobles.Note that the results of the process are not carried over between queries, that is, every process starts with all nobles being alive!

The first line contains the integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2\cdot 10^5$$$, $$$0 \le m \le 2\cdot 10^5$$$) — the number of nobles and number of original friendships respectively. The next $$$m$$$ lines each contain the integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$), describing a friendship. No friendship is listed twice. The next line contains the integer $$$q$$$ ($$$1 \le q \le 2\cdot {10}^{5}$$$) — the number of queries.  The next $$$q$$$ lines contain the queries themselves, each query has one of the following three formats.    $$$1$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — add a friendship between $$$u$$$ and $$$v$$$. It is guaranteed that $$$u$$$ and $$$v$$$ are not friends at this moment.  $$$2$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — remove a friendship between $$$u$$$ and $$$v$$$. It is guaranteed that $$$u$$$ and $$$v$$$ are friends at this moment.  $$$3$$$ — print the answer to the process described in the statement.

For each type $$$3$$$ query print one integer to a new line. It is guaranteed that there will be at least one type $$$3$$$ query.

NoteConsider the first example. In the first type 3 query, we have the diagram below.In the first round of the process, noble $$$1$$$ is weaker than all of his friends ($$$2$$$ and $$$3$$$), and is thus killed. No other noble is vulnerable in round 1. In round 2, noble $$$3$$$ is weaker than his only friend, noble $$$4$$$, and is therefore killed. At this point, the process ends, and the answer is $$$2$$$.  In the second type 3 query, the only surviving noble is $$$4$$$.    The second example consists of only one type $$$3$$$ query. In the first round, two nobles are killed, and in the second round, one noble is killed. The final answer is $$$1$$$, since only one noble survives.

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

void main()
{
	int n = readInt!int;
	int m = readInt!int;
	alias Set = RedBlackTree!(int, (a, b) => a > b);
	auto adj = new Set[](n);
	foreach(ref adji; adj) adji = new Set();
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u].insert(v);
		adj[v].insert(u);
	}
	int noGood = 0;
	auto isGood = new bool[](n);
	foreach(i; 0 .. n)
	{
		isGood[i] = adj[i].length == 0 || adj[i].front < i;
		noGood += isGood[i];
	}
	auto nq = readInt!int;
	foreach(q; 0 .. nq)
	{
		auto op = readInt!int;
		int v, u;
		switch(op)
		{
			case 1:
				u = readInt!int - 1;
				v = readInt!int - 1;
				auto pu = isGood[u];
				auto pv = isGood[v];
				adj[u].insert(v);
				adj[v].insert(u);
				isGood[u] = adj[u].length == 0 || adj[u].front < u;
				isGood[v] = adj[v].length == 0 || adj[v].front < v;
				noGood += isGood[u] - pu;
				noGood += isGood[v] - pv;
				break;
			case 2:
				u = readInt!int - 1;
				v = readInt!int - 1;
				auto pu = isGood[u];
				auto pv = isGood[v];
				adj[u].removeKey(v);
				adj[v].removeKey(u);
				isGood[u] = adj[u].length == 0 || adj[u].front < u;
				isGood[v] = adj[v].length == 0 || adj[v].front < v;
				noGood += isGood[u] - pu;
				noGood += isGood[v] - pv;
				break;
			case 3:
				noGood.writeln;
				break;
			default: assert(0);
		}
	}
}

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

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

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

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

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

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

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

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

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

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		auto adj = new bool [int] [n];
		int total = n;

		void addEdge ()
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			if (u > v)
			{
				swap (u, v);
			}
			if (adj[u].empty)
			{
				total -= 1;
			}
			adj[u][v] = true;
		}

		void remEdge ()
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			if (u > v)
			{
				swap (u, v);
			}
			adj[u].remove (v);
			if (adj[u].empty)
			{
				total += 1;
			}
		}

		foreach (j; 0..m)
		{
			addEdge ();
		}

		int q;
		readf !(" %s") (q);
		foreach (i; 0..q)
		{
			int t;
			readf !(" %s") (t);
			if (t == 1)
			{
				addEdge ();
			}
			else if (t == 2)
			{
				remEdge ();
			}
			else if (t == 3)
			{
				writeln (total);
			}
			else
			{
				assert (false);
			}
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto m = RD!int;
	auto rbts = new RedBlackTree!(int, "a > b")[](n);
	foreach (i; 0..n)
		rbts[i] = new RedBlackTree!(int, "a > b");
	foreach (i; 0..m)
	{
		auto u = RD!int-1;
		auto v = RD!int-1;
		rbts[u].insert(v);
		rbts[v].insert(u);
	}
	int cnt;
	foreach (i; 0..n)
	{
		if (rbts[i].empty) continue;
		if (rbts[i].front > i)
			++cnt;
	}
	auto q = RD!int;
	int[] ans;
	foreach (i; 0..q)
	{
		auto num = RD!int;
		if (num == 3)
			ans ~= n - cnt;
		else
		{
			auto u = RD!int-1;
			auto v = RD!int-1;
			if (u > v)
				swap(u, v);
			if (num == 1)
			{
				bool isChange;
				if (rbts[u].empty)
					isChange = true;
				else if (rbts[u].front < u)
					isChange = true;
				if (isChange)
					++cnt;
				rbts[u].insert(v);
				rbts[v].insert(u);
			}
			else
			{
				rbts[u].removeKey(v);
				rbts[v].removeKey(u);
				if (rbts[u].front < u)
					--cnt;
			}
		}
	}

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

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

void main()
{
	int n = readInt!int;
	int m = readInt!int;
	alias Set = RedBlackTree!(int, (a, b) => a > b);
	auto adj = new Set[](n);
	foreach(ref adji; adj) adji = new Set();
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u].insert(v);
		adj[v].insert(u);
	}
	int noGood = 0;
	auto isGood = new bool[](n);
	foreach(i; 0 .. n)
	{
		isGood[i] = adj[i].front < i;
		noGood += isGood[i];
	}
	auto nq = readInt!int;
	foreach(q; 0 .. nq)
	{
		auto op = readInt!int;
		int v, u;
		switch(op)
		{
			case 1:
				u = readInt!int - 1;
				v = readInt!int - 1;
				auto pu = isGood[u];
				auto pv = isGood[v];
				adj[u].insert(v);
				adj[v].insert(u);
				isGood[u] = adj[u].front < u;
				isGood[v] = adj[v].front < v;
				noGood += isGood[u] - pu;
				noGood += isGood[v] - pv;
				break;
			case 2:
				u = readInt!int - 1;
				v = readInt!int - 1;
				auto pu = isGood[u];
				auto pv = isGood[v];
				adj[u].removeKey(v);
				adj[v].removeKey(u);
				isGood[u] = adj[u].front < u;
				isGood[v] = adj[v].front < v;
				noGood += isGood[u] - pu;
				noGood += isGood[v] - pv;
				break;
			case 3:
				noGood.writeln;
				break;
			default: assert(0);
		}
	}
}

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

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

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

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

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

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

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

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


The term of this problem is the same as the previous one, the only exception — increased restrictions.

The first line contains two positive integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.

Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.

import std.stdio;
import std.algorithm;
import std.string;
import std.range;
import std.array;
import std.conv;
import std.complex;
import std.math;
import std.ascii;
import std.bigint;
import std.container;
import std.typecons;

auto readInts() {
	return array(map!(to!int)(readln().strip().split()));
}
auto readInt() {
	return readInts()[0];
}
auto readLongs() {
	return array(map!(to!long)(readln().strip().split()));
}
auto readLong() {
	return readLongs()[0];
}

void readlnTo(T...)(ref T t) {
    auto s = readln().split();
    assert(s.length == t.length);
    foreach(ref ti; t) {
        ti = s[0].to!(typeof(ti));
        s = s[1..$];
    }
}

const real eps = 1e-10;

void main(){
    long n, k;
    readlnTo(n ,k);
    auto a = readLongs();
    auto b = readLongs();
    long l = 0, u = 10000000000;
    while(u-l > 1) {
        auto m = (u+l)/2;
        auto t = k;
        foreach(i; iota(n.to!uint)) {
            if(m * a[i] > b[i]) {
                t -= m*a[i] - b[i];
            }
            if(t < 0) {
                break;
            }
        }
        if(t < 0) {
            u = m;
        } else {
            l = m;
        }
    }
    writeln(l);
}


Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.

Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.

NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.

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

void main(){
    int n,q,x;
    readf!"%d"(n);
    readln;
    auto a=assumeSorted(readln.split.to!(int[]).sort);
    readf!"%d"(q);
    readln;
    while(q--){
        readf!"%d"(x);
        readln;
        writeln(n-a.upperBound(x).length);
    }
}


Polycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n.Polycarpus needs to come up with a parallel program model. For each memory cell number i this program must record the value n - i to this cell. In other words, for each cell you've got to find the distance to cell n.Let's denote the value that is written in the i-th cell as ai. Initially, ai = 1 (1 ≤ i < n) and an = 0. We will consider that only processor i can write values in the memory cell number i. All processors can read an information from some cell (several processors can read an information from some cell simultaneously).The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows:  Each processor independently of the other ones chooses some memory cell. Let's say that processor i has chosen a cell with number ci (1 ≤ ci ≤ n).  All processors simultaneously execute operation ai = ai + aci. Help Polycarpus come up with the parallel program model that is executed in exactly k steps. Calculate the operations that need to be executed. Note that after k steps for all i's value ai must be equal n - i.

The first line contains two space-separated integers n and k (1 ≤ n ≤ 104, 1 ≤ k ≤ 20). It is guaranteed that at the given n and k the required sequence of operations exists.

Print exactly n·k integers in k lines. In the first line print numbers c1, c2, ..., cn (1 ≤ ci ≤ n) for the first increment operation. In the second line print the numbers for the second increment operation. In the k-th line print the numbers for the k-th increment operation. As a result of the printed operations for any i value ai must equal n - i.

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		auto a = new int [n];
		a[1..$] = 1;
		foreach (i; 0..k)
		{
			int [] r;
			foreach (j; 0..n)
			{
				r ~= min (a[j], j - a[j]);
			}
			a[] += r[];
			r[] = n - r[];
			reverse (r);
			writefln ("%(%s %)", r);
		}
		foreach (j; 0..n)
		{
			enforce (a[j] == j);
		}
	}
}

module sigod.codeforces.p291D;

import std.conv;
import std.stdio;

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

	string end_line = n.to!string() ~ (n > 1 ? " " ~ n.to!string() : "");

	int[] memory = new int[n + 1];
	memory[] = 1;
	memory[n] = 0;

	foreach (ki; 0 .. k) {
		foreach (i; 1 .. n - 1) {
			if (memory[i] < n - i) {
				if (memory[i] * 2 <= n - i) {
					memory[i] *= 2;
					stdout.write(i, " ");
				}
				else {
					int index = n - (n - i - memory[i]);

					memory[i] += memory[index];
					stdout.write(index, " ");
				}
			}
			else {
				stdout.write(n, " ");
			}
		}

		stdout.writeln(end_line);
	}
}


Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $$$l$$$ centimeters after haircut, where $$$l$$$ is her favorite number. Suppose, that the Alice's head is a straight line on which $$$n$$$ hairlines grow. Let's number them from $$$1$$$ to $$$n$$$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $$$l$$$, given that all hairlines on that segment had length strictly greater than $$$l$$$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types:  $$$0$$$ — Alice asks how much time the haircut would take if she would go to the hairdresser now.  $$$1$$$ $$$p$$$ $$$d$$$ — $$$p$$$-th hairline grows by $$$d$$$ centimeters. Note, that in the request $$$0$$$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$l$$$ ($$$1 \le n, m \le 100\,000$$$, $$$1 \le l \le 10^9$$$) — the number of hairlines, the number of requests and the favorite number of Alice. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — the initial lengths of all hairlines of Alice. Each of the following $$$m$$$ lines contains a request in the format described in the statement. The request description starts with an integer $$$t_i$$$. If $$$t_i = 0$$$, then you need to find the time the haircut would take. Otherwise, $$$t_i = 1$$$ and in this moment one hairline grows. The rest of the line than contains two more integers: $$$p_i$$$ and $$$d_i$$$ ($$$1 \le p_i \le n$$$, $$$1 \le d_i \le 10^9$$$) — the number of the hairline and the length it grows by.

For each query of type $$$0$$$ print the time the haircut would take.

NoteConsider the first example:  Initially lengths of hairlines are equal to $$$1, 2, 3, 4$$$ and only $$$4$$$-th hairline is longer $$$l=3$$$, and hairdresser can cut it in $$$1$$$ second.  Then Alice's second hairline grows, the lengths of hairlines are now equal to $$$1, 5, 3, 4$$$  Now haircut takes two seonds: two swings are required: for the $$$4$$$-th hairline and for the $$$2$$$-nd.  Then Alice's first hairline grows, the lengths of hairlines are now equal to $$$4, 5, 3, 4$$$  The haircut still takes two seconds: with one swing hairdresser can cut $$$4$$$-th hairline and with one more swing cut the segment from $$$1$$$-st to $$$2$$$-nd hairline.  Then Alice's third hairline grows, the lengths of hairlines are now equal to $$$4, 5, 4, 4$$$  Now haircut takes only one second: with one swing it is possible to cut the segment from $$$1$$$-st hairline to the $$$4$$$-th.

import std.stdio;
import std.algorithm;

long[] a=new long[100002];
void main()
{
	int n,m,l,ans=0;
	scanf("%d%d%d",&n,&m,&l);
	for (int i=1;i<=n;++i)
	{
		scanf("%lld",&a[i]);
		if (a[i]>l) ans+=a[i-1]<=l;
	}
	for (int i=1;i<=m;++i)
	{
		int o;
		scanf("%d",&o);
		if (o==0) printf("%d\n",ans);
		else
		{
			int p,d;
			scanf("%d%d",&p,&d);
			if (a[p]<=l && a[p]+d>l) ans+=1-(a[p-1]>l)-(a[p+1]>l);
			a[p]+=d;
		}
	}
}

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

void main ()
{
	int n, m, l;
	while (readf (" %s %s %s", &n, &m, &l) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		a = 0 ~ a ~ 0;
		int cur = 0;
		foreach (i; 1..n + 1)
		{
			if (a[i] > l)
			{
				cur += 1;
				cur -= (a[i - 1] > l);
//				cur -= (a[i + 1] > l);
			}
		}

		foreach (j; 0..m)
		{
			int t;
			readf (" %s", &t);
			if (t == 0)
			{
				writeln (cur);
			}
			else
			{
				int p, d;
				readf (" %s %s", &p, &d);
				auto g = (a[p] <= l && a[p] + d > l);
				a[p] += d;
				if (g)
				{
					cur += 1;
					cur -= (a[p - 1] > l);
					cur -= (a[p + 1] > l);
				}
	        	}
		}
	}
}

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

void main ()
{
	int n, m, l;
	while (readf (" %s %s %s", &n, &m, &l) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		a = 0 ~ a ~ 0;
		int cur = 0;
		foreach (i; 1..n + 1)
		{
			if (a[i] > l)
			{
				cur += 1;
				cur -= (a[i - 1] > l);
				cur -= (a[i + 1] > l);
			}
		}

		foreach (j; 0..m)
		{
			int t;
			readf (" %s", &t);
			if (t == 0)
			{
				writeln (cur);
			}
			else
			{
				int p, d;
				readf (" %s %s", &p, &d);
				auto g = (a[p] <= l && a[p] + d > l);
				a[p] += d;
				if (g)
				{
					cur += 1;
					cur -= (a[p - 1] > l);
					cur -= (a[p + 1] > l);
				}
	        	}
		}
	}
}


Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.  The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square . Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads.    To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square  has ai lights.Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.

The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and . All numbers ai are positive integers, not exceeding 100.

Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.

NotePicture for the sample test. Green color denotes the additional street lights.

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

void main() {
	auto n = readln.strip.to!uint;
	auto v = readln.strip.splitter(' ').map!(a => a.to!int).array;

	uint res;

    for(int i = cast(uint)v.length - 2; i >= 0; i -= 2) {
		res += abs(v[i] - v[i + 1]);
		if(i) v[i / 2 - 1] += max(v[i], v[i + 1]);
    }

	res.write;
}

import std.algorithm, std.conv, std.range, std.stdio;
void main () {
	int n;
	readf ("%s ", &n);
	auto a = readln.split.map!(to!int).array,
		m = a.length, v = new int [m + 1];
	int res = 0;
	foreach_reverse (i; 0..m / 2) {
		int lo = v[i * 2 + 1] + a[i * 2 + 0];
		int hi = v[i * 2 + 2] + a[i * 2 + 1];
		v[i] = max (lo, hi);
		res += v[i] * 2 - lo - hi;
	}
	res.writeln;
}

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

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto a = readln ().split ().map !(to !(long)).array;
		auto m = a.length;
		auto v = new long [m + 1];
		long res = 0;
		foreach_reverse (i; 0..m / 2)
		{
			long lo = v[i * 2 + 1] + a[i * 2 + 0];
			long hi = v[i * 2 + 2] + a[i * 2 + 1];
			v[i] = max (lo, hi);
			res += v[i] * 2 - lo - hi;
		}
		writeln (res);
	}
}

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

struct S {
	uint a, b;
	S *left, right;
}

void main() {
	auto n = readln.strip.to!uint;
	auto arr = readln.strip.splitter(' ').map!(a => a.to!uint).array;

	S *create(uint idx) {
		if(idx == n) return null;

		auto s = new S;

		s.a = arr[0];
		s.b = arr[1];

		arr = arr[2..$];

		s.left = create(++idx);
		s.right = create(idx);

		return s;
	}

	auto root = create(0);

	uint calcMax(S *s, uint n = 0) {
		if(!s)
			return n;
		return max(calcMax(s.left, n + s.a), calcMax(s.right, n + s.b));
	}

	auto m = calcMax(root);
	BigInt res;

	long calcResults(S *s, long n = 0) {
		if(!s)
			return m - n;

		auto v = calcResults(s.left, n + s.a);
		auto u = calcResults(s.right, n + s.b);

		auto k = abs(v - u);
		res += k;

		return max(v, u) - k;
	}

	calcResults(root);
	res.writeln;
}

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

struct S {
	uint a, b;
	S *left, right;
}

void main() {
	auto n = readln.strip.to!uint;
	auto arr = readln.strip.splitter(' ').map!(a => a.to!uint).array;

	S *create(uint idx) {
		if(idx == n) return null;

		auto s = new S;

		s.a = arr[0];
		s.b = arr[1];

		arr = arr[2..$];

		s.left = create(++idx);
		s.right = create(idx);

		return s;
	}

	auto root = create(0);

	uint calcMax(S *s, uint n = 0) {
		if(!s)
			return n;
		return max(calcMax(s.left, n + s.a), calcMax(s.right, n + s.b));
	}

	auto m = calcMax(root);
	uint res;

	int calcResults(S *s, uint n = 0) {
		if(!s)
			return m - n;

		auto v = calcResults(s.left, n + s.a);
		auto u = calcResults(s.right, n + s.b);

		auto k = abs(v - u);
		res += k;

		return max(v, u) - k;
	}

	calcResults(root);
	res.writeln;
}