Many years have passed, and n friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo.Simply speaking, the process of photographing can be described as follows. Each friend occupies a rectangle of pixels on the photo: the i-th of them in a standing state occupies a wi pixels wide and a hi pixels high rectangle. But also, each person can lie down for the photo, and then he will occupy a hi pixels wide and a wi pixels high rectangle.The total photo will have size W × H, where W is the total width of all the people rectangles, and H is the maximum of the heights. The friends want to determine what minimum area the group photo can they obtain if no more than n / 2 of them can lie on the ground (it would be strange if more than n / 2 gentlemen lie on the ground together, isn't it?..)Help them to achieve this goal.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of friends. The next n lines have two integers wi, hi (1 ≤ wi, hi ≤ 1000) each, representing the size of the rectangle, corresponding to the i-th friend.

Print a single integer equal to the minimum possible area of the photo containing all friends if no more than n / 2 of them can lie on the ground.

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;

immutable int MAX_H = 1003;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Pair = Tuple !(int, q{w}, int, q{h});
		auto a = new Pair [n];
		foreach (ref x; a)
		{
			readf (" %s %s", &x.w, &x.h);
		}
		sort !((x, y) => x.w - x.h > y.w - y.h) (a);
		debug {writeln (a);}
		int res = int.max;
		for (int t = 1; t <= MAX_H; t++)
		{
			int s = 0;
			auto b = a.filter !(x => x.h > t && x.w > t);
			if (!b.empty)
			{
				continue;
			}
			auto c = a.filter !(x => x.h > t && x.w <= t);
			int clen = c.walkLength;
			if (clen > n / 2)
			{
				continue;
			}
			s += c.map !(x => x.h).sum;
			auto d = a.filter !(x => x.h <= t);
			debug {writeln (b.walkLength, ' ', c.walkLength, ' ',
			    d.walkLength);}
			foreach (cur; d)
			{
				if (cur.w > cur.h &&
				    cur.w <= t &&
				    clen < n / 2)
				{
					s += cur.h;
					clen++;
				}
				else
				{
					s += cur.w;
				}
			}
			debug {writeln (s, ' ', t);}
			res = min (res, s * t);
		}
		writeln (res);
	}
}


Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times:   Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible.

First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$  — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.

Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible.

NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially.

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

immutable int NA = -1;

void main ()
{
	int n;
multitest_loop:
	while (readf !(" %s") (n) > 0)
	{
		auto a = new int [n];
		auto b = new int [n];
		auto c = new int [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s %s") (a[i], b[i], c[i]);
		}
		auto adj = new int [] [n];
		foreach (j; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}

		if (sum (b) != sum (c))
		{
			writeln (-1);
			continue multitest_loop;
		}

		long recur (int v, int p)
		{
			long res = 0;
			int need = b[v] - c[v];
			foreach (u; adj[v])
			{
				if (u != p)
				{
					a[u] = min (a[u], a[v]);
					res += recur (u, v);
					b[v] += b[u];
					c[v] += c[u];
					int next = b[u] - c[u];
					while (need < 0 && next > 0)
					{
						res += a[v];
						need += 1;
						next -= 1;
					}
					while (need > 0 && next < 0)
					{
						res += a[v];
						need -= 1;
						next += 1;
					}
					need += next;
				}
			}
			return res;
		}

		long res = recur (0, NA);
		writeln (res * 2);
	}
}

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;

void main(string[] args)
{
  inputFile = stdin;
  auto n = next!int;
  enum NodeType
    {
      empty,
      mis0,
      mis1,
    }
  auto nodetype = new NodeType[](n);
  auto aValue = new long[](n);
  int dlt = 0;
  foreach(i; 0 .. n)
    {
      auto a = next!long;
      auto b = next!long;
      auto c = next!long;
      aValue[i] = a;
      if (b == c)
	{
	  nodetype[i] = NodeType.empty;
	}
      else
	{
	  if (b == 0)
	    {
	      nodetype[i] = NodeType.mis0;
	      dlt++;
	    }
	  else
	    {
	      nodetype[i] = NodeType.mis1;
	      dlt--;
	    }
	}
    }
  if (dlt != 0) return writeln(-1);
  debug writeln(nodetype);
  auto mis1cnt = new int[](n);
  auto mis0cnt = new int[](n);
  auto cost = new long[](n);
  auto height = new int[](n);
  auto parent = new int[](n);
  auto als = new int[][](n);
  foreach(i; 0 .. n - 1)
    {
      auto u = next!int - 1;
      auto v = next!int - 1;
      als[u] ~= v;
      als[v] ~= u;
    }
  auto queue = new Tuple!(int, int)[](n);
  void calcdfs(int v, long c, int h, int p)
  {
    cost[v] = c;
    height[v] = h;
    parent[v] = p;
    queue[v] = tuple(h, v);
    mis1cnt[v] = (nodetype[v] == NodeType.mis1);
    mis0cnt[v] = (nodetype[v] == NodeType.mis0);
    foreach(w; als[v])
      if (w != p)
	{
	  calcdfs(w, min(cost[v], aValue[w]), h + 1, v);
	}
  }
  /*
            1
          /   \
	 5     2
              / \
             4   3
   */
  calcdfs(0, aValue[0], 0, -1);
  auto squeue = sort(queue);
  auto totalCost = long(0);
  foreach_reverse(q; squeue)
    {
      auto node = q[1];
      debug writeln("doing node ", node + 1, " m0 ", mis0cnt[node], " m1 ", mis1cnt[node]);
      auto toremove = min(mis1cnt[node], mis0cnt[node]);
      totalCost += toremove * cost[node] * 2;
      mis1cnt[node] -= toremove;
      mis0cnt[node] -= toremove;
      debug writeln("doing node ", node + 1, " m0 ", mis0cnt[node], " m1 ", mis1cnt[node],
		    " p ", parent[node] + 1);
      if (parent[node] != -1)
	{
	  mis1cnt[parent[node]] += mis1cnt[node];
	  mis0cnt[parent[node]] += mis0cnt[node];
	}
    }
  totalCost.writeln;
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  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.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
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 n = RD!int;
	auto a = new long[](n);
	auto b = new long[](n);
	auto c = new long[](n);
	foreach (i; 0..n)
	{
		a[i] = RD;
		b[i] = RD;
		c[i] = RD;
	}
	auto edges = new int[][](n);
	foreach (i; 0..n-1)
	{
		auto u = RD!int-1;
		auto v = RD!int-1;
		edges[u] ~= v;
		edges[v] ~= u;
	}

	auto d = new long[](n);
	auto cnt = new long[](n);
	auto par = new int[](n);

	long[] dfs(int pos, int last)
	{
		par[pos] = last;
		d[pos] = c[pos] - b[pos];
		cnt[pos] = b[pos] == c[pos] ? 0 : 1;
		foreach (to; edges[pos])
		{
			if (to == last) continue;
			auto r = dfs(to, pos);
			d[pos] += r[0];
			cnt[pos] += r[1];
		}
		return [d[pos], cnt[pos]];
	}
	dfs(0, -1);

	if (d[0] != 0)
		writeln(-1);
	else
	{
		long ans = a[0] * cnt[0];
		void dfs2(int pos, int last, long cost)
		{
			if (a[pos] < cost)
			{
				auto x = cnt[pos] - abs(d[pos]);
				ans -= cost * x;
				ans += a[pos] * x;
				cost = a[pos];
			}

			foreach (to; edges[pos])
			{
				if (to == last) continue;
				dfs2(to, pos, cost);
			}
		}
		dfs2(0, -1, a[0]);
		writeln(ans);
	}

	stdout.flush;
	debug readln;
}

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;

void main(string[] args)
{
  inputFile = stdin;
  auto n = next!int;
  enum NodeType
    {
      empty,
      mis0,
      mis1,
    }
  auto nodetype = new NodeType[](n);
  auto aValue = new int[](n);
  int dlt = 0;
  foreach(i; 0 .. n)
    {
      auto a = next!int;
      auto b = next!int;
      auto c = next!int;
      aValue[i] = a;
      if (b == c)
	{
	  nodetype[i] = NodeType.empty;
	}
      else
	{
	  if (b == 0)
	    {
	      nodetype[i] = NodeType.mis0;
	      dlt++;
	    }
	  else
	    {
	      nodetype[i] = NodeType.mis1;
	      dlt--;
	    }
	}
    }
  if (dlt != 0) return writeln(-1);
  debug writeln(nodetype);
  auto mis1cnt = new int[](n);
  auto mis0cnt = new int[](n);
  auto cost = new int[](n);
  auto height = new int[](n);
  auto parent = new int[](n);
  auto als = new int[][](n);
  foreach(i; 0 .. n - 1)
    {
      auto u = next!int - 1;
      auto v = next!int - 1;
      als[u] ~= v;
      als[v] ~= u;
    }
  auto queue = new Tuple!(int, int)[](n);
  void calcdfs(int v, int c, int h, int p)
  {
    cost[v] = c;
    height[v] = h;
    parent[v] = p;
    queue[v] = tuple(h, v);
    mis1cnt[v] = (nodetype[v] == NodeType.mis1);
    mis0cnt[v] = (nodetype[v] == NodeType.mis0);
    foreach(w; als[v])
      if (w != p)
	{
	  calcdfs(w, min(cost[v], aValue[w]), h + 1, v);
	}
  }
  /*
            1
          /   \
	 5     2
              / \
             4   3
   */
  calcdfs(0, aValue[0], 0, -1);
  auto squeue = sort(queue);
  auto totalCost = long(0);
  foreach_reverse(q; squeue)
    {
      auto node = q[1];
      debug writeln("doing node ", node + 1, " m0 ", mis0cnt[node], " m1 ", mis1cnt[node]);
      auto toremove = min(mis1cnt[node], mis0cnt[node]);
      totalCost += toremove * cost[node] * 2;
      mis1cnt[node] -= toremove;
      mis0cnt[node] -= toremove;
      debug writeln("doing node ", node + 1, " m0 ", mis0cnt[node], " m1 ", mis1cnt[node],
		    " p ", parent[node] + 1);
      if (parent[node] != -1)
	{
	  mis1cnt[parent[node]] += mis1cnt[node];
	  mis0cnt[parent[node]] += mis0cnt[node];
	}
    }
  totalCost.writeln;
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  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.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
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 n = RD!int;
	auto a = new long[](n);
	auto b = new long[](n);
	auto c = new long[](n);
	foreach (i; 0..n)
	{
		a[i] = RD;
		b[i] = RD;
		c[i] = RD;
	}
	auto edges = new int[][](n);
	foreach (i; 0..n-1)
	{
		auto u = RD!int-1;
		auto v = RD!int-1;
		edges[u] ~= v;
		edges[v] ~= u;
	}

	auto d = new long[](n);
	auto cnt = new long[](n);
	auto par = new int[](n);

	long[] dfs(int pos, int last)
	{
		par[pos] = last;
		d[pos] = c[pos] - b[pos];
		cnt[pos] = b[pos] == c[pos] ? 0 : 1;
		foreach (to; edges[pos])
		{
			if (to == last) continue;
			auto r = dfs(to, pos);
			d[pos] += r[0];
			cnt[pos] += r[1];
		}
		return [d[pos], cnt[pos]];
	}
	dfs(0, -1);

	if (d[0] != 0)
		writeln(-1);
	else
	{
		long ans;
		auto index = a.MAKE_IDX();
		foreach (i; index)
		{
			auto x = min(cnt[i] - abs(d[i]), cnt[0]);
			cnt[i] -= x;
			ans += x * a[i];
			if (cnt[0] == 0)
				break;
			auto p = par[i];
			while (p != -1)
			{
				cnt[p] -= x;
				p = par[p];
			}
		}
		writeln(ans);
	}

	stdout.flush;
	debug readln;
}


Michael has just bought a new electric car for moving across city. Michael does not like to overwork, so each day he drives to only one of two his jobs.Michael's day starts from charging his electric car for getting to the work and back. He spends 1000 burles on charge if he goes to the first job, and 2000 burles if he goes to the second job.On a charging station he uses there is a loyalty program that involves bonus cards. Bonus card may have some non-negative amount of bonus burles. Each time customer is going to buy something for the price of x burles, he is allowed to pay an amount of y (0 ≤ y ≤ x) burles that does not exceed the bonus card balance with bonus burles. In this case he pays x - y burles with cash, and the balance on the bonus card is decreased by y bonus burles. If customer pays whole price with cash (i.e., y = 0) then 10% of price is returned back to the bonus card. This means that bonus card balance increases by  bonus burles. Initially the bonus card balance is equal to 0 bonus burles.Michael has planned next n days and he knows how much does the charge cost on each of those days. Help Michael determine the minimum amount of burles in cash he has to spend with optimal use of bonus card. Assume that Michael is able to cover any part of the price with cash in any day. It is not necessary to spend all bonus burles at the end of the given period.

The first line of input contains a single integer n (1 ≤ n ≤ 300 000), the number of days Michael has planned. Next line contains n integers a1, a2, ..., an (ai = 1000 or ai = 2000) with ai denoting the charging cost at the day i.

Output the minimum amount of burles Michael has to spend.

NoteIn the first sample case the most optimal way for Michael is to pay for the first two days spending 3000 burles and get 300 bonus burles as return. After that he is able to pay only 700 burles for the third days, covering the rest of the price with bonus burles.In the second sample case the most optimal way for Michael is to pay the whole price for the first five days, getting 1000 bonus burles as return and being able to use them on the last day without paying anything in cash.

module main;
__gshared:
import core.bitop, std.algorithm, std.bigint, std.bitmanip, std.complex,
	std.container, std.conv, std.datetime, std.functional, std.math, std.meta;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.parallelism, std.random, std.range, std.regex, std.stdio, std.string,
	std.traits, std.typecons, std.uni, std.variant;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
enum mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///lcm
		T lcm(T)(auto ref T a, auto ref T b)
		{
			return a / gcd(a, b) * b;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///BigInt greatest common divizor
		BigInt gcd(BigInt a, BigInt b)
		{
			while (b)
			{
				a %= b;
				swap(a, b);
			}
			return a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (!(a[m] < g))
					r = m;
				else
					l = m;
			}
			return (!(a[l] < g)) ? l : r;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (g < a[m])
					r = m;
				else
					l = m;
			}
			return (g < a[l]) ? l : r;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return binf(a, g) != a.length;
		}
	}
	///write an array
	void putarr(X)(in X a, in char ch = ' ') if (isInputRange!X)
	{
		writefln("%(%s" ~ ch ~ "%)", a);
	}
	///write a matrix
	void putarr(X)(in X a)
			if (isInputRange!X && isInputRange!(ElementType!X) && !isSomeString!(ElementType!X))
	{
		writefln("%(%(%s %)\n%)", a);
	}
	///get an array
	bool getarr(X)(X a, in size_t n)
	{
		bool b = 1;
		foreach (ref i; a[0 .. n])
			b = input(&i);
		return b;
	}
	///read without format
	bool input(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		return s == ptrs.length;
	}
	///readln without format
	bool read(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		readln;
		return s == ptrs.length;
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version (home)
	{
		freopen("input.txt", "r", core.stdc.stdio.stdin);
		//freopen("output.txt", "w", core.stdc.stdio.stdout);
	}
	int n;
	loop: while (read(n))
	{
		auto a = arread!int;
		foreach (ref x; a)
		{
			x /= 100;
		}
		auto dp = new int[][n];
		dp[0] = new int[31];
		dp[0][] = int.max;
		dp[0][a[0] / 10] = a[0];
		foreach (int i; 1 .. n)
		{
			dp[i] = new int[31];
			dp[i][] = int.max;
			foreach (int j; 0 .. 31)
			{
				if (dp[i - 1][j] != int.max)
				{
					if (j + a[i] / 10 <= 30)
						dp[i][j + a[i] / 10] = min(dp[i][j + a[i] / 10], dp[i - 1][j] + a[i]);
					dp[i][max(0, j - a[i])] = min(dp[i][max(0, j - a[i])],
							dp[i - 1][j] + max(0, a[i] - j));
				}
			}
		}
		writeln(fold!(min)(dp[n - 1]) * 100);
	}
}

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

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

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

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

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

      auto ASum = new int[N + 1];
      foreach (i; 0 .. N) {
        ASum[i + 1] = ASum[i] + A[i];
      }

      int ans;
      foreach (i; 0 .. N + 1) {
        chmax(ans, min(ASum[i], 10 * (ASum[N] - ASum[i])));
      }

      /*
        |1
          22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i + 1; j < N && A[j] == 2; ++j) {}
          const s = j - (i + 1);
          foreach (t; 0 .. s + 1) {
            const a = min(ASum[i], 10);
            const score = a + min(ASum[i] - a + 2 * t, 20 * (s - t) + 10 * (ASum[N] - ASum[j]));
            chmax(ans, score);
          }
        }
      }
      /*
             1|
        22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i; j > 0 && A[j - 1] == 2; --j) {}
          debug {
            writeln("! ", j, " ", i);
          }
          const s = i - j;
          foreach (t; 0 .. s + 1) {
            const a = min(ASum[j] + 2 * t, 20 * (s - t));
            const score = a + min((ASum[j] + 2 * t) - a + 1, 10 * (ASum[N] - ASum[i + 1]));
            debug {
              writeln("  ", t, ": ", score);
            }
            chmax(ans, score);
          }
        }
      }

      debug {
        writeln("ans = ", ans);
      }
      writeln(1000L * ASum[N] - 100L * ans);

      debug {
        auto dp = new int[][](N + 1, 2 * N + 1);
        foreach (i; 0 .. N + 1) {
          dp[i][] = -1;
        }
        dp[0][0] = 0;
        foreach (i; 0 .. N) {
          foreach (j; 0 .. 2 * N + 1) {
            if (dp[i][j] >= 0) {
              // chmax(dp[i + 1][j + A[i]], dp[i][j] + A[i]);
              foreach (dj; 1 .. A[i] + 1) {
                chmax(dp[i + 1][j + dj], dp[i][j] + dj);
              }
              chmax(dp[i + 1][max(j - 10 * A[i], 0)], dp[i][j]);
            }
          }
        }
        foreach (i; 0 .. N + 1) {
          writeln(i, ": ", dp[i]);
        }
        assert(dp[N][0] == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto ASum = new int[N + 1];
      foreach (i; 0 .. N) {
        ASum[i + 1] = ASum[i] + A[i];
      }

      int ans;
      foreach (i; 0 .. N + 1) {
        chmax(ans, min(ASum[i], 10 * (ASum[N] - ASum[i])));
      }

      /*
        |1
          22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i + 1; j < N && A[j] == 2; ++j) {}
          const s = j - (i + 1);
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[i], 10);
            const score = a + min(ASum[i] - a + 2 * t, 20 * (s - t) + 10 * (ASum[N] - ASum[j]));
            chmax(ans, score);
          }
        }
      }
      /*
             1|
        22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i; j > 0 && A[j - 1] == 2; --j) {}
          const s = j - i;
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[j] + 2 * t, 20 * (s - t));
            const score = min((ASum[j] + 2 * t) - a + 1, 10 * (ASum[N] - ASum[i + 1]));
            chmax(ans, score);
          }
        }
      }

      debug {
        writeln("ans = ", ans);
      }
      writeln(1000L * ASum[N] - 100L * ans);

      debug {
        auto dp = new int[][](N + 1, 2 * N + 1);
        foreach (i; 0 .. N + 1) {
          dp[i][] = -1;
        }
        dp[0][0] = 0;
        foreach (i; 0 .. N) {
          foreach (j; 0 .. 2 * N + 1) {
            if (dp[i][j] >= 0) {
              // chmax(dp[i + 1][j + A[i]], dp[i][j] + A[i]);
              foreach (dj; 1 .. A[i] + 1) {
                chmax(dp[i + 1][j + dj], dp[i][j] + dj);
              }
              chmax(dp[i + 1][max(j - 10 * A[i], 0)], dp[i][j]);
            }
          }
        }
        foreach (i; 0 .. N + 1) {
          writeln(i, ": ", dp[i]);
        }
        assert(dp[N][0] == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto ASum = new int[N + 1];
      foreach (i; 0 .. N) {
        ASum[i + 1] = ASum[i] + A[i];
      }

      int ans;
      foreach (i; 0 .. N + 1) {
        chmax(ans, min(ASum[i], 10 * (ASum[N] - ASum[i])));
      }

      /*
        |1
          22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i + 1; j < N && A[j] == 2; ++j) {}
          const s = j - (i + 1);
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[i], 10);
            const score = a + min(ASum[i] - a + 2 * t, 20 * (s - t) + 10 * (ASum[N] - ASum[j]));
            chmax(ans, score);
          }
        }
      }
      /*
             1|
        22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i; j > 0 && A[j - 1] == 2; --j) {}
          const s = i - j;
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[j] + 2 * t, 20 * (s - t));
            const score = min((ASum[j] + 2 * t) - a + 1, 10 * (ASum[N] - ASum[i + 1]));
            chmax(ans, score);
          }
        }
      }

      debug {
        writeln("ans = ", ans);
      }
      writeln(1000L * ASum[N] - 100L * ans);

      debug {
        auto dp = new int[][](N + 1, 2 * N + 1);
        foreach (i; 0 .. N + 1) {
          dp[i][] = -1;
        }
        dp[0][0] = 0;
        foreach (i; 0 .. N) {
          foreach (j; 0 .. 2 * N + 1) {
            if (dp[i][j] >= 0) {
              // chmax(dp[i + 1][j + A[i]], dp[i][j] + A[i]);
              foreach (dj; 1 .. A[i] + 1) {
                chmax(dp[i + 1][j + dj], dp[i][j] + dj);
              }
              chmax(dp[i + 1][max(j - 10 * A[i], 0)], dp[i][j]);
            }
          }
        }
        foreach (i; 0 .. N + 1) {
          writeln(i, ": ", dp[i]);
        }
        assert(dp[N][0] == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto ASum = new int[N + 1];
      foreach (i; 0 .. N) {
        ASum[i + 1] = ASum[i] + A[i];
      }

      int ans;
      foreach (i; 0 .. N + 1) {
        chmax(ans, min(ASum[i], 10 * (ASum[N] - ASum[i])));
      }

      /*
        |1
          22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i + 1; j < N && A[j] == 2; ++j) {}
          const s = j - (i + 1);
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[i], 10);
            const score = a + min(ASum[i] - a + 2 * t, 20 * (s - t) + 10 * (ASum[N] - ASum[j]));
            chmax(ans, score);
          }
        }
      }
      /*
             1|
        22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i; j > 0 && A[j - 1] == 2; --j) {}
          const s = j - (i + 1);
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[j] + 2 * t, 20 * (s - t));
            const score = min((ASum[j] + 2 * t) - a + 1, 10 * (ASum[N] - ASum[i + 1]));
            chmax(ans, score);
          }
        }
      }

      debug {
        writeln("ans = ", ans);
      }
      writeln(1000L * ASum[N] - 100L * ans);

      debug {
        auto dp = new int[][](N + 1, 2 * N + 1);
        foreach (i; 0 .. N + 1) {
          dp[i][] = -1;
        }
        dp[0][0] = 0;
        foreach (i; 0 .. N) {
          foreach (j; 0 .. 2 * N + 1) {
            if (dp[i][j] >= 0) {
              // chmax(dp[i + 1][j + A[i]], dp[i][j] + A[i]);
              foreach (dj; 1 .. A[i] + 1) {
                chmax(dp[i + 1][j + dj], dp[i][j] + dj);
              }
              chmax(dp[i + 1][max(j - 10 * A[i], 0)], dp[i][j]);
            }
          }
        }
        foreach (i; 0 .. N + 1) {
          writeln(i, ": ", dp[i]);
        }
        assert(dp[N][0] == ans);
      }
    }
  } catch (EOFException e) {
  }
}


Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions.Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions.  Spells of this type speed up the preparation time of one potion. There are m spells of this type, the i-th of them costs bi manapoints and changes the preparation time of each potion to ai instead of x.  Spells of this type immediately prepare some number of potions. There are k such spells, the i-th of them costs di manapoints and instantly create ci potions. Anton can use no more than one spell of the first type and no more than one spell of the second type, and the total number of manapoints spent should not exceed s. Consider that all spells are used instantly and right before Anton starts to prepare potions.Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least n potions.

The first line of the input contains three integers n, m, k (1 ≤ n ≤ 2·109, 1 ≤ m, k ≤ 2·105) — the number of potions, Anton has to make, the number of spells of the first type and the number of spells of the second type. The second line of the input contains two integers x and s (2 ≤ x ≤ 2·109, 1 ≤ s ≤ 2·109) — the initial number of seconds required to prepare one potion and the number of manapoints Anton can use. The third line contains m integers ai (1 ≤ ai < x) — the number of seconds it will take to prepare one potion if the i-th spell of the first type is used. The fourth line contains m integers bi (1 ≤ bi ≤ 2·109) — the number of manapoints to use the i-th spell of the first type. There are k integers ci (1 ≤ ci ≤ n) in the fifth line — the number of potions that will be immediately created if the i-th spell of the second type is used. It's guaranteed that ci are not decreasing, i.e. ci ≤ cj if i < j. The sixth line contains k integers di (1 ≤ di ≤ 2·109) — the number of manapoints required to use the i-th spell of the second type. It's guaranteed that di are not decreasing, i.e. di ≤ dj if i < j.

Print one integer — the minimum time one has to spent in order to prepare n potions.

NoteIn the first sample, the optimum answer is to use the second spell of the first type that costs 10 manapoints. Thus, the preparation time of each potion changes to 4 seconds. Also, Anton should use the second spell of the second type to instantly prepare 15 potions spending 80 manapoints. The total number of manapoints used is 10 + 80 = 90, and the preparation time is 4·5 = 20 seconds (15 potions were prepared instantly, and the remaining 5 will take 4 seconds each).In the second sample, Anton can't use any of the spells, so he just prepares 20 potions, spending 10 seconds on each of them and the answer is 20·10 = 200.

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

struct spell {
    int pnt;
    int eff;
}

int main() {
    debug stdin = File("in.txt", "r");

    int n, m, k;
    readf(" %s %s %s\n", &n, &m, &k);
    int x, s;
    readf(" %s %s\n", &x, &s);
    spell[] t1 = new spell[m+1];
    spell[] t2 = new spell[k+1];
    t1[0].pnt = 0;
    t1[0].eff = x;
    t2[0].pnt = 0;
    t2[0].eff = 0;
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].pnt);
    }
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].pnt);
    }
    readf("\n");

    long answer = long.max;
    int pntsAvail = s;
    long poTime = x;
    spell dummySpell;
    auto t2as = assumeSorted!"a.pnt < b.pnt"(t2);
    foreach ( s1; t1 ) {
        pntsAvail = s - s1.pnt;
        if (pntsAvail < 0) continue;
        poTime = s1.eff;
        dummySpell.pnt = pntsAvail;
        auto idx = k - t2as.upperBound(dummySpell).length;
        long toMake = max(0, n - t2[idx].eff);
        answer = min(answer, toMake * poTime);
    }
    writeln(answer);

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

struct spell {
    int pnt;
    int eff;
}

int main() {
    debug stdin = File("in.txt", "r");

    int n, m, k;
    readf(" %s %s %s\n", &n, &m, &k);
    int x, s;
    readf(" %s %s\n", &x, &s);
    spell[] t1 = new spell[m+1];
    spell[] t2 = new spell[k+1];
    t1[0].pnt = 0;
    t1[0].eff = x;
    t2[0].pnt = 0;
    t2[0].eff = 0;
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].pnt);
    }
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].pnt);
    }
    readf("\n");

    long answer = long.max;
    int pntsAvail = s;
    long poTime = x;
    spell dummySpell;
    auto t2as = assumeSorted!"a.pnt < b.pnt"(t2);
    foreach ( s1; t1 ) {
        pntsAvail = s - s1.pnt;
        if (pntsAvail < 0) continue;
        poTime = s1.eff;
        dummySpell.pnt = pntsAvail;
        auto idx = t2as.lowerBound(dummySpell).length;
        while (idx < t2.length && t2[idx].pnt <= pntsAvail) ++idx;
        if (idx > 0) --idx;
        long toMake = max(0, n - t2[idx].eff);
        answer = min(answer, toMake * poTime);
    }
    writeln(answer);

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

struct spell {
    int pnt;
    int eff;
}

int main() {
    debug stdin = File("in.txt", "r");

    int n, m, k;
    readf(" %s %s %s\n", &n, &m, &k);
    int x, s;
    readf(" %s %s\n", &x, &s);
    spell[] t1 = new spell[m+1];
    spell[] t2 = new spell[k+1];
    t1[0].pnt = 0;
    t1[0].eff = x;
    t2[0].pnt = 0;
    t2[0].eff = 0;
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].pnt);
    }
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].pnt);
    }
    readf("\n");

    long answer = long.max;
    int pntsAvail = s;
    long poTime = x;
    foreach ( s1; t1 ) {
        pntsAvail = s - s1.pnt;
        if (pntsAvail < 0) continue;
        poTime = s1.eff;
        int lo = 0, hi = k;
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (pntsAvail < t2[mid].pnt) hi = mid;
            else lo = mid + 1;
        }
        if (pntsAvail < t2[lo].pnt) --lo;
        long toMake = max(0, n - t2[lo].eff);
        answer = min(answer, toMake * poTime);
    }
    writeln(answer);

    return 0;
}

import core.bitop;
import core.checkedint;
import core.simd;
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:

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

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

alias Spell1 = Tuple!(int, `manacost`, int, `newTime`);
alias Spell2 = Tuple!(int, `manacost`, int, `handicap`);

int n, m, k;
int baseTime, manapool;
Spell1[200_000] _spells1;
Spell2[200_000] _spells2;
Spell1[ ] spells1;
Spell2[ ] spells2;
int[200_000] _maxHandicap;
int[ ] maxHandicap;

long check(int mana, int time) {
    int left = 0, right = k;
    while (left != right) {
        int mid = (left + right) >>> 1;
        if (mana < spells2[mid].manacost)
            right = mid;
        else
            left = mid + 1;
    }
    return (left? n - maxHandicap[left - 1] : n) * cast(long)time;
}

void main() {
    while (read(&n, &m, &k, &baseTime, &manapool)) {
        spells1 = _spells1[0 .. m];
        spells2 = _spells2[0 .. k];
        maxHandicap = _maxHandicap[0 .. k];
        foreach (ref sp; spells1)
            read(&sp.newTime);
        foreach (ref sp; spells1)
            read(&sp.manacost);
        foreach (ref sp; spells2)
            read(&sp.handicap);
        foreach (ref sp; spells2)
            read(&sp.manacost);
        int t = 0;
        foreach (ref sp, ref b; lockstep(spells2, maxHandicap))
            b = t = max(t, sp.handicap);
        long result = check(manapool, baseTime);
        foreach (ref sp; spells1)
            if (sp.manacost <= manapool)
                result = min(result, check(manapool - sp.manacost, sp.newTime));
        writeln(result);
    }
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

struct spell {
    int pnt;
    int eff;
}

int main() {
    debug stdin = File("in.txt", "r");

    int n, m, k;
    readf(" %s %s %s\n", &n, &m, &k);
    int x, s;
    readf(" %s %s\n", &x, &s);
    spell[] t1 = new spell[m+1];
    spell[] t2 = new spell[k+1];
    t1[0].pnt = 0;
    t1[0].eff = x;
    t2[0].pnt = 0;
    t2[0].eff = 0;
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].pnt);
    }
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].pnt);
    }
    readf("\n");

    int answer = int.max;
    int pntsAvail = s;
    int poTime = x;
    spell dummySpell;
    auto t2as = assumeSorted!"a.pnt < b.pnt"(t2);
    foreach ( s1; t1 ) {
        pntsAvail = s - s1.pnt;
        if (pntsAvail < 0) continue;
        poTime = s1.eff;
        dummySpell.pnt = pntsAvail;
        auto idx = t2as.lowerBound(dummySpell).length;
        while (idx < t2.length && t2[idx].pnt <= pntsAvail) ++idx;
        if (idx > 0) --idx;
        int toMake = max(0, n - t2[idx].eff);
        answer = min(answer, toMake * poTime);
    }
    writeln(answer);

    return 0;
}

import core.bitop;
import core.checkedint;
import core.simd;
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:

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

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

struct Spell1 {
    int manacost, newTime;
}

struct Spell2 {
    int manacost, handicap;
}

int n, m, k;
int baseTime, manapool;
Spell1[200_000] _spells1;
Spell2[200_000] _spells2;
Spell1[ ] spells1;
Spell2[ ] spells2;
int[200_000] _maxHandicap;
int[ ] maxHandicap;

long check(int mana, int time) {
    int left = 0, right = k;
    while (left != right) {
        int mid = (left + right) >>> 1;
        if (mana < spells2[mid].manacost)
            right = mid;
        else
            left = mid + 1;
    }
    return (left? (n - maxHandicap[left - 1]) : n) * cast(long)time;
}

void main() {
    while (read(&n, &m, &k, &baseTime, &manapool)) {
        spells1 = _spells1[0 .. m];
        spells2 = _spells2[0 .. k];
        maxHandicap = _maxHandicap[0 .. m];
        foreach (ref sp; spells1)
            read(&sp.newTime);
        foreach (ref sp; spells1)
            read(&sp.manacost);
        foreach (ref sp; spells2)
            read(&sp.handicap);
        foreach (ref sp; spells2)
            read(&sp.manacost);
        int t = 0;
        foreach (ref sp, ref b; lockstep(spells2, maxHandicap))
            b = t = max(t, sp.handicap);
        long result = check(manapool, baseTime);
        foreach (ref sp; spells1)
            if (sp.manacost <= manapool)
                result = min(result, check(manapool - sp.manacost, sp.newTime));
        writeln(result);
    }
}


Vasya has an array of integers of length n.Vasya performs the following operations on the array: on each step he finds the longest segment of consecutive equal integers (the leftmost, if there are several such segments) and removes it. For example, if Vasya's array is [13, 13, 7, 7, 7, 2, 2, 2], then after one operation it becomes [13, 13, 2, 2, 2].Compute the number of operations Vasya should make until the array becomes empty, i.e. Vasya removes all elements from it.

The first line contains a single integer n (1 ≤ n ≤ 200 000) — the length of the array. The second line contains a sequence a1, a2, ..., an (1 ≤ ai ≤ 109) — Vasya's array.

Print the number of operations Vasya should make to remove all elements from the array.

NoteIn the first example, at first Vasya removes two fives at the second and third positions. The array becomes [2, 2]. In the second operation Vasya removes two twos at the first and second positions. After that the array becomes empty.In the second example Vasya has to perform five operations to make the array empty. In each of them he removes the first element from the array.In the third example Vasya needs three operations. In the first operation he removes all integers 4, in the second — all integers 100, in the third — all integers 2.In the fourth example in the first operation Vasya removes the first two integers 10. After that the array becomes [50, 10, 50, 50]. Then in the second operation Vasya removes the two rightmost integers 50, so that the array becomes [50, 10]. In the third operation he removes the remaining 50, and the array becomes [10] after that. In the last, fourth operation he removes the only remaining 10. The array is empty after that.

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!*******************************************/

void play(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    ll[] lens; lens.length = arr.length;
    auto intervals = rbt!(tup);
    auto adj = rbt!(long);
    ll cnt = 1; int sti = 0;
    foreach(i; 1..arr.length.to!int){
        if(arr[i] == arr[i-1]){
            ++cnt;
        }else{
            intervals.insert(tup(cnt, n - sti));
            adj.insert(sti);
            lens[sti] = cnt;
            sti = i;
            cnt = 1;
        }
    }
    intervals.insert(tup(cnt, n - sti));
    adj.insert(sti);
    lens[sti] = cnt;

    ll oper = 0;
    while(intervals.length){
        tup maxseg = intervals.back;
        ll ix = n - maxseg[1];

        // Remove Max Segment
        intervals.removeBack;
        adj.removeKey(ix);
        ++oper;

        // Handle Interval Merge
        if(adj.length && adj.front < ix && adj.back > ix){
            int lo = adj.lowerBound(ix).back.to!int;
            int hi = adj.upperBound(ix).front.to!int;
            if(arr[lo] == arr[hi]){
                // remo
                adj.removeKey(hi);
                /* debug writeln(lens[lo], " ", lo, " ", lens[hi], hi); */
                intervals.removeKey(tup(lens[lo], n - lo), tup(lens[hi], n - hi));

                lens[lo] += lens[hi];

                // add bac
                intervals.insert(tup(lens[lo], n - lo));
            }
        }
        debug writeln(intervals, adj);
        assert(intervals.length == adj.length);
    }
    writeln(oper);
}

int main(){
    long t = 1;
    /* t = rd;        // Toggle! */
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!*******************************************/

void play(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    ll[] lens; lens.length = arr.length;
    auto intervals = rbt!(tup);
    auto adj = rbt!(long);
    ll cnt = 1; int sti = 0;
    foreach(i; 1..arr.length.to!int){
        if(arr[i] == arr[i-1]){
            ++cnt;
        }else{
            intervals.insert(tup(cnt, sti));
            adj.insert(sti);
            lens[sti] = cnt;
            sti = i;
            cnt = 1;
        }
    }
    intervals.insert(tup(cnt, sti));
    adj.insert(sti);
    lens[sti] = cnt;

    ll oper = 0;
    while(intervals.length){
        tup maxseg = intervals.back;

        // Remove Max Segment
        intervals.removeBack;
        adj.removeKey(maxseg[1]);
        ++oper;

        // Handle Interval Merge
        if(adj.length && adj.front < maxseg[1] && adj.back > maxseg[1]){
            int lo = adj.lowerBound(maxseg[1]).back.to!int;
            int hi = adj.upperBound(maxseg[1]).front.to!int;
            if(arr[lo] == arr[hi]){
                // remo
                adj.removeKey(hi);
                /* debug writeln(lens[lo], " ", lo, " ", lens[hi], hi); */
                intervals.removeKey(tup(lens[lo], lo), tup(lens[hi], hi));

                lens[lo] += lens[hi];

                // add bac
                intervals.insert(tup(lens[lo], lo));
            }
        }
        debug writeln(intervals, adj);
        assert(intervals.length == adj.length);
    }
    writeln(oper);
}

int main(){
    long t = 1;
    /* t = rd;        // Toggle! */
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}


Casimir has a rectangular piece of paper with a checkered field of size $$$n \times m$$$. Initially, all cells of the field are white.Let us denote the cell with coordinates $$$i$$$ vertically and $$$j$$$ horizontally by $$$(i, j)$$$. The upper left cell will be referred to as $$$(1, 1)$$$ and the lower right cell as $$$(n, m)$$$.Casimir draws ticks of different sizes on the field. A tick of size $$$d$$$ ($$$d > 0$$$) with its center in cell $$$(i, j)$$$ is drawn as follows:   First, the center cell $$$(i, j)$$$ is painted black.  Then exactly $$$d$$$ cells on the top-left diagonally to the center and exactly $$$d$$$ cells on the top-right diagonally to the center are also painted black.  That is all the cells with coordinates $$$(i - h, j \pm h)$$$ for all $$$h$$$ between $$$0$$$ and $$$d$$$ are painted. In particular, a tick consists of $$$2d + 1$$$ black cells. An already painted cell will remain black if painted again. Below you can find an example of the $$$4 \times 9$$$ box, with two ticks of sizes $$$2$$$ and $$$3$$$.  You are given a description of a checkered field of size $$$n \times m$$$. Casimir claims that this field came about after he drew some (possibly $$$0$$$) ticks on it. The ticks could be of different sizes, but the size of each tick is at least $$$k$$$ (that is, $$$d \ge k$$$ for all the ticks).Determine whether this field can indeed be obtained by drawing some (possibly none) ticks of sizes $$$d \ge k$$$ or not.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number test cases. The following lines contain the descriptions of the test cases.  The first line of the test case description contains the integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le k \le n \le 10$$$; $$$1 \le m \le 19$$$) — the field size and the minimum size of the ticks that Casimir drew. The following $$$n$$$ lines describe the field: each line consists of $$$m$$$ characters either being '.' if the corresponding cell is not yet painted or '*' otherwise.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be YES if the given field can be obtained by drawing ticks of at least the given size and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answers).

NoteThe first sample test case consists of two asterisks neither of which can be independent ticks since ticks of size $$$0$$$ don't exist.The second sample test case is already described in the statement (check the picture in the statement). This field can be obtained by drawing ticks of sizes $$$2$$$ and $$$3$$$, as shown in the figure.The field in the third sample test case corresponds to three ticks of size $$$1$$$. Their center cells are marked with $$$\color{blue}{\text{blue}}$$$, $$$\color{red}{\text{red}}$$$ and $$$\color{green}{\text{green}}$$$ colors: *.*.*$$$\color{blue}{\textbf{*}}$$$**.$$$\color{green}{\textbf{*}}\color{red}{\textbf{*}}$$$.....The field in the fourth sample test case could have been obtained by drawing two ticks of sizes $$$1$$$ and $$$2$$$. Their vertices are marked below with $$$\color{blue}{\text{blue}}$$$ and $$$\color{red}{\text{red}}$$$ colors respectively: .....*...*.*.*...$$$\color{red}{\textbf{*}}$$$.*...$$$\color{blue}{\textbf{*}}$$$.The field in the fifth sample test case can not be obtained because $$$k = 2$$$, and the last asterisk in the fourth row from the top with coordinates $$$(4, 5)$$$ can only be a part of a tick of size $$$1$$$.The field in the sixth sample test case can not be obtained because the top left asterisk $$$(1, 1)$$$ can't be an independent tick, since the sizes of the ticks must be positive, and cannot be part of a tick with the center cell in the last row, since it is separated from it by a gap (a point, '.') in $$$(2, 2)$$$.In the seventh sample test case, similarly, the field can not be obtained by the described process because the asterisks with coordinates $$$(1, 2)$$$ (second cell in the first row), $$$(3, 1)$$$ and $$$(3, 3)$$$ (leftmost and rightmost cells in the bottom) can not be parts of any ticks.

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto m = readInt!int;
	auto k = readInt!int + 1;
	auto field = ma(n, readString);
	auto maxRight = new int[][](n, m);
	auto maxLeft = new int[][](n, m);
	auto maxTick = new int[][](n, m);
	foreach(j; 0 .. m)
	{
		maxRight[0][j] = maxLeft[0][j] = field[0][j] == '*';
	}
	foreach(i; 1 .. n)
	{
		maxRight[i][0] = maxLeft[i][0] = field[i][0] == '*';
		maxRight[i][m-1] = maxLeft[i][m-1] = field[i][m-1] == '*';
		foreach(j; 1 .. m - 1)
		{
			if (field[i][j] == '*')
			{
				maxRight[i][j] = 1 + maxRight[i-1][j+1];
				maxLeft[i][j] = 1 + maxLeft[i-1][j-1];
			}
		}
	}
	foreach(i; 0 .. n)
	{
		foreach(j; 0 .. m)
		{
			maxTick[i][j] = min(maxRight[i][j], maxLeft[i][j]);
		}
	}
	debug
	{
		foreach(i; 0 .. n)
		{
			foreach(j; 0 .. m) write(maxTick[i][j], " ");
			writeln;
		}
	}
	auto covered = new bool[][](n, m);
	void coverTick(int i, int j)
	{
		foreach(k; 0 .. maxTick[i][j])
		{
			covered[i-k][j-k] = covered[i-k][j+k] = true;
		}
	}
	foreach(i; 0 .. n)
	{
		foreach(j; 0 .. m)
		{
			if (maxTick[i][j] >= k)
			{
				coverTick(i, j);
			}
		}
	}
	auto completelyCovered = true;
outer: foreach(i; 0 .. n)
		foreach(j; 0 .. m)
			if (field[i][j] == '*' && !covered[i][j])
			{
				completelyCovered = false;
				break outer;
			}
	if (completelyCovered) writeln("YES"); else writeln("NO");
}

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

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

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

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

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


Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a1, a2, ..., an, where ai denotes the distance of the i-th mark from the origin (a1 = 0, an = l).Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1 ≤ i ≤ j ≤ n), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, aj - ai = d). Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (x < y) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y. Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.

The first line contains four positive space-separated integers n, l, x, y (2 ≤ n ≤ 105, 2 ≤ l ≤ 109, 1 ≤ x < y ≤ l) — the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly. The second line contains a sequence of n integers a1, a2, ..., an (0 = a1 < a2 < ... < an = l), where ai shows the distance from the i-th mark to the origin.

In the first line print a single non-negative integer v — the minimum number of marks that you need to add on the ruler. In the second line print v space-separated integers p1, p2, ..., pv (0 ≤ pi ≤ l). Number pi means that the i-th mark should be at the distance of pi centimeters from the origin. Print the marks in any order. If there are multiple solutions, print any of them.

NoteIn the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark.In the second sample you already can use the ruler to measure the distances of 185 and 230 centimeters, so you don't have to add new marks.In the third sample the ruler only contains the initial and the final marks. We will need to add two marks to be able to test the children's skills.

#!/usr/bin/env rdmd
// Computes average line length for standard input.
import std.stdio;
import std.algorithm;
import std.container;
import std.string;
import std.math;

int a[] = new int[100001];

int find(int l, int r, int x) {
	if (l<r) {
		int m = (l+r)/2;
		if (x<a[m]) {
			return find(l,m-1,x);
		} else	if (a[m]<x) {
			return find(m+1,r,x);
		} else {
			return m;
		}
	} else {
		return (a[l]==x?l:-1);
	}
}

int addcheck(int c, int oc, int n, int l) {
	for (int k=0; k<n; k++) {
		a[n]=a[k]+c;
		if ((a[n]<0) || (a[n]>l)) {
			continue;
		}
		if ((find(0,n,a[k]+c+oc)>=0) || (find(0,n,a[k]+c-oc)>=0)) {
			return a[n];
		}
	}
	return -1;
}

void main()
{
	int n,l,x,y;
	readf("%s %s %s %s\n", &n, &l, &x, &y);

	for (int i=0; i<n; i++) {
		readf(" %s", &a[i]);
	}

	bool fx = false;
	bool fy = false;
	for (int i=0; i<n; i++) {
		if (find(0,n-1,y+a[i])>=0) {
		    fy = true;
		    break;
	    }
	}
	for (int i=0; i<n; i++) {
		if (find(0,n-1,x+a[i])>=0) {
		    fx = true;
		    break;
	    }
	}

	if (fx && fy) {
		writeln(0);
	} else if (fx || fy) {
		writeln(1);
		writeln(fx?y:x);
	} else {
		int r = -1;
		r = addcheck(x, y, n, l);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(-x, y, n, l);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(y, x, n, l);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(-y, x, n, l);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}

		writeln(2);
		writeln(x);
		writeln(y);
	}
}

#!/usr/bin/env rdmd
// Computes average line length for standard input.
import std.stdio;
import std.algorithm;
import std.container;
import std.string;
import std.math;

int a[] = new long[100000];

bool find(int l, int r, int x) {
	if (l<r) {
		int m = (l+r)/2;
		if (x<a[m]) {
			return find(l,m,x);
		} else	if (a[m]<x) {
			return find(m+1,r,x);
		} else {
			return true;
		}
	} else {
		return (a[l]==x);
	}
}

void main()
{
	int n,l,x,y;
	readf("%s %s %s %s\n", &n, &l, &x, &y);

	for (int i=0; i<n; i++) {
		readf(" %s", &a[i]);
	}

	bool fx = false;
	bool fy = false;
	for (int i=0; i<n; i++) {
		if (find(0,n-1,y+a[i])) {
		    fy = true;
		    break;
	    }
	}
	for (int i=0; i<n; i++) {
		if (find(0,n-1,x+a[i])) {
		    fx = true;
		    break;
	    }
	}

	if (fx && fy) {
		writeln(0);
	} else if (fx || fy) {
		writeln(1);
		writeln(fx?y:x);
	} else {
		for (int i=0; i<n; i++) {
			if (find(0,n-1,y-x+a[i]) && a[i]-x>0) { // find optimus
			    x = a[i] - x;
			    fx = true;
			    break;
		    }
		}
		if (fx) {
			writeln(1);
			writeln(x);
		} else {
			writeln(2);
			writeln(x);
			writeln(y);
		}
	}
}

#!/usr/bin/env rdmd
// Computes average line length for standard input.
import std.stdio;
import std.algorithm;
import std.container;
import std.string;
import std.math;

int a[] = new long[100000];

int find(int l, int r, int x) {
	if (l<r) {
		int m = (l+r)/2;
		if (x<a[m]) {
			return find(l,m,x);
		} else	if (a[m]<x) {
			return find(m+1,r,x);
		} else {
			return m;
		}
	} else {
		return (a[l]==x?l:-1);
	}
}

void main()
{
	int n,l,x,y;
	readf("%s %s %s %s\n", &n, &l, &x, &y);

	for (int i=0; i<n; i++) {
		readf(" %s", &a[i]);
	}

	bool fx = false;
	bool fy = false;
	for (int i=0; i<n; i++) {
		if (find(0,n-1,y+a[i])>0) {
		    fy = true;
		    break;
	    }
	}
	for (int i=0; i<n; i++) {
		if (find(0,n-1,x+a[i])>0) {
		    fx = true;
		    break;
	    }
	}

	if (fx && fy) {
		writeln(0);
	} else if (fx || fy) {
		writeln(1);
		writeln(fx?y:x);
	} else {
		for (int i=0; i<n; i++) {
			int r = find(0,n-1,y-x+a[i]);
			if (r>=0 && a[i]-x>=0 && a[r]-y>=0) {
			    x = a[i] - x;
			    fx = true;
			    break;
			}
		}
		if (fx) {
			writeln(1);
			writeln(x);
		} else {
			writeln(2);
			writeln(x);
			writeln(y);
		}
	}
}

#!/usr/bin/env rdmd
// Computes average line length for standard input.
import std.stdio;
import std.algorithm;
import std.container;
import std.string;
import std.math;

int a[] = new long[100001];

int find(int l, int r, int x) {
	if (l<r) {
		int m = (l+r)/2;
		if (x<a[m]) {
			return find(l,m-1,x);
		} else	if (a[m]<x) {
			return find(m+1,r,x);
		} else {
			return m;
		}
	} else {
		return (a[l]==x?l:-1);
	}
}

int addcheck(int c, int n, int l, int x, int y) {
	for (int k=0; k<n; k++) {
		bool fx = false;
		bool fy = false;
		a[n]=a[k]+c;
		if ((a[n]<0) || (a[n]>l)) {
			continue;
		}
		for (int i=0; i<=n; i++) {
			if (find(0,n,y+a[i])>=0) {
				fy = true;
				break;
			}
		}
		for (int i=0; i<=n; i++) {
			if (find(0,n,x+a[i])>=0) {
				fx = true;
				break;
			}
		}
		if (fx && fy) return a[k]+c;
	}
	return -1;
}

void main()
{
	int n,l,x,y;
	readf("%s %s %s %s\n", &n, &l, &x, &y);

	for (int i=0; i<n; i++) {
		readf(" %s", &a[i]);
	}

	bool fx = false;
	bool fy = false;
	for (int i=0; i<n; i++) {
		if (find(0,n-1,y+a[i])>=0) {
		    fy = true;
		    break;
	    }
	}
	for (int i=0; i<n; i++) {
		if (find(0,n-1,x+a[i])>=0) {
		    fx = true;
		    break;
	    }
	}

	if (fx && fy) {
		writeln(0);
	} else if (fx || fy) {
		writeln(1);
		writeln(fx?y:x);
	} else {
		int r = -1;
		r = addcheck(x, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(-x, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(y, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(-y, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}

		writeln(2);
		writeln(x);
		writeln(y);
	}
}

#!/usr/bin/env rdmd
// Computes average line length for standard input.
import std.stdio;
import std.algorithm;
import std.container;
import std.string;
import std.math;

int a[] = new long[100001];

int find(int l, int r, int x) {
	if (l<r) {
		int m = (l+r)/2;
		if (x<a[m]) {
			return find(l,m,x);
		} else	if (a[m]<x) {
			return find(m+1,r,x);
		} else {
			return m;
		}
	} else {
		return (a[l]==x?l:-1);
	}
}

int addcheck(int c, int n, int l, int x, int y) {
	for (int k=0; k<n; k++) {
		bool fx = false;
		bool fy = false;
		a[n]=a[k]+c;
		if ((a[n]<0) || (a[n]>l)) {
			continue;
		}
		for (int i=0; i<=n; i++) {
			if (find(0,n,y+a[i])>0) {
				fy = true;
				break;
			}
		}
		for (int i=0; i<=n; i++) {
			if (find(0,n,x+a[i])>0) {
				fx = true;
				break;
			}
		}
		if (fx && fy) return a[k]+c;
	}
	return -1;
}

void main()
{
	int n,l,x,y;
	readf("%s %s %s %s\n", &n, &l, &x, &y);

	for (int i=0; i<n; i++) {
		readf(" %s", &a[i]);
	}

	bool fx = false;
	bool fy = false;
	for (int i=0; i<n; i++) {
		if (find(0,n-1,y+a[i])>0) {
		    fy = true;
		    break;
	    }
	}
	for (int i=0; i<n; i++) {
		if (find(0,n-1,x+a[i])>0) {
		    fx = true;
		    break;
	    }
	}

	if (fx && fy) {
		writeln(0);
	} else if (fx || fy) {
		writeln(1);
		writeln(fx?y:x);
	} else {
		int r = -1;
		r = addcheck(x, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(-x, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(y, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(-y, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}

		writeln(2);
		writeln(x);
		writeln(y);
	}
}

#!/usr/bin/env rdmd
// Computes average line length for standard input.
import std.stdio;
import std.algorithm;
import std.container;
import std.string;
import std.math;

int a[] = new long[100001];

int find(int l, int r, int x) {
	if (l<r) {
		int m = (l+r)/2;
		if (x<a[m]) {
			return find(l,m,x);
		} else	if (a[m]<x) {
			return find(m+1,r,x);
		} else {
			return m;
		}
	} else {
		return (a[l]==x?l:-1);
	}
}

int addcheck(int c, int n, int l, int x, int y) {
	for (int k=0; k<n; k++) {
		bool fx = false;
		bool fy = false;
		a[n]=a[k]+c;
		if ((a[n]<0) || (a[n]>l)) {
			continue;
		}
		for (int i=0; i<=n; i++) {
			if (find(0,n,y+a[i])>=0) {
				fy = true;
				break;
			}
		}
		for (int i=0; i<=n; i++) {
			if (find(0,n,x+a[i])>=0) {
				fx = true;
				break;
			}
		}
		if (fx && fy) return a[k]+c;
	}
	return -1;
}

void main()
{
	int n,l,x,y;
	readf("%s %s %s %s\n", &n, &l, &x, &y);

	for (int i=0; i<n; i++) {
		readf(" %s", &a[i]);
	}

	bool fx = false;
	bool fy = false;
	for (int i=0; i<n; i++) {
		if (find(0,n-1,y+a[i])>=0) {
		    fy = true;
		    break;
	    }
	}
	for (int i=0; i<n; i++) {
		if (find(0,n-1,x+a[i])>=0) {
		    fx = true;
		    break;
	    }
	}

	if (fx && fy) {
		writeln(0);
	} else if (fx || fy) {
		writeln(1);
		writeln(fx?y:x);
	} else {
		int r = -1;
		r = addcheck(x, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(-x, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(y, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(-y, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}

		writeln(2);
		writeln(x);
		writeln(y);
	}
}

#!/usr/bin/env rdmd
// Computes average line length for standard input.
import std.stdio;
import std.algorithm;
import std.container;
import std.string;
import std.math;

int a[] = new long[100001];

int find(int l, int r, int x) {
	if (l<r) {
		int m = (l+r)/2;
		if (x<a[m]) {
			return find(l,m,x);
		} else	if (a[m]<x) {
			return find(m+1,r,x);
		} else {
			return m;
		}
	} else {
		return (a[l]==x?l:-1);
	}
}

int addcheck(int c, int n, int l, int x, int y) {
	for (int k=0; k<n; k++) {
		bool fx = false;
		bool fy = false;
		a[n]=a[k]+c;
		if ((a[n]<0) || (a[n]>l)) {
			return -1;
		}
		for (int i=0; i<=n; i++) {
			if (find(0,n,y+a[i])>0) {
				fy = true;
				break;
			}
		}
		for (int i=0; i<=n; i++) {
			if (find(0,n,x+a[i])>0) {
				fx = true;
				break;
			}
		}
		if (fx && fy) return a[k]+c;
	}
	return -1;
}

void main()
{
	int n,l,x,y;
	readf("%s %s %s %s\n", &n, &l, &x, &y);

	for (int i=0; i<n; i++) {
		readf(" %s", &a[i]);
	}

	bool fx = false;
	bool fy = false;
	for (int i=0; i<n; i++) {
		if (find(0,n-1,y+a[i])>0) {
		    fy = true;
		    break;
	    }
	}
	for (int i=0; i<n; i++) {
		if (find(0,n-1,x+a[i])>0) {
		    fx = true;
		    break;
	    }
	}

	if (fx && fy) {
		writeln(0);
	} else if (fx || fy) {
		writeln(1);
		writeln(fx?y:x);
	} else {
		int r = -1;
		r = addcheck(x, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(-x, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(y, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}
		r = addcheck(-y, n, l, x, y);
		if (r>=0) {
			writeln(1);
			writeln(r);
			return;
		}

		writeln(2);
		writeln(x);
		writeln(y);
	}
}

#!/usr/bin/env rdmd
// Computes average line length for standard input.
import std.stdio;
import std.algorithm;
import std.container;
import std.string;
import std.math;

int a[] = new long[100000];

bool find(int l, int r, int x) {
	if (l<r) {
		int m = (l+r)/2;
		if (x<a[m]) {
			return find(l,m,x);
		} else	if (a[m]<x) {
			return find(m+1,r,x);
		} else {
			return true;
		}
	} else {
		return (a[l]==x);
	}
}

void main()
{
	int n,l,x,y;
	readf("%s %s %s %s\n", &n, &l, &x, &y);

	for (int i=0; i<n; i++) {
		readf(" %s", &a[i]);
	}

	bool fx = false;
	bool fy = false;
	for (int i=0; i<n; i++) {
		if (find(0,n-1,y+a[i])) {
		    fy = true;
		    break;
	    }
	}
	for (int i=0; i<n; i++) {
		if (find(0,n-1,x+a[i])) {
		    fx = true;
		    break;
	    }
	}

	if (fx && fy) {
		writeln(0);
	} else if (fx || fy) {
		writeln(1);
		writeln(fx?y:x);
	} else {
		for (int i=0; i<n; i++) {
			if (find(0,n-1,y-x+a[i])) { // find optimus
			    x = a[i] - x;
			    fx = true;
			    break;
		    }
		}
		if (fx) {
			writeln(1);
			writeln(x);
		} else {
			writeln(2);
			writeln(x);
			writeln(y);
		}
	}
}

#!/usr/bin/env rdmd
// Computes average line length for standard input.
import std.stdio;
import std.algorithm;
import std.container;
import std.string;
import std.math;

int a[] = new long[100000];

int find(int l, int r, int x) {
	if (l<r) {
		int m = (l+r)/2;
		if (x<a[m]) {
			return find(l,m,x);
		} else	if (a[m]<x) {
			return find(m+1,r,x);
		} else {
			return m;
		}
	} else {
		return (a[l]==x?l:-1);
	}
}

void main()
{
	int n,l,x,y;
	readf("%s %s %s %s\n", &n, &l, &x, &y);

	for (int i=0; i<n; i++) {
		readf(" %s", &a[i]);
	}

	bool fx = false;
	bool fy = false;
	for (int i=0; i<n; i++) {
		if (find(0,n-1,y+a[i])>0) {
		    fy = true;
		    break;
	    }
	}
	for (int i=0; i<n; i++) {
		if (find(0,n-1,x+a[i])>0) {
		    fx = true;
		    break;
	    }
	}

	if (fx && fy) {
		writeln(0);
	} else if (fx || fy) {
		writeln(1);
		writeln(fx?y:x);
	} else {
		for (int i=0; i<n; i++) {
			int r = find(0,n-1,y-x+a[i]);
			if (r>=0 && a[i]-x>0 && a[r]-y>0) {
			    x = a[i] - x;
			    fx = true;
			    break;
			}
		}
		if (fx) {
			writeln(1);
			writeln(x);
		} else {
			writeln(2);
			writeln(x);
			writeln(y);
		}
	}
}


$$$n$$$ boys and $$$m$$$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $$$1$$$ to $$$n$$$ and all girls are numbered with integers from $$$1$$$ to $$$m$$$. For all $$$1 \leq i \leq n$$$ the minimal number of sweets, which $$$i$$$-th boy presented to some girl is equal to $$$b_i$$$ and for all $$$1 \leq j \leq m$$$ the maximal number of sweets, which $$$j$$$-th girl received from some boy is equal to $$$g_j$$$.More formally, let $$$a_{i,j}$$$ be the number of sweets which the $$$i$$$-th boy give to the $$$j$$$-th girl. Then $$$b_i$$$ is equal exactly to the minimum among values $$$a_{i,1}, a_{i,2}, \ldots, a_{i,m}$$$ and $$$g_j$$$ is equal exactly to the maximum among values $$$b_{1,j}, b_{2,j}, \ldots, b_{n,j}$$$.You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of $$$a_{i,j}$$$ for all $$$(i,j)$$$ such that $$$1 \leq i \leq n$$$ and $$$1 \leq j \leq m$$$. You are given the numbers $$$b_1, \ldots, b_n$$$ and $$$g_1, \ldots, g_m$$$, determine this number.

The first line contains two integers $$$n$$$ and $$$m$$$, separated with space — the number of boys and girls, respectively ($$$2 \leq n, m \leq 100\,000$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$, separated by spaces — $$$b_i$$$ is equal to the minimal number of sweets, which $$$i$$$-th boy presented to some girl ($$$0 \leq b_i \leq 10^8$$$). The third line contains $$$m$$$ integers $$$g_1, \ldots, g_m$$$, separated by spaces — $$$g_j$$$ is equal to the maximal number of sweets, which $$$j$$$-th girl received from some boy ($$$0 \leq g_j \leq 10^8$$$).

If the described situation is impossible, print $$$-1$$$. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied.

NoteIn the first test, the minimal total number of sweets, which boys could have presented is equal to $$$12$$$. This can be possible, for example, if the first boy presented $$$1$$$ and $$$4$$$ sweets, the second boy presented $$$3$$$ and $$$2$$$ sweets and the third boy presented $$$1$$$ and $$$1$$$ sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$12$$$.In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied.In the third test, the minimal total number of sweets, which boys could have presented is equal to $$$4$$$. This can be possible, for example, if the first boy presented $$$1$$$, $$$1$$$, $$$2$$$ sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to $$$4$$$.

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

void main()
{
    auto nm = readln.split.to!(int[]);
    auto N = nm[0];
    auto M = nm[1];
    auto BS = readln.split.to!(long[]);
    auto GS = readln.split.to!(long[]);

    long ret;
    foreach (b; BS) {
        ret += b * M;
    }
    sort!"a > b"(BS);
    int c;
    sort!"a < b"(GS);
    foreach (g; GS) {
        if (g < BS[0]) {
            writeln("-1");
            return;
        }
        if (g == BS[0]) {
            continue;
        }
        if (c == M-1) {
            ret += g - BS[1];
        } else {
            ++c;
            ret += g - BS[0];
        }
    }
    writeln(ret);
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!long;

void main() {
    GC.disable();

    long n, m;
    readf(" %s %s", n, m);

    auto b = new long[to!int(n)];
    auto g = new long[to!int(m)];

    foreach(i;0 .. n) readf(" %s", b[to!int(i)]);
    foreach(i;0 .. m) readf(" %s", g[to!int(i)]);

    long ans = -1;
    if  (b.maxElement > g.minElement) {
      ans = -1;
    } else if (g.minElement > b.maxElement) {
      sort(b);
      long tt = sum(g) + sum(b) * m - b[$-1]*(m-1) - b[$-2];
      ans = tt;
    } else {
      long ss = sum(b);
      long tt = 0;
      auto tree = new Tree(b);
      foreach(gg; g) {
        auto rr = tree.lowerBound(gg+1);
        tt = tt + (ss - rr.back() + gg);
      }

      ans = tt;

    }

    writeln(ans);

}

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

void main()
{
    auto nm = readln.split.to!(int[]);
    auto N = nm[0];
    auto M = nm[1];
    auto BS = readln.split.to!(long[]);
    auto GS = readln.split.to!(long[]);

    long ret;
    foreach (b; BS) {
        ret += b * M;
    }
    sort!"a < b"(BS);
    int[] uc;
    uc.length = N;
    foreach (g; GS) {
        if (g < BS[$-1]) {
            writeln("-1");
            return;
        }
        size_t l, r = N-1;
        while (l+1 != r) {
            auto m = (l+r)/2;
            if (BS[m] <= g) {
                l = m;
            } else {
                r = m;
            }
        }
        if (r <= g) l = r;
        if (l == g) continue;
        if (uc[l] == M-1) {
            if (l == 0) {
                writeln("-1");
                return;
            }
            --l;
        }
        ++uc[l];
        ret += g - BS[l];
    }
    writeln(ret);
}

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

void main()
{
    auto nm = readln.split.to!(int[]);
    auto N = nm[0];
    auto M = nm[1];
    auto BS = readln.split.to!(long[]);
    auto GS = readln.split.to!(long[]);

    long ret;
    foreach (b; BS) {
        ret += b * M;
    }
    sort!"a > b"(BS);
    int c;
    sort!"a < b"(GS);
    long prev = -1;
    foreach (g; GS) {
        if (g == prev) continue;
        prev = g;
        if (g < BS[0]) {
            writeln("-1");
            return;
        }
        if (g == BS[0]) {
            continue;
        }
        if (c == M-1) {
            ret += g - BS[1];
        } else {
            ++c;
            ret += g - BS[0];
        }
    }
    writeln(ret);
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

void main() {
    GC.disable();

    int n, m;
    readf(" %s %s", n, m);

    auto b = new int[n];
    auto g = new int[m];

    foreach(i;0 .. n) readf(" %s", b[i]);
    foreach(i;0 .. m) readf(" %s", g[i]);

    int ans = -1;
    if  (b.maxElement > g.minElement) {
      ans = -1;
    } else if (g.minElement > b.maxElement) {
      sort(b);
      int tt = sum(g) + sum(b) * m - b[$-1]*(m-1) - b[$-2];
      ans = tt;
    } else {
      int ss = sum(b);
      int tt = 0;
      auto tree = new Tree(b);
      foreach(gg; g) {
        auto rr = tree.lowerBound(gg+1);
        tt = tt + (ss - rr.back() + gg);
      }

      ans = tt;

    }

    writeln(ans);

}


You are given a permutation $$$a_1,a_2,\ldots,a_n$$$ of integers from $$$0$$$ to $$$n - 1$$$. Your task is to find how many permutations $$$b_1,b_2,\ldots,b_n$$$ are similar to permutation $$$a$$$. Two permutations $$$a$$$ and $$$b$$$ of size $$$n$$$ are considered similar if for all intervals $$$[l,r]$$$ ($$$1 \le l \le r \le n$$$), the following condition is satisfied: $$$$$$\operatorname{MEX}([a_l,a_{l+1},\ldots,a_r])=\operatorname{MEX}([b_l,b_{l+1},\ldots,b_r]),$$$$$$ where the $$$\operatorname{MEX}$$$ of a collection of integers $$$c_1,c_2,\ldots,c_k$$$ is defined as the smallest non-negative integer $$$x$$$ which does not occur in collection $$$c$$$. For example, $$$\operatorname{MEX}([1,2,3,4,5])=0$$$, and $$$\operatorname{MEX}([0,1,2,4,5])=3$$$.Since the total number of such permutations can be very large, you will have to print its remainder modulo $$$10^9+7$$$.In this problem, a permutation of size $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$0$$$ to $$$n-1$$$ in arbitrary order. For example, $$$[1,0,2,4,3]$$$ is a permutation, while $$$[0,1,1]$$$ is not, since $$$1$$$ appears twice in the array. $$$[0,1,3]$$$ is also not a permutation, since $$$n=3$$$ and there is a $$$3$$$ in the array.

Each test contains multiple test cases. The first line of input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of permutation $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0 \le a_i \lt n$$$) — the elements of permutation $$$a$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer, the number of permutations similar to permutation $$$a$$$, taken modulo $$$10^9+7$$$.

NoteFor the first test case, the only permutations similar to $$$a=[4,0,3,2,1]$$$ are $$$[4,0,3,2,1]$$$ and $$$[4,0,2,3,1]$$$.For the second and third test cases, the given permutations are only similar to themselves.For the fourth test case, there are $$$4$$$ permutations similar to $$$a=[1,2,4,0,5,3]$$$:   $$$[1,2,4,0,5,3]$$$;  $$$[1,2,5,0,4,3]$$$;  $$$[1,4,2,0,5,3]$$$;  $$$[1,5,2,0,4,3]$$$.

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

long mod = 1_000_000_007;

void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(x => x.to!int).array;
    auto ord = new int[N];
    foreach (i; 0 .. N) {
        ord[A[i]] = i;
    }
    long ans = 1;
    int l = ord[0], r = ord[0];
    for (int k = 1; k < N; k++) {
        int p = ord[k];
        if (l < p && p < r) {
            // k positions are already fixed
            long x = r - l + 1 - k;
            ans = ans * x % mod;
        } else {
            l = min(l, p);
            r = max(r, p);
        }
    }
    writeln(ans);
}

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