The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep". Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.In Shapur's opinion the weakness of an army is equal to the number of triplets i, j, k such that i < j < k and ai > aj > ak where ax is the power of man standing at position x. The Roman army has one special trait — powers of all the people in it are distinct.Help Shapur find out how weak the Romans are.

The first line of input contains a single number n (3 ≤ n ≤ 106) — the number of men in Roman army. Next line contains n different positive integers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 109) — powers of men in the Roman army.

A single integer number, the weakness of the Roman army.  Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).

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

class Treap(T)
{
    protected class Node
    {
        Node left;
        Node right;
        T val;
        int priority;
        int size;

        this()
        {
            left = right = null;
            size = 1;
        }

        //int opCmp(Node node)
        //{
            //return this.priority - node.priority;
        //}

        int cmpPriority(int priority)
        {
            if (this.priority == priority) return 0;
            return this.priority < priority ? -1 : 1;
        }

        int cmpVal(T val)
        {
            if (this.val == val) return 0;
            return this.val < val ? -1 : 1;
        }
    }

    protected Node root;
    protected Xorshift rnd;
    protected int _size;
    protected T minimal;
    protected T maximal;

    this()
    {
        root = null;
        rnd = Xorshift(1234567891);
        _size = 0;
        minimal = T.max;
        maximal = T.min;
    }

    protected void leftRotate(ref Node node)
    {
        auto rightNode = node.right;
        if (rightNode)
        {
            node.size = 1;
            if (node.left) node.size += node.left.size;
            if (rightNode.left) node.size += rightNode.left.size;
            rightNode.size = 1 + node.size;
            if (rightNode.right) rightNode.size += rightNode.right.size;
            node.right = rightNode.left;
            rightNode.left = node;
            node = rightNode;
        }
    }

    protected void rightRotate(ref Node node)
    {
        auto leftNode = node.left;
        if (leftNode)
        {
            node.size = 1;
            if (node.right) node.size += node.right.size;
            if (leftNode.right) node.size += leftNode.right.size;
            leftNode.size = 1 + node.size;
            if (leftNode.left) leftNode.size += leftNode.left.size;
            node.left = leftNode.right;
            leftNode.right = node;
            node = leftNode;
        }
    }

    protected Node find(T val)
    {
        return _find(root, val);
    }

    protected Node _find(Node node, T val)
    {
        if (!node) return null;
        auto ret = node.cmpVal(val);
        if (ret == 0) return node;
        if (ret == -1) return _find(node.right, val);
        return _find(node.left, val);
    }

    public void insert(T val)
    {
        auto ret = _insert(root, val);
        if (ret)
        {
            ++ _size;
        }
    }

    protected bool _insert(ref Node node, T val)
    {
        if (!node)
        {
            node = new Node();
            node.val = val;
            node.priority = this.rnd.front;
            this.rnd.seed(unpredictableSeed);
            return true;
        }
        auto ret = node.cmpVal(val);
        if (ret == 0) return false;
        bool res;
        if (ret == 1)
        {
            res = _insert(node.left, val);
            if (res)
            {
                if (node.left.priority > node.priority)
                {
                    rightRotate(node);
                }
                else
                {
                    ++ node.size;
                }
            }
        }
        else if (ret == -1)
        {
            res = _insert(node.right, val);
            if (res)
            {
                if (node.right.priority > node.priority)
                {
                    leftRotate(node);
                }
                else
                {
                    ++ node.size;
                }
            }
        }
        return res;
    }

    public void remove(T val)
    {
        auto ret = _remove(root, val);
        if (ret)
        {
            -- _size;
        }
    }

    protected bool _remove(ref Node node, T val)
    {
        if (!node) return false;
        auto ret = node.cmpVal(val);
        if (ret == -1)
        {
            return _remove(node.right, val);
        }
        else if (ret == 1)
        {
            return _remove(node.left, val);
        }
        if (!node.left && !node.right)
        {
            node = null;
            return true;
        }
        if (!node.left)
        {
            node = node.right;
            return true;
        }
        if (!node.right)
        {
            node = node.left;
            return true;
        }
        bool res;
        if (node.left.cmpPriority(node.right.priority) == 1)
        {
            rightRotate(node);
            res = _remove(node.right, val);
        }
        else
        {
            leftRotate(node);
            res = _remove(node.left, val);
        }
        if (res)
        {
            -- node.size;
        }
        return res;
    }

    protected int _countLess(Node node, T val)
    {
        if (!node) return 0;
        if (node.val == val)
        {
            if (node.left)
            {
                return node.left.size;
            }
            return 0;
        }
        if (node.val < val)
        {
            auto res = _countLess(node.right, val);
            ++ res;
            if (node.left)
            {
                res += node.left.size;
            }
            return res;
        }
        return _countLess(node.left, val);
    }

    public int countLess(T val)
    {
        return _countLess(root, val);
    }

    protected int _countGreater(Node node, T val)
    {
        if (!node) return 0;
        if (node.val == val)
        {
            if (node.right)
            {
                return node.right.size;
            }
            return 0;
        }
        if (node.val > val)
        {
            auto res = _countGreater(node.left, val);
            ++ res;
            if (node.right)
            {
                res += node.right.size;
            }
            return res;
        }
        return _countGreater(node.right, val);
    }

    public int countGreater(T val)
    {
        return _countGreater(root, val);
    }

    protected T _getMinimal(Node node)
    {
        if (!node) return minimal;
        if (!node.left) return node.val;
        return _getMinimal(node.left);
    }

    public T getMinimal()
    {
        return _getMinimal(root);
    }

    protected T _getMaximal(Node node)
    {
        if (!node) return maximal;
        if (!node.right) return node.val;
        return _getMaximal(node.right);
    }

    public T getMaximal()
    {
        return _getMaximal(root);
    }

    public void travel()
    {
        _travel(root);
    }

    protected void _travel(Node node)
    {
        if (!node) return;
        _travel(node.left);
        writeln(node.val);
        writeln(node.priority);
        writeln(node.size);
        _travel(node.right);
    }

    public void clear()
    {
        while (root)
        {
            remove(root.val);
        }
    }

    @property public int size()
    {
        return _size;
    }
}

void solve(int[] a)
{
    auto n = cast(int)a.length;
    auto treap = new Treap!int();
    auto lc = new int[n];
    foreach (i; 0 .. n)
    {
        lc[i] = treap.countGreater(a[i]);
        treap.insert(a[i]);
    }
    treap = new Treap!int();
    //treap.clear();
    auto rc = new int[n];
    for (int i = n - 1; i >= 0; -- i)
    {
        rc[i] = treap.countLess(a[i]);
        treap.insert(a[i]);
    }
    long ans = 0;
    foreach (i; 0 .. n)
    {
        ans += cast(long)lc[i] * rc[i];
    }
    writeln(ans);
}

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

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

class Treap(T)
{
    protected class Node
    {
        Node left;
        Node right;
        T val;
        int priority;
        int size;

        this()
        {
            left = right = null;
            size = 1;
        }

        //int opCmp(Node node)
        //{
            //return this.priority - node.priority;
        //}

        int cmpPriority(int priority)
        {
            if (this.priority == priority) return 0;
            return this.priority < priority ? -1 : 1;
        }

        int cmpVal(T val)
        {
            if (this.val == val) return 0;
            return this.val < val ? -1 : 1;
        }
    }

    protected Node root;
    protected Xorshift rnd;
    protected int _size;
    protected T minimal;
    protected T maximal;

    this()
    {
        root = null;
        rnd = Xorshift(1234567891);
        _size = 0;
        minimal = T.max;
        maximal = T.min;
    }

    protected void leftRotate(ref Node node)
    {
        auto rightNode = node.right;
        if (rightNode)
        {
            node.size = 1;
            if (node.left) node.size += node.left.size;
            if (rightNode.left) node.size += rightNode.left.size;
            rightNode.size = 1 + node.size;
            if (rightNode.right) rightNode.size += rightNode.right.size;
            node.right = rightNode.left;
            rightNode.left = node;
            node = rightNode;
        }
    }

    protected void rightRotate(ref Node node)
    {
        auto leftNode = node.left;
        if (leftNode)
        {
            node.size = 1;
            if (node.right) node.size += node.right.size;
            if (leftNode.right) node.size += leftNode.right.size;
            leftNode.size = 1 + node.size;
            if (leftNode.left) leftNode.size += leftNode.left.size;
            node.left = leftNode.right;
            leftNode.right = node;
            node = leftNode;
        }
    }

    protected Node find(T val)
    {
        return _find(root, val);
    }

    protected Node _find(Node node, T val)
    {
        if (!node) return null;
        auto ret = node.cmpVal(val);
        if (ret == 0) return node;
        if (ret == -1) return _find(node.right, val);
        return _find(node.left, val);
    }

    public void insert(T val)
    {
        auto ret = _insert(root, val);
        if (ret)
        {
            ++ _size;
        }
    }

    protected bool _insert(ref Node node, T val)
    {
        if (!node)
        {
            node = new Node();
            node.val = val;
            node.priority = this.rnd.front;
            this.rnd.seed(unpredictableSeed);
            return true;
        }
        auto ret = node.cmpVal(val);
        if (ret == 0) return false;
        bool res;
        if (ret == 1)
        {
            res = _insert(node.left, val);
            if (res)
            {
                if (node.left.priority > node.priority)
                {
                    rightRotate(node);
                }
                else
                {
                    ++ node.size;
                }
            }
        }
        else if (ret == -1)
        {
            res = _insert(node.right, val);
            if (res)
            {
                if (node.right.priority > node.priority)
                {
                    leftRotate(node);
                }
                else
                {
                    ++ node.size;
                }
            }
        }
        return res;
    }

    public void remove(T val)
    {
        auto ret = _remove(root, val);
        if (ret)
        {
            -- _size;
        }
    }

    protected bool _remove(ref Node node, T val)
    {
        if (!node) return false;
        auto ret = node.cmpVal(val);
        if (ret == -1)
        {
            return _remove(node.right, val);
        }
        else if (ret == 1)
        {
            return _remove(node.left, val);
        }
        if (!node.left && !node.right)
        {
            node = null;
            return true;
        }
        if (!node.left)
        {
            node = node.right;
            return true;
        }
        if (!node.right)
        {
            node = node.left;
            return true;
        }
        bool res;
        if (node.left.cmpPriority(node.right.priority) == 1)
        {
            rightRotate(node);
            res = _remove(node.right, val);
        }
        else
        {
            leftRotate(node);
            res = _remove(node.left, val);
        }
        if (res)
        {
            -- node.size;
        }
        return res;
    }

    protected int _countLess(Node node, T val)
    {
        if (!node) return 0;
        if (node.val == val)
        {
            if (node.left)
            {
                return node.left.size;
            }
            return 0;
        }
        if (node.val < val)
        {
            auto res = _countLess(node.right, val);
            ++ res;
            if (node.left)
            {
                res += node.left.size;
            }
            return res;
        }
        return _countLess(node.left, val);
    }

    public int countLess(T val)
    {
        return _countLess(root, val);
    }

    protected int _countGreater(Node node, T val)
    {
        if (!node) return 0;
        if (node.val == val)
        {
            if (node.right)
            {
                return node.right.size;
            }
            return 0;
        }
        if (node.val > val)
        {
            auto res = _countGreater(node.left, val);
            ++ res;
            if (node.right)
            {
                res += node.right.size;
            }
            return res;
        }
        return _countGreater(node.right, val);
    }

    public int countGreater(T val)
    {
        return _countGreater(root, val);
    }

    protected T _getMinimal(Node node)
    {
        if (!node) return minimal;
        if (!node.left) return node.val;
        return _getMinimal(node.left);
    }

    public T getMinimal()
    {
        return _getMinimal(root);
    }

    protected T _getMaximal(Node node)
    {
        if (!node) return maximal;
        if (!node.right) return node.val;
        return _getMaximal(node.right);
    }

    public T getMaximal()
    {
        return _getMaximal(root);
    }

    public void travel()
    {
        _travel(root);
    }

    protected void _travel(Node node)
    {
        if (!node) return;
        _travel(node.left);
        writeln(node.val);
        writeln(node.priority);
        writeln(node.size);
        _travel(node.right);
    }

    public void clear()
    {
        while (root)
        {
            remove(root.val);
        }
    }

    @property public int size()
    {
        return _size;
    }
}

void solve(int[] a)
{
    auto n = cast(int)a.length;
    auto treap = new Treap!int();
    auto lc = new int[n];
    foreach (i; 0 .. n)
    {
        lc[i] = treap.countGreater(a[i]);
        treap.insert(a[i]);
    }
    treap.clear();
    auto rc = new int[n];
    for (int i = n - 1; i >= 0; -- i)
    {
        rc[i] = treap.countLess(a[i]);
        treap.insert(a[i]);
    }
    long ans = 0;
    foreach (i; 0 .. n)
    {
        ans += cast(long)lc[i] * rc[i];
    }
    writeln(ans);
}

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

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

void main(string[] args)
{
  auto n = next!int;
  auto a = next!long(n);
  auto lsThan = St(new long[](n));
  auto rightLessThan = new long[](n);
  auto si = iota(0, n).array.sort!((i, j) => a[i] < a[j]);
  debug writeln(si);
  foreach(i; si)
    {
      lsThan.set(i, 1);
      debug
	{
	  foreach(k; 0 .. n)
	    write(lsThan.getSum(k, k), " ");
	  writeln;
	}
      if (i < n - 1) rightLessThan[i] = lsThan.getSum(i + 1, n - 1);
    }
  debug writeln(rightLessThan);
  auto pairs = St(new long[](n));
  auto sol = new long[](n);
  foreach(i; si)
    {
      pairs.set(i, rightLessThan[i]);
      if (i < n - 1) sol[i] = pairs.getSum(i + 1, n - 1);
    }
  sol.sum.writeln;
}

struct St
{
  class Node
  {
    this(int s, int e)
    {
      this.s = s;
      this.e = e;
      this.sum = 0;
    }
    int s, e;
    int len() {return e - s + 1;}
    long sum;
    long query(int i, int j)
    {
      debug writeln("querying ", s, " ", e, " for ", i, " ", j);
      if (i <= s && e <= j) return sum;
      if (s > j || i > e) return 0;
      return leftChild.query(i, j) + rightChild.query(i, j);
    }
    void set(int i, long val)
    {
      if (s <= i && i <= e)
	{
	  if (len == 1) { debug writeln("setting "); sum = val; return; }
	  leftChild.set(i, val);
	  rightChild.set(i, val);
	  sum = leftChild.sum + rightChild.sum;
	}
    }
    Node leftChild, rightChild;
  }
  Node _root;
  this(long[] arr)
  {
    Node construct(int s, int e)
    {
      auto node = new Node(s, e);
      auto len = e - s + 1;
      if (len == 1)
	{
	  node.sum = arr[s];
	  return node;
	}
      int llen = len / 2;
      node.leftChild = construct(s, s + llen - 1);
      node.rightChild = construct(s + llen, e);
      assert(node.leftChild.len == llen);
      assert(node.rightChild.len == len - llen);
      node.sum = node.leftChild.sum + node.rightChild.sum;
      return node;
    }
    _root = construct(0, cast(int)arr.length - 1);
  }
  long getSum(int i, int j)
  {
    return _root.query(i, j);
  }
  void set(int i, long val)
  {
    return _root.set(i, val);
  }
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}


You are given two integers $$$a$$$ and $$$b$$$.In one move, you can choose some integer $$$k$$$ from $$$1$$$ to $$$10$$$ and add it to $$$a$$$ or subtract it from $$$a$$$. In other words, you choose an integer $$$k \in [1; 10]$$$ and perform $$$a := a + k$$$ or $$$a := a - k$$$. You may use different values of $$$k$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case, print the answer: the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.

NoteIn the first test case of the example, you don't need to do anything.In the second test case of the example, the following sequence of moves can be applied: $$$13 \rightarrow 23 \rightarrow 32 \rightarrow 42$$$ (add $$$10$$$, add $$$9$$$, add $$$10$$$).In the third test case of the example, the following sequence of moves can be applied: $$$18 \rightarrow 10 \rightarrow 4$$$ (subtract $$$8$$$, subtract $$$6$$$).

// Vicfred
// https://codeforces.com/contest/1409/problem/A
//
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.stdio;
import std.string;

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

    while(t--) {
        long a, b;
        readf("%s %s", &a, &b);
        readln;

        real diff = (a - b)/10.0;
        long moves = cast(long)ceil(abs(diff));
        moves.writeln;
    }
}

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

long pmod(long a, long m)
{
  return (a%m +m)%m;
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);

  auto t = next!int;
  foreach(tc; 0 .. t)
    {
      auto a = next!long;
      auto b = next!long;
      auto diff = abs(a - b);
      long ops = diff / 10;
      if (diff % 10 != 0)
        ops++;
      writeln(ops);
    }
}

// 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.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;
		auto d = abs(a - b);
		ans[ti] = (d+9) / 10;
	}

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


You are given two integers $$$n$$$ and $$$k$$$. You are asked to choose maximum number of distinct integers from $$$1$$$ to $$$n$$$ so that there is no subset of chosen numbers with sum equal to $$$k$$$.A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.

The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 100$$$). Each of the next $$$T$$$ lines contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 1000$$$) — the description of test cases.

For each test case output two lines. In the first line output a single integer $$$m$$$ — the number of chosen integers. In the second line output $$$m$$$ distinct integers from $$$1$$$ to $$$n$$$ — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		auto a = iota (1, n + 1).array;
		a = a.filter !(x => x * 2 >= k && x != k).array;
		writeln (a.length);
		writefln !("%(%s %)") (a);
	}
}

import std.stdio;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n, k;
        readf!"%d %d\n"(n, k);
        writeln(n - k + k / 2);
        foreach (i; k + 1 .. n + 1)
            write(i, ' ');
        foreach (i; (k + 1) / 2 .. k)
            write(i, ' ');
        writeln;
    }
}

module main;
import std.stdio, std.conv, std.string, std.array;

T read(T)()
{
    static string[] tokens;
    while (!tokens.length)
        tokens = stdin.readln.split;
    auto result = tokens[0].to!T;
    tokens = tokens[1 .. $];
    return result;
}

void main()
{
    auto T = read!int;
    foreach (case_index; 0 .. T)
    {
        auto n = read!int, k = read!int;
        auto result_builder = appender!(int[]);
        foreach (i; 1 .. n + 1)
        {
            if (i >= (k + 1) / 2 && i != k)
                result_builder ~= i;
        }
        auto result = result_builder[];
        writeln(result.length);
        writefln!"%(%s %)"(result);
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach_reverse (i; 1..n+1)
		{
			if (i == k || i*2 < k) continue;
			else
				ans[ti] ~= i;
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		int m = (k + 1) / 2 + 1;
		writeln (n - m + 1);
		writefln !("%(%s %)") (iota (m, n + 1));
	}
}

import std.stdio;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n, k;
        readf!"%d %d\n"(n, k);
        foreach (i; k + 1 .. n + 1)
            write(i, ' ');
        foreach (i; (k + 1) / 2 .. k)
            write(i, ' ');
        writeln;
    }
}


You are given two lists of segments $$$[al_1, ar_1], [al_2, ar_2], \dots, [al_n, ar_n]$$$ and $$$[bl_1, br_1], [bl_2, br_2], \dots, [bl_n, br_n]$$$.Initially, all segments $$$[al_i, ar_i]$$$ are equal to $$$[l_1, r_1]$$$ and all segments $$$[bl_i, br_i]$$$ are equal to $$$[l_2, r_2]$$$.In one step, you can choose one segment (either from the first or from the second list) and extend it by $$$1$$$. In other words, suppose you've chosen segment $$$[x, y]$$$ then you can transform it either into $$$[x - 1, y]$$$ or into $$$[x, y + 1]$$$.Let's define a total intersection $$$I$$$ as the sum of lengths of intersections of the corresponding pairs of segments, i.e. $$$\sum\limits_{i=1}^{n}{\text{intersection_length}([al_i, ar_i], [bl_i, br_i])}$$$. Empty intersection has length $$$0$$$ and length of a segment $$$[x, y]$$$ is equal to $$$y - x$$$.What is the minimum number of steps you need to make $$$I$$$ greater or equal to $$$k$$$?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^9$$$) — the length of lists and the minimum required total intersection. The second line of each test case contains two integers $$$l_1$$$ and $$$r_1$$$ ($$$1 \le l_1 \le r_1 \le 10^9$$$) — the segment all $$$[al_i, ar_i]$$$ are equal to initially. The third line of each test case contains two integers $$$l_2$$$ and $$$r_2$$$ ($$$1 \le l_2 \le r_2 \le 10^9$$$) — the segment all $$$[bl_i, br_i]$$$ are equal to initially. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ integers — one per test case. For each test case, print the minimum number of step you need to make $$$I$$$ greater or equal to $$$k$$$.

NoteIn the first test case, we can achieve total intersection $$$5$$$, for example, using next strategy:   make $$$[al_1, ar_1]$$$ from $$$[1, 2]$$$ to $$$[1, 4]$$$ in $$$2$$$ steps;  make $$$[al_2, ar_2]$$$ from $$$[1, 2]$$$ to $$$[1, 3]$$$ in $$$1$$$ step;  make $$$[bl_1, br_1]$$$ from $$$[3, 4]$$$ to $$$[1, 4]$$$ in $$$2$$$ steps;  make $$$[bl_2, br_2]$$$ from $$$[3, 4]$$$ to $$$[1, 4]$$$ in $$$2$$$ steps.  In result, $$$I = \text{intersection_length}([al_1, ar_1], [bl_1, br_1]) + \text{intersection_length}([al_2, ar_2], [bl_2, br_2]) + \\ + \text{intersection_length}([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5$$$In the second test case, we can make $$$[al_1, ar_1] = [0, 1000000000]$$$ in $$$1000000000$$$ steps and $$$[bl_1, br_1] = [0, 1000000000]$$$ in $$$1000000000$$$ steps.In the third test case, the total intersection $$$I$$$ is already equal to $$$10 > 3$$$, so we don't need to do any steps.

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 n;
		long k;
		readf !(" %s %s") (n, k);
		alias Segment = Tuple !(long, q{lo}, long, q{hi});
		Segment [2] s;
		foreach (i; 0..2)
		{
			readf !(" %s %s") (s[i].lo, s[i].hi);
		}
		auto hi = min (s[0].hi, s[1].hi);
		auto lo = max (s[0].lo, s[1].lo);
		auto common = max (0, hi - lo);
		k = max (0L, k - n * 1L * common);
		auto gap = max (0, s[0].lo - s[1].hi, s[1].lo - s[0].hi);
		auto d1 = abs (s[1].hi - s[0].hi);
		auto d2 = abs (s[1].lo - s[0].lo);
		long len = d1 + d2 - gap;
		debug {writeln ("gap = ", gap, ", len = ", len);}

		long res = 0;
		foreach (i; 0..n)
		{
			if (k <= 0)
			{
				break;
			}
			/// заплатить  gap + cur
			/// получить       + cur      к ответу
			///   0 <= cur <= len
			auto cur = min (k, len);
			auto pay = gap + cur;
			if (i > 0 && pay > cur * 2)
			{
				res += k * 2;
				k = 0;
			}
			else
			{
				res += pay;
				k -= cur;
			}
		}
		writeln (res + k * 2);
	}
}

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 n;
		long k;
		readf !(" %s %s") (n, k);
		alias Segment = Tuple !(long, q{lo}, long, q{hi});
		Segment [2] s;
		foreach (i; 0..2)
		{
			readf !(" %s %s") (s[i].lo, s[i].hi);
		}
		auto hi = min (s[0].hi, s[1].hi);
		auto lo = max (s[0].lo, s[1].lo);
		auto common = max (0, hi - lo);
		k = max (0L, k - n * 1L * common);
		auto gap = max (0, s[0].lo - s[1].hi, s[1].lo - s[0].hi);
		auto d1 = abs (s[1].hi - s[0].hi);
		auto d2 = abs (s[1].lo - s[0].lo);
		long len = d1 + d2 - gap;
		debug {writeln ("gap = ", gap, ", len = ", len);}

		long res = 0;
		foreach (i; 0..n)
		{
			if (k <= 0)
			{
				break;
			}
			auto cur = min (k, len);
			auto pay = gap + cur;
			if (i > 0 && pay > k * 2)
			{
				res += k * 2;
				k = 0;
			}
			else
			{
				res += pay;
				k -= cur;
			}
		}
		writeln (res + k * 2);
	}
}


Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) the number of nodes in the tree. Each of the next $$$n - 1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the edges of the tree. It is guaranteed that the given edges form a tree.

If there are no decompositions, print the only line containing "No". Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition $$$m$$$.  Each of the next $$$m$$$ lines should contain two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$) denoting that one of the paths in the decomposition is the simple path between nodes $$$u_i$$$ and $$$v_i$$$.  Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order. If there are multiple decompositions, print any.

NoteThe tree from the first example is shown on the picture below:  The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.The tree from the second example is shown on the picture below:  We can show that there are no valid decompositions of this tree.The tree from the third example is shown on the picture below:  The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.

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

void main() {
    auto N = readln.chomp.to!int;
    auto G = new int[][](N);
    foreach (_; 0..N-1) {
        auto s = readln.split.map!(to!int);
        G[s[0]-1] ~= s[1]-1;
        G[s[1]-1] ~= s[0]-1;
    }

    if (G.map!(g => g.length >= 3).sum >= 2) {
        writeln("No");
        return;
    }

    writeln("Yes");

    int[] root1;
    int root3 = -1;
    foreach (i; 0..N) if (G[i].length == 1) root1 ~= i;
    foreach (i; 0..N) if (G[i].length >= 3) root3 = i;

    if (root3 == -1) {
        writeln(1);
        writeln(root1[0]+1, " ", root1[1]+1);
    } else {
        writeln(root1.length);
        foreach (r; root1)
            writeln(r+1, " ", root3+1);
    }
}

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

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

int main() {
    Scanner sc = new Scanner(stdin);
    int n;
    sc.read(n);
    int[][] g = new int[][n];
    foreach (i; 0..n-1) {
        int a, b;
        sc.read(a, b); a--; b--;
        g[a] ~= b; g[b] ~= a;
    }
    if (g.count!"a.length>=3" >= 2) {
        writeln("No");
        return 0;
    }
    int[] leafs;
    void dfs(int p, int b) {
        bool haveCh = false;
        foreach (d; g[p]) {
            if (d == b) continue;
            haveCh = true;
            dfs(d, p);
        }
        if (!haveCh) leafs ~= p;
    }
    foreach (i; 0..n) {
        if (i == n-1 || g[i].length >= 3) {
            dfs(i, -1);
            writeln("Yes");
            writeln(leafs.length);
            foreach (d; leafs) {
                writeln(i+1, " ", d+1);
            }
            break;
        }
    }
    return 0;
}
/* IMPORT /mnt/c/Users/yosupo/Programs/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

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

    private T* _data;
    private uint len, cap;

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

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

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

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

    void clear() {
        len = 0;
    }

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

/* IMPORT /mnt/c/Users/yosupo/Programs/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

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

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

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
    void read(Args...)(auto ref Args args) {
        import std.exception;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }
    bool hasNext() {
        return succ();
    }
}

/* IMPORT /mnt/c/Users/yosupo/Programs/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

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

}

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

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

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

    auto g = new int [][] ( n+1 );
    foreach ( _; 0..n-1 ) {
        auto t = readln.splitter.map!( to!int ).array;
        (2).iota.each!( i => g[ t[ i ] ] ~= t[ 1-i ] );
    }

    debug { writeln( g ); }

    bool ok = g.count!(adj => adj.length > 2) <= 1;

    if ( !ok ) {
        writeln( "No" );
        return;
    }

    int v = cast(int) g.maxIndex!( q{ a.length < b.length });

    int[] ans;
    foreach ( u; g[v] ) {
        int lst = v;
        int cur = u;
        while ( true ) {
            if ( g[ cur ].length == 1 ) break;

            auto nxt = g[ cur ][ 0 ] != lst ? g[ cur ][ 0 ] : g[ cur ][ 1 ];
            lst = cur;
            cur = nxt;
        }
        ans ~= cur;
    }

    writeln( "Yes" );
    writeln( ans.length );
    ans.each!( lst => writeln( v, ' ', lst ) );
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto d = new int [n];
		auto a = new int [] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
			d[u] += 1;
			d[v] += 1;
		}
		auto p = n.iota.array;
		makeIndex (d, p);
		if (d[p[$ - 2]] > 2)
		{
			writeln ("No");
			continue;
		}
		writeln ("Yes");
		auto r = p[$ - 1];
		writeln (n.iota.count !(x => x != r && d[x] == 1));
		foreach (v; 0..n)
		{
			if (v != r && d[v] == 1)
			{
				writeln (v + 1, " ", r + 1);
			}
		}
	}
}


Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations: Move from the list of letters to the content of any single letter. Return to the list of letters from single letter viewing mode. In single letter viewing mode, move to the next or to the previous letter in the list. You cannot move from the first letter to the previous one or from the last letter to the next one.The program cannot delete the letters from the list or rearrange them.Alexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. What minimum number of operations does Alexey need to perform to read all unread letters?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of letters in the mailbox. The second line contains n space-separated integers (zeros and ones) — the state of the letter list. The i-th number equals either 1, if the i-th number is unread, or 0, if the i-th letter is read.

Print a single number — the minimum number of operations needed to make all the letters read.

NoteIn the first sample Alexey needs three operations to cope with the task: open the second letter, move to the third one, move to the fourth one.In the second sample the action plan: open the first letter, move to the second letter, return to the list, open the fifth letter.In the third sample all letters are already read.

import std.stdio;

void main() {

	int n, ni, num, flag;

	scanf("%d", &n);

	foreach (i; 0 .. n) {
		scanf("%d", &ni);
		if (!ni && flag) {
			flag = 0;
			num++;
		}
		else
			if (ni == 1) {
				num++;
				flag = 1;
			}
	}

	if (num > 0 && !ni)
		num--;

	printf("%d\n", num);
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;
import std.conv;
import std.functional;
import std.traits;
import std.string;
import std.container;

unittest{
  assert(solve([1,1,0,0,1]) == 4, "Teste 1");
  assert(solve([0,1,0,1,0]) == 3, "Teste 2");
  assert(solve([0,0]) == 0, "Teste 3");
  assert(solve([0,0,1,0,0,0,0,0]) == 1, "Teste 4");
  assert(solve([0,0,0,0,0,0,0,1]) == 1, "Teste 5");
  assert(solve([1,0,0,0,0,0,0,0]) == 1, "Teste 6");
  assert(solve([1,0,1,0,0,1,1,0]) == 6, "Teste 7");
}

long solve(long[] ls){
  long c = 0;
  int state = 0;
  foreach(i,l;ls){
    if(state == 0 && l == 1){
      c++;
      state = 1;
      //writefln("%s open",i);
    } else if(state == 1){
      if(l == 0){
        if(ls[i-1] == 0){
          state = 0;
          //writefln("%s back",i-1);
        } else {
          c++;
          //writefln("%s next",i);
        }
      } else {
        //writefln("%s next",i);
        c++;
      }
    }
  }
  if(ls[$-1] == 0 && c != 0){
    c--;
  }
  //writeln(c);
  return c;
}

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

  long[] l = new long[n];
  for(size_t i = 0; i < n; i++){
    readf("%s ",l.ptr+i);
  }
  writeln(solve(l));
}

import std.stdio;
import std.string: chomp, split;
import std.conv: to;

void main()
{
	int n; readf("%s\n", &n);
	auto ar = readln.chomp.split.to!(int[]);
	//writeln(ar);

	int state = -1, sol = 0;

	foreach (a; ar) {
		//writefln("%d %d", a, state);
		if (a == 0) {
			if (state != -1) {
				state = 1;
			}
			continue;
		}
		if (state == -1) {
			state = 0;
		}
		sol++;
		if (state == 1) {
			sol++;
			state = 0;
		}
	}

	writeln(sol);
}

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

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

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

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

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

int N;
int[] A;

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

		int ans;
		for (int i = 0, j; i < N; i = j) {
			for (; j < N && A[i] == A[j]; ++j) {}
			if (A[i] == 1) {
				ans += (j - i + 1);
			}
		}
		if (ans > 0) {
			--ans;
		}
		writeln(ans);
	}
	} catch (EOFException) {}
}


Numbers $$$1, 2, 3, \dots n$$$ (each integer from $$$1$$$ to $$$n$$$ once) are written on a board. In one operation you can erase any two numbers $$$a$$$ and $$$b$$$ from the board and write one integer $$$\frac{a + b}{2}$$$ rounded up instead.You should perform the given operation $$$n - 1$$$ times and make the resulting number that will be left on the board as small as possible. For example, if $$$n = 4$$$, the following course of action is optimal:  choose $$$a = 4$$$ and $$$b = 2$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3, 3]$$$;  choose $$$a = 3$$$ and $$$b = 3$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3]$$$;  choose $$$a = 1$$$ and $$$b = 3$$$, so the new number is $$$2$$$, and the whiteboard contains $$$[2]$$$. It's easy to see that after $$$n - 1$$$ operations, there will be left only one number. Your goal is to minimize it.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of integers written on the board initially. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, in the first line, print the minimum possible number left on the board after $$$n - 1$$$ operations. Each of the next $$$n - 1$$$ lines should contain two integers — numbers $$$a$$$ and $$$b$$$ chosen and erased in each operation.

// Vicfred
// https://codeforces.com/contest/1430/problem/C
// math, greedy
import std.stdio;

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

    int n;
    while(t--) {
        readf("%s\n", &n);

        "2".writeln;

        int x = n - 2;
        int y = n;
        writefln("%s %s", n - 1, n);

        for(int i = 0; i < n - 2; ++i) {
            writefln("%s %s", x, y);
            x -= 1;
            y -= 1;
        }
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		BinaryHeap!(Array!int, "a < b") heap;
		foreach (i; 1..n+1)
		{
			heap.insert(i);
		}

		while (heap.length > 1)
		{
			auto x = heap.front; heap.removeFront;
			auto y = heap.front; heap.removeFront;
			ans[ti] ~= [x, y];
			heap.insert((x+y+1)/2);
		}
		ans2[ti] = heap.front;
	}

	foreach (ti; 0..t)
	{
		writeln(ans2[ti]);
		foreach (e; ans[ti])
		{
			writeln(e[0], " ", e[1]);
		}
	}
	stdout.flush;
	debug readln;
}


A penguin Rocher has $$$n$$$ sticks. He has exactly one stick with length $$$i$$$ for all $$$1 \le i \le n$$$.He can connect some sticks. If he connects two sticks that have lengths $$$a$$$ and $$$b$$$, he gets one stick with length $$$a + b$$$. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?

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. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).

For each test case, print a single integer  — the answer to the problem.

NoteIn the third case, he can connect two sticks with lengths $$$1$$$ and $$$2$$$ and he will get one stick with length $$$3$$$. So, he will have two sticks with lengths $$$3$$$.In the fourth case, he can connect two sticks with lengths $$$1$$$ and $$$3$$$ and he will get one stick with length $$$4$$$. After that, he will have three sticks with lengths $$$\{2, 4, 4\}$$$, so two sticks have the same length, and one stick has the other length.

import std.algorithm, std.conv, std.stdio, std.string;
void main () {
	readln;
	stdin.byLine.each !(x => writeln ((x.strip.to!int + 1) / 2));
}

import std.container: DList;
import std.algorithm: all, map, count, filter;
import std.range: iota;
import std.array: array;
import std.stdio;
import std.utf;

DList!string _words;
void read(T)(out T t)
{
  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;
  t = to!T(word);
}

void main()
{
  int t;
  read(t);
  while(t--)
    {
      long n;
      read(n);
      writeln((n + n % 2)/2);
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD;
		ans[ti] = (n-1) / 2 + 1;
	}

	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}


You went to the store, selling $$$n$$$ types of chocolates. There are $$$a_i$$$ chocolates of type $$$i$$$ in stock.You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy $$$x_i$$$ chocolates of type $$$i$$$ (clearly, $$$0 \le x_i \le a_i$$$), then for all $$$1 \le j < i$$$ at least one of the following must hold:  $$$x_j = 0$$$ (you bought zero chocolates of type $$$j$$$) $$$x_j < x_i$$$ (you bought less chocolates of type $$$j$$$ than of type $$$i$$$) For example, the array $$$x = [0, 0, 1, 2, 10]$$$ satisfies the requirement above (assuming that all $$$a_i \ge x_i$$$), while arrays $$$x = [0, 1, 0]$$$, $$$x = [5, 5]$$$ and $$$x = [3, 2]$$$ don't.Calculate the maximum number of chocolates you can buy.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$), denoting the number of types of chocolate. The next line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$), denoting the number of chocolates of each type.

Print the maximum number of chocolates you can buy.

NoteIn the first example, it is optimal to buy: $$$0 + 0 + 1 + 3 + 6$$$ chocolates.In the second example, it is optimal to buy: $$$1 + 2 + 3 + 4 + 10$$$ chocolates.In the third example, it is optimal to buy: $$$0 + 0 + 0 + 1$$$ chocolates.

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;

    long ans = 0;
    long last = 1L << 59;

    foreach_reverse (i; 0..N) {
        long tmp = max(0L, min(last - 1, A[i]));
        ans += tmp;
        last = tmp;
    }

    ans.writeln;
}


You are given an array $$$a$$$ consisting of $$$n$$$ non-negative integers. You have to choose a non-negative integer $$$x$$$ and form a new array $$$b$$$ of size $$$n$$$ according to the following rule: for all $$$i$$$ from $$$1$$$ to $$$n$$$, $$$b_i = a_i \oplus x$$$ ($$$\oplus$$$ denotes the operation bitwise XOR).An inversion in the $$$b$$$ array is a pair of integers $$$i$$$ and $$$j$$$ such that $$$1 \le i < j \le n$$$ and $$$b_i > b_j$$$.You should choose $$$x$$$ in such a way that the number of inversions in $$$b$$$ is minimized. If there are several options for $$$x$$$ — output the smallest one.

First line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements in $$$a$$$. Second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Output two integers: the minimum possible number of inversions in $$$b$$$, and the minimum possible value of $$$x$$$, which achieves those number of inversions.

NoteIn the first sample it is optimal to leave the array as it is by choosing $$$x = 0$$$.In the second sample the selection of $$$x = 14$$$ results in $$$b$$$: $$$[4, 9, 7, 4, 9, 11, 11, 13, 11]$$$. It has $$$4$$$ inversions:  $$$i = 2$$$, $$$j = 3$$$;  $$$i = 2$$$, $$$j = 4$$$;  $$$i = 3$$$, $$$j = 4$$$;  $$$i = 8$$$, $$$j = 9$$$. In the third sample the selection of $$$x = 8$$$ results in $$$b$$$: $$$[0, 2, 11]$$$. It has no inversions.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
	        readln;
	        auto a = readln.splitter.map !(to !(int)).array;
		auto b = new int [n];
	        auto c = a.dup;

		auto countInv (int lo, int hi)
		{
			if (hi - lo < 2)
			{
				return 0L;
			}
			auto me = (lo + hi) >> 1;
			auto res = countInv (lo, me) + countInv (me, hi);
			b[lo..hi] = c[lo..hi];
			for (int i = lo, j = me, k = lo; i < me || j < hi; )
			{
				if (i < me && (j >= hi || b[i] <= b[j]))
				{
					c[k++] = b[i++];
				}
				else
				{
					res += me - i;
					c[k++] = b[j++];
				}
			}
			return res;
		}

		c[] = a[];
		auto cur = countInv (0, n);
		int res = 0;
		foreach_reverse (d; 0..30)
		{
			a[] ^= 1 << d;
			c[] = a[];
			auto temp = countInv (0, n);
			if (cur > temp)
			{
				cur = temp;
				res ^= 1 << d;
			}
			else
			{
				a[] ^= 1 << d;
			}
		}

		writeln (cur, " ", res);
	}
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
	        readln;
	        auto a = readln.splitter.map !(to !(int)).array;
		auto b = new int [n];
	        auto c = a.dup;

		auto countInv (int lo, int hi)
		{
			if (hi - lo < 2)
			{
				return 0;
			}
			auto me = (lo + hi) >> 1;
			auto res = countInv (lo, me) + countInv (me, hi);
			b[lo..hi] = c[lo..hi];
			for (int i = lo, j = me, k = lo; i < me || j < hi; )
			{
				if (i < me && (j >= hi || b[i] <= b[j]))
				{
					c[k++] = b[i++];
				}
				else
				{
					res += me - i;
					c[k++] = b[j++];
				}
			}
			return res;
		}

		c[] = a[];
		auto cur = countInv (0, n);
		int res = 0;
		foreach_reverse (d; 0..30)
		{
			a[] ^= 1 << d;
			c[] = a[];
			auto temp = countInv (0, n);
			if (cur > temp)
			{
				cur = temp;
				res ^= 1 << d;
			}
			else
			{
				a[] ^= 1 << d;
			}
		}

		writeln (cur, " ", res);
	}
}


A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3.m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj.A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served.You are to compute the prices each buyer will pay for t-shirts.

The first line contains single integer n (1 ≤ n ≤ 200 000) — the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≤ pi ≤ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≤ m ≤ 200 000) — the number of buyers.  The following line contains sequence c1, c2, ..., cm (1 ≤ cj ≤ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served.

Print to the first line m integers — the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1.

import core.bitop;
import core.checkedint;
import core.simd;
//import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

int[ ][3][3] shirts;
int[2 * 10^^5] p;
ubyte[2 * 10^^5] a, b;

void main() {
    int n;
    read(n);
    foreach (ref x; p[0 .. n])
        read(x);
    foreach (ref x; a[0 .. n])
        read(x);
    foreach (ref x; b[0 .. n])
        read(x);
    foreach (i; 0 .. n)
        shirts[a[i] - 1][b[i] - 1] ~= p[i];
    foreach (i; 0 .. 3)
        foreach (j; 0 .. 3)
            shirts[i][j].sort!`a > b`;
    int q;
    read(q);
    while (q--) {
        ubyte c;
        read(c);
        c--;
        uint result = uint.max;
        int y = -1, x = -1;
        foreach (i; 0 .. 3)
            if (!shirts[i][c].empty && shirts[i][c].back < result) {
                y = i;
                x = c;
                result = shirts[y][x].back;
            }
        foreach (j; 0 .. 3)
            if (!shirts[c][j].empty && shirts[c][j].back < result) {
                y = c;
                x = j;
                result = shirts[y][x].back;
            }
        if (~result) {
            shirts[y][x].popBack();
            write(result, ' ');
        } else
            write("-1 ");
    }
    writeln();
}


There are $$$n$$$ people sitting in a circle, numbered from $$$1$$$ to $$$n$$$ in the order in which they are seated. That is, for all $$$i$$$ from $$$1$$$ to $$$n-1$$$, the people with id $$$i$$$ and $$$i+1$$$ are adjacent. People with id $$$n$$$ and $$$1$$$ are adjacent as well.The person with id $$$1$$$ initially has a ball. He picks a positive integer $$$k$$$ at most $$$n$$$, and passes the ball to his $$$k$$$-th neighbour in the direction of increasing ids, that person passes the ball to his $$$k$$$-th neighbour in the same direction, and so on until the person with the id $$$1$$$ gets the ball back. When he gets it back, people do not pass the ball any more.For instance, if $$$n = 6$$$ and $$$k = 4$$$, the ball is passed in order $$$[1, 5, 3, 1]$$$. Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $$$1 + 5 + 3 = 9$$$.Find and report the set of possible fun values for all choices of positive integer $$$k$$$. It can be shown that under the constraints of the problem, the ball always gets back to the $$$1$$$-st player after finitely many steps, and there are no more than $$$10^5$$$ possible fun values for given $$$n$$$.

The only line consists of a single integer $$$n$$$ ($$$2 \leq n \leq 10^9$$$) — the number of people playing with the ball.

Suppose the set of all fun values is $$$f_1, f_2, \dots, f_m$$$. Output a single line containing $$$m$$$ space separated integers $$$f_1$$$ through $$$f_m$$$ in increasing order.

NoteIn the first sample, we've already shown that picking $$$k = 4$$$ yields fun value $$$9$$$, as does $$$k = 2$$$. Picking $$$k = 6$$$ results in fun value of $$$1$$$. For $$$k = 3$$$ we get fun value $$$5$$$ and with $$$k = 1$$$ or $$$k = 5$$$ we get $$$21$$$.   In the second sample, the values $$$1$$$, $$$10$$$, $$$28$$$, $$$64$$$ and $$$136$$$ are achieved for instance for $$$k = 16$$$, $$$8$$$, $$$4$$$, $$$10$$$ and $$$11$$$, respectively.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		bool [int] b;

		void go (int v)
		{
			auto d = gcd (v, n);
			b[d] = true;
		}

		for (int d = 1; d * d <= n; d++)
		{
			go (d);
			go (n / d);
		}

		auto p = b.keys;
		bool [long] c;

		foreach (int q; p)
		{
			long res = n / q;
			res *= n - q;
			res /= 2;
			res += n / q;
			c[res] = true;
		}

		auto ans = c.keys;
		sort (ans);
		writefln ("%(%s %)", ans);
	}
}

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

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

    long[] ans;

    for (int d = 1; d*d <= n; d++) {
        if (n % d != 0) {
            continue;
        }
        ans ~= 1L * n * (n / d - 1) / 2 + n / d;
        auto c = n / d;
        ans ~= 1L * n * (n / c - 1) / 2 + n / c;
    }

    auto anss = ans.sort().uniq();

    writefln("%(%s %)", anss);
}

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

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

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

void main() {
  import std.stdio, std.string, std.conv, std.algorithm;
  import std.range;

  // for (int n = 2; n <= 20; n++) {
  // auto ids = iota(n);
  // int[] ans;
  // for (int k = 1; k <= n; k++) {
  // int cur = k, s = 1;
  // while (cur % n) {
  // s += (cur + 1);
  // cur += k;
  // cur %= n;
  // }
  // ans ~= s;
  // }
  // ans = ans.sort.uniq.array;
  // writeln(n, " ", ans);
  // }

  long n;
  rd(n);
  long[] ans;
  for (long i = 1; i * i <= n; i++) {
    if (n % i == 0) {
      auto j = n / i;
      ans ~= i * (2 + (i - 1) * j) / 2;
      ans ~= j * (2 + (j - 1) * i) / 2;
    }
  }
  ans = ans.sort.uniq.array;
  writefln("%(%s %)", ans);
}

// 16
// 1 10 28 64 136
// 1  2  4  8  16
// 1 = 1
// 10 = 1 + 9
// 28 = 1 + 5 + 9 + 13
// 64 = 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}


You are given a matrix $$$a$$$ consisting of positive integers. It has $$$n$$$ rows and $$$m$$$ columns.Construct a matrix $$$b$$$ consisting of positive integers. It should have the same size as $$$a$$$, and the following conditions should be met:   $$$1 \le b_{i,j} \le 10^6$$$;  $$$b_{i,j}$$$ is a multiple of $$$a_{i,j}$$$;  the absolute value of the difference between numbers in any adjacent pair of cells (two cells that share the same side) in $$$b$$$ is equal to $$$k^4$$$ for some integer $$$k \ge 1$$$ ($$$k$$$ is not necessarily the same for all pairs, it is own for each pair). We can show that the answer always exists.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n,m \le 500$$$). Each of the following $$$n$$$ lines contains $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$a_{i,j}$$$ ($$$1 \le a_{i,j} \le 16$$$).

The output should contain $$$n$$$ lines each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line should be $$$b_{i,j}$$$.

NoteIn the first example, the matrix $$$a$$$ can be used as the matrix $$$b$$$, because the absolute value of the difference between numbers in any adjacent pair of cells is $$$1 = 1^4$$$.In the third example:   $$$327$$$ is a multiple of $$$3$$$, $$$583$$$ is a multiple of $$$11$$$, $$$408$$$ is a multiple of $$$12$$$, $$$664$$$ is a multiple of $$$8$$$;  $$$|408 - 327| = 3^4$$$, $$$|583 - 327| = 4^4$$$, $$$|664 - 408| = 4^4$$$, $$$|664 - 583| = 3^4$$$.

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

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

    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j){
            int colr = (i & 1) ^ (j & 1);
            if(!colr){
                mat[i][j] = 720720;
            }else{
                mat[i][j] *= mat[i][j];
                mat[i][j] *= mat[i][j];
                mat[i][j] += 720720;
            }
        }
    }
    foreach(row; mat){
        row.each!(cell => write(cell, " "));
        writeln;
    }
}

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

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

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

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

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

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

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

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

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

enum X = 720720;
enum PP = [0, 13439, 106064, 189279, 106064, 330095, 388944, 106064, 106064, 189279, 560720, 486464, 388944, 263744, 106064, 670095, 106064];

void main()
{
    int N, M; get(N, M);
    int[][] aa; get_lines(N, aa);

    auto bb = new int[][](N, M);
    foreach (i; 0..N) foreach (j; 0..M) {
        if ((i + j) % 2 == 0) {
            bb[i][j] = X;
        } else {
            bb[i][j] = PP[aa[i][j]];
        }
    }
    writefln!"%(%(%d %)\n%)"(bb);
}

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

void main ()
{
	int rows, cols;
	while (readf !(" %s %s") (rows, cols) > 0)
	{
		int [] [] board;
		readln;
		foreach (row; 0..rows)
		{
			board ~= readln.splitter.map !(to !(int)).array;
		}
		auto answer = new int [] [] (rows, cols);
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				int value = 720_720;
				if ((row ^ col) & 1)
				{
					value -= board[row][col] ^^ 4;
				}
				answer[row][col] = value;
			}
		}
		writefln !("%(%(%s %)\n%)") (answer);
	}
}