The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer x and reduce it to the number of bits set to 1 in the binary representation of x. For example for number 13 it's true that 1310 = 11012, so it has 3 bits set and 13 will be reduced to 3 in one operation.He calls a number special if the minimum number of operations to reduce it to 1 is k.He wants to find out how many special numbers exist which are not greater than n. Please help the Travelling Salesman, as he is about to reach his destination!Since the answer can be large, output it modulo 109 + 7.

The first line contains integer n (1 ≤ n < 21000). The second line contains integer k (0 ≤ k ≤ 1000). Note that n is given in its binary representation without any leading zeros.

Output a single integer — the number of special numbers not greater than n, modulo 109 + 7.

NoteIn the first sample, the three special numbers are 3, 5 and 6. They get reduced to 2 in one operation (since there are two set bits in each of 3, 5 and 6) and then to 1 in one more operation (since there is only one set bit in 2).

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

long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp;
    auto K = readln.chomp.to!int;
    auto dp = new int[](1001);
    dp[1] = 1;

    for (int i = 2; i <= 1000; ++i) {
        dp[i] = dp[i.popcnt] + 1;
    }

    auto dp2 = new long[][][](N.length+1, N.length+1, 2);
    dp2[0][0][0] = 1;

    foreach (i; 0..N.length) {
        foreach (j; 0..N.length+1) {
            foreach (k; 0..2) {
                int digit = (k || N[i] == '1') ? 2 : 1;
                foreach (d; 0..digit) {
                    if (j+d <= N.length)
                        (dp2[i+1][j+d][k||(d < N[i]-'0')] += dp2[i][j][k]) %= MOD;
                }
            }
        }
    }

    long ans = 0;
    foreach (i; 1..N.length+1) {
        if (dp[i] == K) {
            (ans += dp2[N.length][i][0]) %= MOD;
            (ans += dp2[N.length][i][1]) %= MOD;
        }
    }

    if (K == 1) {
        ans -= 1;
        ans %= MOD;
    } else if (K == 0) {
        ans = 1;
    }

    ans.writeln;
}

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

immutable int mod = 10 ^^ 9 + 7;
immutable int limit = 1003;

void add (ref int a, int b)
{
	a = (a + b) % mod;
}

void main ()
{
	auto h = new int [limit];
	h[1] = 0;
	foreach (i; 2..limit)
	{
		h[i] = h[popcnt (i)] + 1;
	}

	string s;
	while ((s = readln.strip) != "")
	{
		auto k = readln.strip.to !(int);
		if (k == 0)
		{
			writeln (1);
			continue;
		}

		auto n = s.length.to !(int);
		auto f = new int [2] [] [] (n + 1, n + 1);
		f[0][0][0] = 1;
		foreach (i; 0..n)
		{
			int lim = (s[i] == '1');
			foreach (j; 0..i + 1)
			{
				foreach (prevLess; 0..2)
				{
					foreach (cur; 0..2)
					{
						if ((cur > lim) && !prevLess)
						{
							continue;
						}
						int nextLess = prevLess ||
						    (cur < lim);
						add (f[i + 1][j + cur]
						    [nextLess], f[i][j]
						    [prevLess]);
					}
				}
			}
		}
		add (f[n][1][1], mod - 1);

		int res = 0;
		foreach (j; 1..n + 1)
		{
			if (h[j] == k - 1)
			{
				add (res, f[n][j][0]);
				add (res, f[n][j][1]);
			}
		}
		writeln (res);
	}
}

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

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

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

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

void main() {
  try {
    for (; ; ) {
      const N = readToken();
      const K = readInt();
      const L = cast(int)(N.length);

      auto numSteps = new int[L + 1];
      foreach (i; 2 .. L + 1) {
        numSteps[i] = 1 + numSteps[popcnt(i)];
      }
      debug {
        writeln("numSteps = ", numSteps);
      }

      auto dp = new Mint[][][](L + 1, 2, L + 1);
      dp[0][0][0] = 1;
      foreach (i; 0 .. L) {
        foreach (s; 0 .. 2) foreach (j; 0 .. i + 1) {
          foreach (x; 0 .. 2) {
            if (s || x <= N[i] - '0') {
              dp[i + 1][(s || x < N[i] - '0') ? 1 : 0][j + x] += dp[i][s][j];
            }
          }
        }
      }
      Mint ans;
      if (K == 0) {
        // 1 <= N
        ans += 1;
      } else {
        foreach (s; 0 .. 2) foreach (j; 1 .. L + 1) {
          if (K == 1 + numSteps[j]) {
            ans += dp[L][s][j];
          }
        }
        if (K == 1) {
          // 1 <= N
          ans -= 1;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

immutable int mod = 10 ^^ 9 + 7;
immutable int limit = 1003;

void add (ref int a, int b)
{
	a = (a + b) % mod;
}

void main ()
{
	auto h = new int [limit];
	h[1] = 0;
	foreach (i; 2..limit)
	{
		h[i] = h[popcnt (i)] + 1;
	}

	string s;
	while ((s = readln.strip) != "")
	{
		auto k = readln.strip.to !(int);
		if ((k == 0) || (s == "1"))
		{
			int res = (k == 0) && (s == "1");
			writeln (res);
			continue;
		}

		auto n = s.length.to !(int);
		auto f = new int [2] [] [] (n + 1, n + 1);
		f[0][0][0] = 1;
		foreach (i; 0..n)
		{
			int lim = (s[i] == '1');
			foreach (j; 0..i + 1)
			{
				foreach (prevLess; 0..2)
				{
					foreach (cur; 0..2)
					{
						if ((cur > lim) && !prevLess)
						{
							continue;
						}
						int nextLess = prevLess ||
						    (cur < lim);
						add (f[i + 1][j + cur]
						    [nextLess], f[i][j]
						    [prevLess]);
					}
				}
			}
		}
		add (f[n][1][0], mod - 1);

		int res = 0;
		foreach (j; 1..n + 1)
		{
			if (h[j] == k - 1)
			{
				add (res, f[n][j][0]);
				add (res, f[n][j][1]);
			}
		}
		writeln (res);
	}
}

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

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

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

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

struct ModInt(int M_) {
  import std.conv : to;
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op: "-")() const { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const {
    return mixin("ModInt(this) " ~ op ~ "= a");
  }
  ModInt opBinaryRight(string op)(long a) const {
    return mixin("ModInt(a) " ~ op ~ "= this");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

enum MO = 10^^9 + 7;
alias Mint = ModInt!MO;

void main() {
  try {
    for (; ; ) {
      const N = readToken();
      const K = readInt();
      const L = cast(int)(N.length);

      auto numSteps = new int[L + 1];
      foreach (i; 2 .. L + 1) {
        numSteps[i] = 1 + numSteps[popcnt(i)];
      }
      debug {
        writeln("numSteps = ", numSteps);
      }

      auto dp = new Mint[][][](L + 1, 2, L + 1);
      dp[0][0][0] = 1;
      foreach (i; 0 .. L) {
        foreach (s; 0 .. 2) foreach (j; 0 .. i + 1) {
          foreach (x; 0 .. 2) {
            if (s || x <= N[i] - '0') {
              dp[i + 1][(s || x < N[i] - '0') ? 1 : 0][j + x] += dp[i][s][j];
            }
          }
        }
      }
      Mint ans;
      if (K == 0) {
        // 1 <= N
        ans = 1;
      } else {
        foreach (s; 0 .. 2) foreach (j; 1 .. L + 1) {
          if (K == 1 + numSteps[j]) {
            ans += dp[L][s][j];
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.He has suggestions to work on n distinct projects. Mikhail has already evaluated that the participation in the i-th project will increase his experience by ai per day and bring bi dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time.Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true.For example, suppose Mikhail is suggested to work on three projects and a1 = 6, b1 = 2, a2 = 1, b2 = 3, a3 = 2, b3 = 6. Also, p = 20 and q = 20. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, a1·2.5 + a2·0 + a3·2.5 = 6·2.5 + 1·0 + 2·2.5 = 20 and b1·2.5 + b2·0 + b3·2.5 = 2·2.5 + 3·0 + 6·2.5 = 20.

The first line of the input contains three integers n, p and q (1 ≤ n ≤ 100 000, 1 ≤ p, q ≤ 1 000 000) — the number of projects and the required number of experience and money. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 1 000 000) — the daily increase in experience and daily income for working on the i-th project.

Print a real value — the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteFirst sample corresponds to the example in the problem statement.

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;

real vp (real x0, real y0, real x1, real y1, real x2, real y2)
{
	return (x2 - x0) * (y1 - y0) - (x1 - x0) * (y2 - y0);
}

void main ()
{
	int n;
	real p, q;
	while (readf (" %s %s %s", &n, &p, &q) > 0)
	{
		alias Point = Tuple !(real, q{x}, real, q{y});
		auto a = new Point [n];
		foreach (ref z; a)
		{
			readf (" %s %s", &z.x, &z.y);
		}
		sort !((a, b) => (vp (0, 0, a.x, a.y, b.x, b.y) < 0) ||
		    (vp (0, 0, a.x, a.y, b.x, b.y) == 0 &&
		    hypot (a.y, a.x) < hypot (b.y, b.x))) (a);
		a = a.uniq.array;
/*
		Point [] c;
		foreach (ref z; a)
		{
			if (!c.empty &&
			    (vp (0, 0, z.x, z.y, c[0].x, c[0].y) == 0 &&
			    hypot (z.y, z.x) >= hypot (c[0].y, c[0].x)))
			{
				c.popBack ();
				c.assumeSafeAppend ();
			}
			c ~= z;
		}
		debug {writeln (c);}
		a = c;
*/
                n = a.length;
		Point [] b;
		foreach (i; 0..n)
		{
			while (b.length >= 2 &&
			    vp (b[$ - 2].x, b[$ - 2].y,
			    b[$ - 1].x, b[$ - 1].y, a[i].x, a[i].y) > 0)
			{
				b.popBack ();
				b.assumeSafeAppend ();
			}
			b ~= a[i];
		}
		debug {writeln (b);}

		real res = 1E100;
		foreach (i; 0..b.length)
		{
			res = min (res, max (p / b[i].x, q / b[i].y));
			if (i > 0 && vp (0, 0, b[i - 1].x, b[i - 1].y, p, q) *
			    vp (0, 0, b[i].x, b[i].y, p, q) < 0)
			{
				real lo = 0;
				real hi = 1;
				foreach (j; 0..100)
				{
					real me = (lo + hi) * 0.5;
					real ppart1 = me * p;
					real ppart2 = p - ppart1;
					real t1 = ppart1 / b[i - 1].x;
					real t2 = ppart2 / b[i].x;
					real qpart1 = t1 * b[i - 1].y;
					real qpart2 = t2 * b[i].y;
					if (q < qpart1 + qpart2)
					{
						lo = me;
					}
					else
					{
						hi = me;
					}
				}
				debug {writeln (lo);}
				real ppart1 = lo * p;
				real ppart2 = p - ppart1;
				real t1 = ppart1 / b[i - 1].x;
				real t2 = ppart2 / b[i].x;
				res = min (res, t1 + t2);
			}
		}

		writefln ("%.10f", res);
	}
}


Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≤ li ≤ ri ≤ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 ≤ xi ≤ yi ≤ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array.Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.

The first line contains integers n, m, k (1 ≤ n, m, k ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105) — the initial array. Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 ≤ li ≤ ri ≤ n), (0 ≤ di ≤ 105). Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 ≤ xi ≤ yi ≤ m). The numbers in the lines are separated by single spaces.

On a single line print n integers a1, a2, ..., an — the array after executing all the queries. Separate the printed numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.

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

void main(){
    int n,m,k;
    readf!"%d %d %d"(n,m,k);
    readln;
    long[] a=readln.splitter.map!(to!long).array;
    //if(n==40) writeln(a);
    Tuple!(int,int,ulong)[] q;
    int l,r;
    ulong v;
    foreach(i;0..m){
        readf!"%d %d %d"(l,r,v);
        readln;
        q~=tuple(l,r,v);
    }
    long[] dk=new long[m];
    foreach(i;0..k){
        readf!"%d %d"(l,r);
        readln;
        dk[l-1]++;
        if(r<m) dk[r]--;
    }
    foreach(i;1..m)
        dk[i]+=dk[i-1];
    long[] d=new long[n];
    foreach(i;0..m){
        v=(cast(ulong)dk[i])*q[i][2];//:q[i][2];
        d[q[i][0]-1]+=v;
        if(q[i][1]<n) d[q[i][1]]-=v;
    }
    a[0]+=d[0];
    foreach(i;1..n){
        d[i]+=d[i-1];
        a[i]+=d[i];
    }
    writefln!"%(%d %)"(a);
}

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

void main ()
{
	int n, m, k;
	while (readf (" %s %s %s", &n, &m, &k) > 0)
	{
		auto a = new long [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		auto l = new int [m];
		auto r = new int [m];
		auto d = new long [m];
		foreach (j; 0..m)
		{
			readf (" %s %s %s", &l[j], &r[j], &d[j]);
			l[j]--;
			r[j]--;
		}
		auto x = new int [k];
		auto y = new int [k];
		foreach (p; 0..k)
		{
			readf (" %s %s", &x[p], &y[p]);
			x[p]--;
			y[p]--;
		}
		auto v = new long [m + 1];
		foreach (p; 0..k)
		{
			v[x[p]]++;
			v[y[p] + 1]--;
		}
		foreach (j; 0..m)
		{
			v[j + 1] += v[j];
		}
		auto t = new long [n + 1];
		foreach (j; 0..m)
		{
			t[l[j]] += v[j] * d[j];
			t[r[j] + 1] -= v[j] * d[j];
		}
		foreach (i; 0..n)
		{
			t[i + 1] += t[i];
		}
		foreach (i; 0..n)
		{
			a[i] += t[i];
		}
		writefln ("%(%s %)", a);
	}
}

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

immutable int mod = 10^^9 + 7;

void main() {
    int n, m, k;
    readVars(n, m, k);

    auto a = readln.split.to!(long[]);

    auto l = new int[](m);
    auto r = new int[](m);
    auto d = new int[](m);

    foreach (i ; 0 .. m) {
        readVars(l[i], r[i], d[i]);
        l[i]--;
    }

    auto ims = new int[](m + 1);
    int xi, yi;

    foreach (i ; 0 .. k) {
        readVars(xi, yi);
        ims[xi - 1]++;
        ims[yi]--;
    }

    iota(m).each!(i => ims[i + 1] += ims[i]);

    auto dif = new long[](n + 1);

    foreach (i ; 0 .. m) {
        dif[l[i]] += d[i].to!long * ims[i];
        dif[r[i]] -= d[i].to!long * ims[i];
    }

    iota(n).each!(i => dif[i + 1] += dif[i]);

    debug {
        stderr.writeln("ims:", ims);
        stderr.writeln("dif:", dif);
    }

    a[] += dif[0 .. $ - 1];

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

int dfs(int n, int[][] child, int u) {
    if (child[u].empty) {
        return 0;
    }

    int res;

    foreach(v ; child[u]) {
        res = max(res, dfs(n, child, v));
    }

    return res + 1;
}

void readVars(T...)(auto ref T args)
{
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

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

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

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

    struct op { int le, r, d; }
    op[] ops;
    foreach (_; 0 .. m) {
        int le, r, d;
        readf("%s %s %s", &le, &r, &d);
        readln;
        --le, --r;

        ops ~= op(le, r, d);
    }

    debug { ops.writeln; }

    auto opscnt = new int[] (m+1);
    foreach (_; 0 .. k) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;
        --x, --y;

        opscnt[x] += 1;
        opscnt[y+1] -= 1;
    }

    auto addcnt = new long[] (n+1);
    foreach (i; 0 .. m) {
        if (i > 0) opscnt[i] += opscnt[i-1];
        auto val = cast(long)ops[i].d * opscnt[i];
        addcnt[ops[i].le] += val;
        addcnt[ops[i].r+1] -= val;
    }

    foreach (i; 0 .. n) {
        if (i > 0) addcnt[i] += addcnt[i-1];
        arr[i] += addcnt[i];
    }

    arr.writefln!("%(%s %)");
}

module sigod.codeforces.p296C;

import std.stdio;

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

	long[] a = new long[n + 2];
	foreach (i; 1 .. n + 1) {
		stdin.readf(" %s", &a[i]);
	}

	int[] l = new int[m + 1];
	int[] r = new int[m + 1];
	long[] d = new long[m + 2];

	foreach (i; 1 .. m + 1) {
		stdin.readf(" %s %s %s", &l[i], &r[i], &d[i]);
	}

	// process requests

	int[] multipl = new int[m + 2];

	foreach (i; 0 .. k) {
		int x, y;
		stdin.readf(" %s %s", &x, &y);

		++multipl[x];
		--multipl[y + 1];
	}

	foreach (i; 1 .. m + 1) {
		multipl[i] += multipl[i - 1];

		d[i] *= multipl[i];
	}

	// process operations

	long[] sum = new long[n + 2];

	foreach (i; 1 .. m + 1) {
		sum[l[i]] += d[i];
		sum[r[i] + 1] -= d[i];
	}

	foreach (i; 1 .. n + 1) {
		sum[i] += sum[i - 1];

		a[i] += sum[i];
	}

	// output

	foreach (i; 1 .. n + 1) {
		stdout.write(a[i], " ");
	}
}

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

void main(){
    int n,m,k;
    readf!"%d %d %d"(n,m,k);
    readln;
    ulong[] a=readln.splitter.map!(to!ulong).array;
    Tuple!(int,int,long)[] q;
    int l,r;
    long v;
    foreach(i;0..m){
        readf!"%d %d %d"(l,r,v);
        readln;
        q~=tuple(l,r,v);
    }
    long[] dk=new long[m];
    while(k--){
        readf!"%d %d"(l,r);
        readln;
        dk[l-1]++;
        if(r<m) dk[r]--;
    }
    foreach(i;1..m)
        dk[i]+=dk[i-1];
    long[] d=new long[n];
    foreach(i;0..m){
        ulong val=dk[i]?dk[i]*q[i][2]:q[i][2];
        d[q[i][0]-1]+=val;
        if(q[i][1]<n) d[q[i][1]]-=val;
    }
    a[0]+=d[0];
    foreach(i;1..n){
        d[i]+=d[i-1];
        a[i]+=d[i];
    }
    writefln!"%(%d %)"(a);
}

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

void main(){
    int n,m,k;
    readf!"%d %d %d"(n,m,k);
    readln;
    ulong[] a=readln.splitter.map!(to!ulong).array;
    Tuple!(int,int,ulong)[] q;
    int l,r;
    ulong v;
    foreach(i;0..m){
        readf!"%d %d %d"(l,r,v);
        readln;
        q~=tuple(l,r,v);
    }
    long[] dk=new long[m];
    while(k--){
        readf!"%d %d"(l,r);
        readln;
        dk[l-1]++;
        if(r<m) dk[r]--;
    }
    foreach(i;1..m)
        dk[i]+=dk[i-1];
    long[] d=new long[n];
    foreach(i;0..m){
        v=dk[i]?(cast(ulong)dk[i])*q[i][2]:q[i][2];
        d[q[i][0]-1]+=v;
        if(q[i][1]<n) d[q[i][1]]-=v;
    }
    a[0]+=d[0];
    foreach(i;1..n){
        d[i]+=d[i-1];
        a[i]+=d[i];
    }
    writefln!"%(%d %)"(a);
}

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

void main(){
    int n,m,k;
    readf!"%d %d %d"(n,m,k);
    readln;
    ulong[] a=readln.splitter.map!(to!ulong).array;
    Tuple!(int,int,int)[] q;
    int l,r,v;
    foreach(i;0..m){
        readf!"%d %d %d"(l,r,v);
        readln;
        q~=tuple(l,r,v);
    }
    long[] dk=new long[m];
    while(k--){
        readf!"%d %d"(l,r);
        readln;
        dk[l-1]++;
        if(r<m) dk[r]--;
    }
    foreach(i;1..m)
        dk[i]+=dk[i-1];
    long[] d=new long[n];
    foreach(i;0..m){
        long val=dk[i]?dk[i]*q[i][2]:q[i][2];
        d[q[i][0]-1]+=val;
        if(q[i][1]<n) d[q[i][1]]-=val;
    }
    a[0]+=d[0];
    foreach(i;1..n){
        d[i]+=d[i-1];
        a[i]+=d[i];
    }
    writefln!"%(%d %)"(a);
}

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

immutable int mod = 10^^9 + 7;

void main() {
    int n, m, k;
    readVars(n, m, k);

    auto a = readln.split.to!(long[]);

    auto l = new int[](m);
    auto r = new int[](m);
    auto d = new int[](m);

    foreach (i ; 0 .. m) {
        readVars(l[i], r[i], d[i]);
        l[i]--;
    }

    auto ims = new int[](m + 1);
    int xi, yi;

    foreach (i ; 0 .. k) {
        readVars(xi, yi);
        ims[xi - 1]++;
        ims[yi]--;
    }

    iota(m).each!(i => ims[i + 1] += ims[i]);

    auto dif = new long[](n + 1);

    foreach (i ; 0 .. m) {
        dif[l[i]] += d[i] * ims[i];
        dif[r[i]] -= d[i] * ims[i];
    }

    iota(n).each!(i => dif[i + 1] += dif[i]);

    debug {
        stderr.writeln("ims:", ims);
        stderr.writeln("dif:", dif);
    }

    a[] += dif[0 .. $ - 1];

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

int dfs(int n, int[][] child, int u) {
    if (child[u].empty) {
        return 0;
    }

    int res;

    foreach(v ; child[u]) {
        res = max(res, dfs(n, child, v));
    }

    return res + 1;
}

void readVars(T...)(auto ref T args)
{
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

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

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

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

    struct op { int le, r, d; }
    op[] ops;
    foreach (_; 0 .. m) {
        int le, r, d;
        readf("%s %s %s", &le, &r, &d);
        readln;
        --le, --r;

        ops ~= op(le, r, d);
    }

    debug { ops.writeln; }

    auto opscnt = new int[] (m+1);
    foreach (_; 0 .. k) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;
        --x, --y;

        opscnt[x] += 1;
        opscnt[y+1] -= 1;
    }

    auto addcnt = new long[] (n+1);
    foreach (i; 0 .. m) {
        if (i > 0) opscnt[i] += opscnt[i-1];
        addcnt[ops[i].le] += ops[i].d * opscnt[i];
        addcnt[ops[i].r+1] -= ops[i].d * opscnt[i];
    }

    foreach (i; 0 .. n) {
        if (i > 0) addcnt[i] += addcnt[i-1];
        arr[i] += addcnt[i];
    }

    arr.writefln!("%(%s %)");
}

module sigod.codeforces.p296C;

import std.stdio;

struct FenwickTree
{
	private {
		int _size;
		long[] _array;
	}

	this(int size)
	{
		this._size = size;
		this._array = new long[size];
	}

	this(long[] array)
	{
		//this._size = array.length;
		//this._array = array.dup;

		this(array.length);

		for (int i = 0; i < this._size; ++i) {
			this.inc(i, array[i]);
		}
	}

	void inc(int i, long delta)
	{
		for (; i < this._size; i = (i | (i + 1))) {
			this._array[i] += delta;
		}
	}

	long sum(int r)
	{
		long result = 0;

		for (; r >= 0; r = (r & (r + 1)) - 1) {
			result += this._array[r];
		}

		return result;
	}

	long sum(int l, int r)
	{
		return sum(r) - sum(l);
	}

	long[] toArray()
	{
		long[] result = new long[this._size];

		foreach (i; 0 .. this._size) {
			result[i] = this.sum(i);
		}

		for (int i = this._size - 1; i > 0; --i) {
			result[i] -= result[i - 1];
		}

		return result;
	}
}

void main()
{
	int array_size = read_value!int();
	int operations_count = read_value!int();
	int requests_count = read_value!int();

	long[] array = read_array!long(array_size);

	int[] left_operations = new int[operations_count];
	int[] right_operations = new int[operations_count];
	int[] delta = new int[operations_count];

	foreach (i; 0 .. operations_count) {
		left_operations[i] = read_value!int() - 1;
		right_operations[i] = read_value!int() - 1;
		delta[i] = read_value!int();
	}

	int[] x = new int[requests_count];
	int[] y = new int[requests_count];

	foreach (i; 0 .. requests_count) {
		x[i] = read_value!int() - 1;
		y[i] = read_value!int() - 1;
	}

	FenwickTree array_tree = FenwickTree(array);
	FenwickTree operations_tree = FenwickTree(operations_count);

	foreach (i; 0 .. requests_count) {
		foreach (j; x[i] .. y[i] + 1) {
			operations_tree.inc(j, 1);
		}
	}

	stdout.writeln("operations_counts: ", operations_tree.toArray());

	stdout.writeln("array: ", array_tree.toArray());

	foreach (index, count; operations_tree.toArray()) {
		if (count == 0) continue;

		foreach (i; left_operations[index] .. right_operations[index] + 1) {
			array_tree.inc(i, delta[index] * count);
		}

		stdout.writeln("left: ", left_operations[index], "; right: ", right_operations[index]);
		stdout.writeln("delta: ", delta[index], "; count: ", count);
		stdout.writeln("array: ", array_tree.toArray());
	}

	foreach (element; array_tree.toArray()) {
		stdout.write(element, " ");
	}
}

private
T read_value(T)()
{
	T value;
	stdin.readf(" %s", &value);

	return value;
}

private
T[] read_array(T)(int size)
{
	T[] array = new T[size];

	foreach (ref element; array) {
		stdin.readf(" %s", &element);
	}

	return array;
}

module sigod.codeforces.p296C;

import std.stdio;

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

	long[] a = new long[n + 2];
	foreach (i; 1 .. n + 1) {
		stdin.readf(" %s", &a[i]);
	}

	int[] l = new int[m + 1];
	int[] r = new int[m + 1];
	int[] d = new int[m + 2];

	foreach (i; 1 .. m + 1) {
		stdin.readf(" %s %s %s", &l[i], &r[i], &d[i]);
	}

	// process requests

	int[] multipl = new int[m + 2];

	foreach (i; 0 .. k) {
		int x, y;
		stdin.readf(" %s %s", &x, &y);

		++multipl[x];
		--multipl[y + 1];
	}

	foreach (i; 1 .. m + 2) {
		multipl[i] += multipl[i - 1];

		d[i] *= multipl[i];
	}

	// process operations

	long[] sum = new long[n + 2];

	foreach (i; 1 .. m + 1) {
		sum[l[i]] += d[i];
		sum[r[i] + 1] -= d[i];
	}

	foreach (i; 1 .. n + 1) {
		sum[i] += sum[i - 1];

		a[i] += sum[i];
	}

	// output

	foreach (i; 1 .. n + 1) {
		stdout.write(a[i], " ");
	}
}

private
T max(T)(T a, T b)
{
	if (a > b) return a;
	else return b;
}


Alice got an array of length $$$n$$$ as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.Bob has chosen $$$m$$$ changes of the following form. For some integer numbers $$$x$$$ and $$$d$$$, he chooses an arbitrary position $$$i$$$ ($$$1 \le i \le n$$$) and for every $$$j \in [1, n]$$$ adds $$$x + d \cdot dist(i, j)$$$ to the value of the $$$j$$$-th cell. $$$dist(i, j)$$$ is the distance between positions $$$i$$$ and $$$j$$$ (i.e. $$$dist(i, j) = |i - j|$$$, where $$$|x|$$$ is an absolute value of $$$x$$$).For example, if Alice currently has an array $$$[2, 1, 2, 2]$$$ and Bob chooses position $$$3$$$ for $$$x = -1$$$ and $$$d = 2$$$ then the array will become $$$[2 - 1 + 2 \cdot 2,~1 - 1 + 2 \cdot 1,~2 - 1 + 2 \cdot 0,~2 - 1 + 2 \cdot 1]$$$ = $$$[5, 2, 1, 3]$$$. Note that Bob can't choose position $$$i$$$ outside of the array (that is, smaller than $$$1$$$ or greater than $$$n$$$).Alice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric.What is the maximum arithmetic mean value Bob can achieve?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of elements of the array and the number of changes. Each of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$d_i$$$ ($$$-10^3 \le x_i, d_i \le 10^3$$$) — the parameters for the $$$i$$$-th change.

Print the maximal average arithmetic mean of the elements Bob can achieve. Your answer is considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.

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

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

    auto totx = 0, posd = 0, negd = 0;
    while (m--) {
        int x, d;
        readf("%s %s", &x, &d);
        readln;

        totx += x;
        if (d > 0) posd += d;
        else negd += d;
    }

    debug { writeln(totx, ' ', negd, ' ', posd); }

    auto bigd = (cast(long)n).iota.sum;
    auto smalld = n % 2 == 1 ? 2L * (cast(long)n/2 + 1).iota.sum
        : (cast(long)n/2 + 1).iota.sum + (cast(long)n/2).iota.sum;

    debug { writeln(smalld, ' ', bigd); }

    auto ans = totx + cast(double)(posd * bigd + negd * smalld) / n;

    ans.writefln!("%.18f");
}

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

  int n, m; rd(n, m);
  long sum=0;
  while(m--){
    long x, d; rd(x, d);
    sum+=x*n;
    if(d>0){// 0+d+d*2+...+d*(n-1)
      sum+=d*n*(n-1)/2;
    }else{
      auto k=n/2;
      sum+=d*k*(k+1)/2*2;
      if(n%2==0) sum-=d*k;
    }
  }

  writefln("%.18f", 1.0*sum/n);
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

/*

  0 0
  -1 2
  -1 2
  -2 -3

  0 0 0
  0 2 4
  5 7 9

*/

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

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

    auto totx = 0, posd = 0, negd = 0;
    while (m--) {
        int x, d;
        readf("%s %s", &x, &d);
        readln;

        totx += x;
        if (d > 0) posd += d;
        else negd += d;
    }

    debug { writeln(totx, ' ', negd, ' ', posd); }

    auto bigd = (cast(long)n).iota.sum;
    auto smalld = n % 2 == 1 ? 2L * (cast(long)n/2 + 1).iota.sum : (cast(long)n/2 + 1).iota.sum + (cast(long)n/2).iota.sum;

    debug { writeln(smalld, ' ', bigd); }

    auto ans = totx + cast(double)(posd * bigd + negd * smalld) / n;

    ans.writeln;
}


Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He was so sad that he punched some kind of scoreboard with numbers. The numbers are displayed in the same way as on an electronic clock: each digit position consists of $$$7$$$ segments, which can be turned on or off to display different numbers. The picture shows how all $$$10$$$ decimal digits are displayed:   After the punch, some segments stopped working, that is, some segments might stop glowing if they glowed earlier. But Denis remembered how many sticks were glowing and how many are glowing now. Denis broke exactly $$$k$$$ segments and he knows which sticks are working now. Denis came up with the question: what is the maximum possible number that can appear on the board if you turn on exactly $$$k$$$ sticks (which are off now)? It is allowed that the number includes leading zeros.

The first line contains integer $$$n$$$ $$$(1 \leq n \leq 2000)$$$  — the number of digits on scoreboard and $$$k$$$ $$$(0 \leq k \leq 2000)$$$  — the number of segments that stopped working. The next $$$n$$$ lines contain one binary string of length $$$7$$$, the $$$i$$$-th of which encodes the $$$i$$$-th digit of the scoreboard. Each digit on the scoreboard consists of $$$7$$$ segments. We number them, as in the picture below, and let the $$$i$$$-th place of the binary string be $$$0$$$ if the $$$i$$$-th stick is not glowing and $$$1$$$ if it is glowing. Then a binary string of length $$$7$$$ will specify which segments are glowing now.    Thus, the sequences "1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011" encode in sequence all digits from $$$0$$$ to $$$9$$$ inclusive.

Output a single number consisting of $$$n$$$ digits  — the maximum number that can be obtained if you turn on exactly $$$k$$$ sticks or $$$-1$$$, if it is impossible to turn on exactly $$$k$$$ sticks so that a correct number appears on the scoreboard digits.

NoteIn the first test, we are obliged to include all $$$7$$$ sticks and get one $$$8$$$ digit on the scoreboard.In the second test, we have sticks turned on so that units are formed. For $$$5$$$ of additionally included sticks, you can get the numbers $$$07$$$, $$$18$$$, $$$34$$$, $$$43$$$, $$$70$$$, $$$79$$$, $$$81$$$ and $$$97$$$, of which we choose the maximum  — $$$97$$$.In the third test, it is impossible to turn on exactly $$$5$$$ sticks so that a sequence of numbers appears on the scoreboard.

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

immutable int[][] digits = [
  [1,2,3,5,6,7],
  [3,6],
  [1,3,4,5,7],
  [1,3,4,6,7],
  [2,3,4,6],
  [1,2,4,6,7],
  [1,2,4,5,6,7],
  [1,3,6],
  [1,2,3,4,5,6,7],
  [1,2,3,4,6,7]
];

int cvt (in int[] a) {
  return a.map!(i => 1 << (i - 1)).sum;
}

immutable int[] mask = digits.map!(cvt).array.idup;

final class Solve {
  immutable int n, maxk;
  immutable int[] c;
  BitArray dp;
  int[] pc;
  bool f (int i, int t) {
    int idx = (i * (maxk + 1) + t) * 2;
    if (dp[idx]) return dp[idx+1];
    dp[idx] = true;
    if (i == n) {
      if (t == 0) {
        dp[idx+1] = true;
        return true;
      }
      return false;
    }
    const int ci = c[i];
    foreach_reverse (j; mask) {
      const int w = ci & j;
      if (w != ci) continue;
      const int bits = pc[j ^ ci];
      if (bits > t) continue;
      if (f (i + 1, t - bits)) {
        dp[idx+1] = true;
        return true;
      }
    }
    return false;
  }
  void restore () {
    int i, t = maxk;
    while (i < n) {
      const int ci = c[i];
      foreach_reverse (pos, j; mask) {
        const int w = ci & j;
        if (w != ci) continue;
        const int bits = pc[j ^ ci];
        if (bits > t) continue;
        if (f (i + 1, t - bits)) {
          write(pos);
          t -= bits;
          break;
        }
      }
      ++i;
    }
  }
  this (int n, int maxk, int[] c) {
    this.n = n;
    this.maxk = maxk;
    this.c = c.idup;
    dp.length = 2 * (n + 1) * (maxk + 1);
    pc = new int[128];
    foreach (i; 1 .. 128) {
      pc[i] = pc[i & (i - 1)] + 1;
    }
  }
}

void main() {
  auto s = readln;
  int n, k;
  formattedRead(s, " %d %d", n, k);
  auto c = new int[n];
  foreach (i; 0 .. n) {
    auto t = readln;
    foreach (j; 0 .. 7) if (t[j] == '1') {
      c[i] += 1 << j;
    }
  }
  auto solve = new Solve (n, k, c);
  if (solve.f (0, k)) {
    solve.restore ();
    writeln;
  } else {
    writeln (-1);
  }

}

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

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

    int[] arr;
    foreach (_; 0 .. n) {
        string s = readln.chomp;
        arr ~= to!int(s, 2);
    }

    int[] nums;
    nums ~= to!int("1110111", 2);
    nums ~= to!int("0010010", 2);
    nums ~= to!int("1011101", 2);
    nums ~= to!int("1011011", 2);
    nums ~= to!int("0111010", 2);
    nums ~= to!int("1101011", 2);
    nums ~= to!int("1101111", 2);
    nums ~= to!int("1010010", 2);
    nums ~= to!int("1111111", 2);
    nums ~= to!int("1111011", 2);

    auto best = new Tuple!(int, int)[][] (1 << 7);
    foreach (x; 0 .. (1 << 7)) {
        outer: foreach (val, target; nums.enumerate(0)) {
            int need = 0;
            foreach (bit; 0 .. 8) {
                int xb = x & (1 << bit);
                int tb = target & (1 << bit);
                if (tb < xb) { continue outer; }
                if (tb > xb) { ++need; }
            }
            best[x] ~= tuple(val, need);
        }
    }

    auto dp = new int[][] (n+1, k+1);
    foreach (i; 0 .. n+1) { dp[i][] = -2; }

    int go(int pos, int left) {
        if (pos == n) { return left == 0 ? 0 : -1; }
        if (dp[pos][left] > -2) { return dp[pos][left]; }

        foreach (i, pr; best[arr[pos]]) {
            auto target = pr[0], need = pr[1];
            if (need > left) { continue; }

            auto rest = go(pos+1, left - need);
            if (rest >= 0) { dp[pos][left] = i.to!int; }
        }

        if (dp[pos][left] == -2) { dp[pos][left] = -1; }

        return dp[pos][left];
    }

    auto score = go(0, k);

    if (score < 0) {
        writeln(-1);
        return;
    }

    int[] ans;
    int left = k;
    foreach (i; 0 .. n) {
       auto pr = best[arr[i]][dp[i][left]];
       ans ~= pr[0];
       left -= pr[1];
    }

    ans.map!(to!string).join.writeln;
}

import core.bitop;
import std.algorithm;
import std.stdio;

immutable int digits = 10;
int [digits] digit;

void prepare ()
{
	digit[0] = 0b1110111;
	digit[1] = 0b0010010;
	digit[2] = 0b1011101;
	digit[3] = 0b1011011;
	digit[4] = 0b0111010;
	digit[5] = 0b1101011;
	digit[6] = 0b1101111;
	digit[7] = 0b1010010;
	digit[8] = 0b1111111;
	digit[9] = 0b1111011;
}

void main ()
{
	prepare ();

	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		auto a = new int [n];
		foreach (ref c; a)
		{
			readf !(" %b") (c);
		}
		auto f = new byte [] [] (n + 1, k + 10);
		foreach (ref g; f)
		{
			g[] = -1;
		}
		f[n][0] = digits;
		foreach_reverse (i; 0..n)
		{
			foreach (d, v; digit)
			{
				if ((a[i] | v) != v)
				{
					continue;
				}
				auto add = popcnt (a[i] ^ v);
				foreach (j; add..k + 1)
				{
					if (f[i + 1][j - add] >= 0)
					{
						f[i][j] = cast (byte)
						    ((add << 4) | d);
					}
				}
	        	}
		}

		if (f[0][k] >= 0)
		{
			foreach (i; 0..n)
			{
				write (f[i][k] & 15);
				k -= f[i][k] >> 4;
			}
			writeln;
		}
		else
		{
			writeln (-1);
		}
	}
}

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

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

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

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

enum A = 10;
enum DIGITS = ["1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"];

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      auto S = new string[N];
      foreach (i; 0 .. N) {
        S[i] = readToken();
      }

      auto dks = new int[][](N, A);
      foreach (i; 0 .. N) {
        foreach (a; 0 .. A) {
          foreach (pos; 0 .. 7) {
            if (S[i][pos] > DIGITS[a][pos]) {
              dks[i][a] += K + 1;
            } else if (S[i][pos] < DIGITS[a][pos]) {
              dks[i][a] += 1;
            }
          }
        }
      }
      auto dp = new bool[][](N + 1, K + 1);
      dp[N][0] = true;
      foreach_reverse (i; 0 .. N) {
        foreach (a; 0 .. A) {
          const dk = dks[i][a];
          foreach (k; dk .. K + 1) {
            if (dp[i + 1][k - dk]) {
              dp[i][k] = true;
            }
          }
        }
      }

      if (dp[0][K]) {
        string ans;
        int k = K;
        foreach (i; 0 .. N) {
          foreach_reverse (a; 0 .. A) {
            if (k >= dks[i][a] && dp[i + 1][k - dks[i][a]]) {
              ans ~= cast(char)('0' + a);
              k -= dks[i][a];
              goto found;
            }
          }
          assert(false);
         found:
        }
        writeln(ans);
      } else {
        writeln(-1);
      }
    }
  } 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)); }

enum A = 10;
enum DIGITS = ["1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"];

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      auto S = new string[N];
      foreach (i; 0 .. N) {
        S[i] = readToken();
      }

      auto dks = new int[][](N, A);
      foreach (i; 0 .. N) {
        foreach (a; 0 .. A) {
          foreach (pos; 0 .. 7) {
            if (DIGITS[a][pos] != S[i][pos]) {
              ++dks[i][a];
            }
          }
        }
      }
      auto dp = new bool[][](N + 1, K + 1);
      dp[N][0] = true;
      foreach_reverse (i; 0 .. N) {
        foreach (a; 0 .. A) {
          const dk = dks[i][a];
          foreach (k; dk .. K + 1) {
            if (dp[i + 1][k - dk]) {
              dp[i][k] = true;
            }
          }
        }
      }

      if (dp[0][K]) {
        string ans;
        int k = K;
        foreach (i; 0 .. N) {
          foreach_reverse (a; 0 .. A) {
            if (k >= dks[i][a] && dp[i + 1][k - dks[i][a]]) {
              ans ~= cast(char)('0' + a);
              k -= dks[i][a];
              goto found;
            }
          }
          assert(false);
         found:
        }
        writeln(ans);
      } else {
        writeln(-1);
      }
    }
  } catch (EOFException e) {
  }
}


In the Bus of Characters there are $$$n$$$ rows of seat, each having $$$2$$$ seats. The width of both seats in the $$$i$$$-th row is $$$w_i$$$ centimeters. All integers $$$w_i$$$ are distinct.Initially the bus is empty. On each of $$$2n$$$ stops one passenger enters the bus. There are two types of passengers:   an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it;  an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it. You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of rows in the bus. The second line contains the sequence of integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^{9}$$$), where $$$w_i$$$ is the width of each of the seats in the $$$i$$$-th row. It is guaranteed that all $$$w_i$$$ are distinct. The third line contains a string of length $$$2n$$$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $$$j$$$-th character is '0', then the passenger that enters the bus on the $$$j$$$-th stop is an introvert. If the $$$j$$$-th character is '1', the the passenger that enters the bus on the $$$j$$$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $$$n$$$), and for each extrovert there always is a suitable row.

Print $$$2n$$$ integers — the rows the passengers will take. The order of passengers should be the same as in input.

NoteIn the first example the first passenger (introvert) chooses the row $$$2$$$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $$$1$$$, because it is the only empty row now. The third passenger (extrovert) chooses the row $$$1$$$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $$$2$$$, because it is the only row with an empty place.

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

void main() {
    auto N = readln.chomp.to!int;
    auto W = readln.split.map!(to!int).array;
    auto A = N.iota.map!(i => tuple(W[i], i+1)).array;
    auto P = readln.chomp.map!(a => a == '1').array;
    auto ans = new int[](2*N);
    A.sort();
    auto stack = new int[](N);
    int a = 0, sp = -1;

    foreach (i; 0..2*N) {
        if (P[i]) {
            ans[i] = stack[sp];
            sp--;
        } else {
            ans[i] = A[a][1];
            sp++;
            stack[sp] = A[a][1];
            a++;
        }
    }

    ans.map!(to!string).join(" ").writeln;
}


Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.Omkar currently has $$$n$$$ supports arranged in a line, the $$$i$$$-th of which has height $$$a_i$$$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $$$1$$$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $$$1$$$ to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!An array $$$b$$$ is a subsegment of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.An array $$$b_1, b_2, \dots, b_n$$$ is called nondecreasing if $$$b_i\le b_{i+1}$$$ for every $$$i$$$ from $$$1$$$ to $$$n-1$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of supports Omkar has. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(0 \leq a_{i} \leq 10^9)$$$ — the heights of the supports. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.

NoteThe subarray with which Omkar performs the operation is bolded.In the first test case:First operation:$$$[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$$$Second operation:$$$[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$$$Third operation:$$$[5, \textbf{4}, \textbf{4}, 5] \to [5, \textbf{5}, \textbf{5}, 5]$$$In the third test case, the array is already nondecreasing, so Omkar does $$$0$$$ operations.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		long res = 0;
		foreach (i; 1..n)
		{
			res += max (0, a[i - 1] - a[i]);
		}
		writeln (res);
	}
}

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

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

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

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

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

        long ans;
        foreach (i; 0 .. N - 1) {
          ans += max(A[i] - A[i + 1], 0);
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n;
  @Dim("n") long[] a;

  void solve(long tc = -1)
  {
    a ~= long.max;
    long ops = 0;
    foreach_reverse(i; 0 .. cast(size_t)n)
      {
        if (a[i] > a[i + 1])
          {
            ops += a[i] - a[i + 1];
          }
      }
    writeln(ops);
  }
}

struct Interval
{
  long l, h;

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 0..n-1)
		{
			auto x = a[i] - a[i+1];
			if (x > 0)
			{
				ans[ti] += x;
			}
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 0..n-1)
		{
			auto x = a[i] - a[i+1];
			if (x > 0)
			{
				ans[ti] += x;
			}
		}
	}

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


Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.

The first line contains two integer numbers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105) — the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0 ≤ ci ≤ 109) — the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≤ xi, yi ≤ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.

Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.

NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.

#!/usr/bin/env dub
/+ dub.sdl:
    name "C"
+/

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

void main()
{
    int N, M;
    readf(" %s %s ", N, M);

    long[] C = new long[N];
    foreach (i; 0..N) {
        readf(" %s ", C[i]);
    }

    int[][] adj = new int[][N];
    foreach (i; 0..M) {
        int x, y;
        readf(" %s %s ", x, y);
        x--;
        y--;

        adj[x] ~= y;
        adj[y] ~= x;
    }

    debug(2) { writeln(adj);}

    int[] comps = replicate([-1], N);
    int ncomps = 0;

    foreach (v; 0..N) {
        if (comps[v] == -1) {
            auto bfs = DList!int(v);
            comps[v] = ncomps;

            while (!bfs.empty) {
                auto cur = bfs.front();
                bfs.removeFront();

                foreach (nbr; adj[cur]) {
                    if (comps[nbr] == -1) {
                        bfs.insertBack(nbr);
                        comps[nbr] = ncomps;
                    }
                }
            }

            ncomps++;
        }
    }

    long[] mins = replicate([long.max], ncomps);

    foreach (v; 0..N) {
        mins[comps[v]] = min(mins[comps[v]], C[v]);
    }

    long ans = sum(mins);
    writeln(ans);
}

#!/usr/bin/env dub
/+ dub.sdl:
    name "C"
+/

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

class Graph {
    int N;
    int[][] adj;

    private int[] comps;
    private int ncomps;

    bool flag_connected_components = false;

    this(int N) {
        this.N = N;
        adj = new int[][N];
    }

    void addEdge(int u, int v) {
        adj[u] ~= v;
        adj[v] ~= u;
    }

    void do_connected_components() {
        comps = replicate([-1], N);

        foreach (v; 0..N) {
            if (comps[v] == -1) {
                auto bfs = DList!int(v);
                comps[v] = ncomps;

                while (!bfs.empty) {
                    auto cur = bfs.front();
                    bfs.removeFront();

                    foreach (nbr; adj[cur]) {
                        if (comps[nbr] == -1) {
                            bfs.insertBack(nbr);
                            comps[nbr] = ncomps;
                        }
                    }
                }

                ncomps++;
            }
        }

        debug {
            flag_connected_components = true;
        }
    }

    int component(int v) {
        debug {
            assert(flag_connected_components);
        }
        return comps[v];
    }

}

void main()
{
    int N, M;
    readf(" %s %s ", N, M);

    long[] C = new long[N];
    foreach (i; 0..N) {
        readf(" %s ", C[i]);
    }

    Graph G = new Graph(N);
    foreach (i; 0..M) {
        int x, y;
        readf(" %s %s ", x, y);
        x--;
        y--;

        G.addEdge(x, y);
    }
    G.do_connected_components();

    long[] mins = replicate([long.max], G.ncomps);

    foreach (v; 0..N) {
        mins[G.component(v)] =
            min(mins[G.component(v)], C[v]);
    }

    long ans = sum(mins);
    writeln(ans);
}

// https://codeforces.com/problemset/problem/893/C
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;
import std.range.primitives;

int[][] graph;
int[] visited;
long[] c;

long dfs(int u) {
    visited[u] = 1;
    long minima = c[u];
    for(int i = 0; i < graph[u].length; i++) {
        int v = graph[u][i];
        if(visited[v] == 0) {
            minima = min(minima,dfs(v));
        }
    }
    return minima;
}

void main() {
    int n, m;
    readf("%s %s\n", &n, &m);
    c = readln.split.map!(to!long).array;
    // TODO how to initialize this?
    visited = new int[n];
    foreach(_; 0..n) {
        int[] vertex;
        graph ~= vertex;
    }
    foreach(_; 0..m) {
        int x,y;
        readf("%s %s\n", &x, &y);
        x -= 1;
        y -= 1;
        graph[x] ~= y;
        graph[y] ~= x;
    }
    long[] cost;
    foreach(vertex; 0..n) {
        if(visited[vertex] == 0) {
            cost ~= dfs(vertex);
        }
    }
    long total;
    foreach(item; cost)
        total += item;
    total.writeln;
}

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

immutable inf = 10^^9 + 7;

void main() {
    int n, m;
    scan(n, m);
    auto c = readln.split.to!(int[]);

    auto uf = UnionFind(n);

    foreach (i ; 0 .. m) {
        int xi, yi;
        scan(xi, yi);
        xi--, yi--;
        uf.unite(xi, yi);
    }

    auto d = new int[](n);
    d[] = inf;

    foreach (i ; 0 .. n) {
        int r = uf.find_root(i);
        d[r] = min(d[r], c[i]);
    }

    long ans;

    foreach (i ; 0 .. n) {
        if (d[i] < inf) ans += d[i];
    }

    writeln(ans);
}

struct UnionFind {
    private {
        int N;
        int[] p;
        int[] rank;
    }

    this (int n) {
        N = n;
        p = iota(N).array;
        rank = new int[](N);
    }

    int find_root(int x) {
        if (p[x] != x) {
            p[x] = find_root(p[x]);
        }

        return p[x];
    }

    bool same(int x, int y) {
        return find_root(x) == find_root(y);
    }

    void unite(int x, int y) {
        int u = find_root(x), v = find_root(y);

        if (u == v) return;

        if (rank[u] < rank[v]) {
            p[u] = v;
        }
        else {
            p[v] = u;

            if (rank[u] == rank[v]) {
                rank[u]++;
            }
        }
    }
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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

struct Queue(T) {
    private {
        int N, head, tail;
        T[] data;
    }

    this(int n) {
        N = n + 1;
        data = new T[](N);
    }

    bool empty() {
        return head == tail;
    }

    bool full() {
        return (tail + 1) % N == head;
    }

    T front() {
        return data[head];
    }

    void push(T x) {
        assert(!full);
        data[tail++] = x;
        tail %= N;
    }

    void pop() {
        assert(!empty);
        head = (head + 1) % N;
    }

    void clear() {
        head = tail = 0;
    }
}

// https://codeforces.com/problemset/problem/893/C
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;
import std.range.primitives;

int[][] graph;
int[] visited;
int[] c;

int dfs(int u) {
    visited[u] = 1;
    int minima = c[u];
    for(int i = 0; i < graph[u].length; i++) {
        int v = graph[u][i];
        minima = min(minima, c[v]);
        if(visited[v] == 0) {
            dfs(v);
        }
    }
    return minima;
}

void main() {
    int n, m;
    readf("%s %s\n", &n, &m);
    c = readln.split.map!(to!int).array;
    // TODO how to initialize this?
    visited = new int[n];
    foreach(_; 0..n) {
        int[] vertex;
        graph ~= vertex;
    }
    foreach(_; 0..m) {
        int x,y;
        readf("%s %s\n", &x, &y);
        x -= 1;
        y -= 1;
        graph[x] ~= y;
        graph[y] ~= x;
    }
    int[] cost;
    foreach(vertex; 0..n) {
        if(visited[vertex] == 0) {
            cost ~= dfs(vertex);
        }
    }
    sum(cost).writeln;
}

// https://codeforces.com/problemset/problem/893/C
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;
import std.range.primitives;

int[][] graph;
int[] visited;
long[] c;

long dfs(int u) {
    visited[u] = 1;
    long minima = c[u];
    for(int i = 0; i < graph[u].length; i++) {
        int v = graph[u][i];
        minima = min(minima, c[v]);
        if(visited[v] == 0) {
            dfs(v);
        }
    }
    return minima;
}

void main() {
    int n, m;
    readf("%s %s\n", &n, &m);
    c = readln.split.map!(to!long).array;
    // TODO how to initialize this?
    visited = new int[n];
    foreach(_; 0..n) {
        int[] vertex;
        graph ~= vertex;
    }
    foreach(_; 0..m) {
        int x,y;
        readf("%s %s\n", &x, &y);
        x -= 1;
        y -= 1;
        graph[x] ~= y;
        graph[y] ~= x;
    }
    long[] cost;
    foreach(vertex; 0..n) {
        if(visited[vertex] == 0) {
            cost ~= dfs(vertex);
        }
    }
    long total;
    foreach(item; cost)
        total += item;
    total.writeln;
}


You have an axis-aligned rectangle room with width $$$W$$$ and height $$$H$$$, so the lower left corner is in point $$$(0, 0)$$$ and the upper right corner is in $$$(W, H)$$$.There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in $$$(x_1, y_1)$$$, and the upper right corner in $$$(x_2, y_2)$$$.You want to place another rectangular table in this room with width $$$w$$$ and height $$$h$$$ with the width of the table parallel to the width of the room.The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).You can't rotate any of the tables, but you can move the first table inside the room.   Example of how you may move the first table. What is the minimum distance you should move the first table to free enough space for the second one?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of the test cases. The first line of each test case contains two integers $$$W$$$ and $$$H$$$ ($$$1 \le W, H \le 10^8$$$) — the width and the height of the room. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$0 \le x_1 < x_2 \le W$$$; $$$0 \le y_1 < y_2 \le H$$$) — the coordinates of the corners of the first table. The third line contains two integers $$$w$$$ and $$$h$$$ ($$$1 \le w \le W$$$; $$$1 \le h \le H$$$) — the width and the height of the second table.

For each test case, print the minimum distance you should move the first table, or $$$-1$$$ if there is no way to free enough space for the second table. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.

NoteThe configuration of the first test case is shown in the picture. But the movement of the first table is not optimal. One of the optimal movement, for example, is to move the table by $$$(0, -1)$$$, so the lower left corner will move from $$$(2, 1)$$$ to $$$(2, 0)$$$. Then you can place the second table at $$$(0, 3)-(4, 5)$$$.In the second test case, there is no way to fit both tables in the room without intersecting.In the third test case, you can move the first table by $$$(0, 2)$$$, so the lower left corner will move from $$$(0, 3)$$$ to $$$(0, 5)$$$.

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

void theCode(){
    ll W = scan; ll H = scan;
    ll x1 = scan; ll y1 = scan;
    ll x2 = scan; ll y2 = scan;
    ll w = scan; ll h = scan;
    // Height
    ll wdis = max(W - x2, x1);
    ll hdis = max(H - y2, y1);
    ll wdiff = max(w - wdis, 0);
    ll hdiff = max(h - hdis, 0);
    /* show(wdis, hdis); */
    /* show(wdiff, hdiff); */
    ll nx, ny;
    bool f = 1;
    if(W - x2 > x1){
        nx = x1 - wdiff;
        if(nx < 0){
            f = 0;
        }
    }else{
        nx = x1 + wdiff;
        if(x2 + wdiff > W){
            f = 0;
        }
    }
    bool f2 = 1;
    if(H - y2 > y1){
        ny = y1 - hdiff;
        if(ny < 0){
            if(!f){
                writeln(-1);
                return;
            }else{
                f2 = 0;
            }
        }
    }else{
        ny = y1 + hdiff;
        if(y2 + hdiff > H){
            if(!f){
                writeln(-1);
                return;
            }else{
                f2 = 0;
            }
        }
    }
    show(nx, ny);
    ll dist = -1;
    if(f && f2){
        dist = min(abs(nx - x1), abs(ny - y1));
    }else if(f2){
        dist = abs(ny - y1);
    }else if(f){
        dist = abs(nx - x1);
    }
    if(dist == -1){
        writeln(dist);
        return;
    }
    double dis = dist.to!double;
    writefln("%.10f", dis);
}

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

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

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

void main()
{
	int t = readInt!int; while (t--) solve;
}

void solve()
{
	long w = readInt!long;
	long h = readInt!long;
	long[2] xb, yb;
	long x1 = readInt!long;
	long y1 = readInt!long;
	long x2 = readInt!long;
	long y2 = readInt!long;
	xb = [x1, x2];
	yb = [y1, y2];
	long rw = readInt!long;
	long rh = readInt!long;
	long wb = x2 - x1;
	long hb = y2 - y1;
	long minDist = long.max;
	void tryPoint(long x, long y)
	{
		if (rw <= x || rh <= y) { minDist = 0; return; }
		if (rw > x)
		{
			long hx = rw;
			if (hx + wb <= w)
			{
				minDist = min(minDist, rw - x);
			}
		}
		if (rh > y)
		{
			long hy = rh;
			if (hy + hb <= h)
			{
				minDist = min(minDist, rh - y);
			}
		}
	}
	tryPoint(xb[0], yb[0]);
	tryPoint(xb[0], h - yb[1]);
	tryPoint(w - xb[1], yb[0]);
	tryPoint(w - xb[1], h - yb[1]);
	if (minDist != long.max) minDist.writeln; else (-1).writeln;
}
/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

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

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

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

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

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

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

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

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int W, H;
    readf!" %d %d "(W, H);
    int x1, y1, x2, y2;
    readf!" %d %d %d %d "(x1, y1, x2, y2);

    int X1 = max(x1, W - x2);
    int Y1 = max(y1, H - y2);

    int w, h;
    readf!" %d %d "(w, h);

    int movex, movey;
    if (w > X1) {
      movex = w - X1;
      if (w + abs(x2 - x1) > W)
        movex = int.max;
    }
    if (h > Y1) {
      movey = h - Y1;
      if (h + abs(y2 - y1) > H)
        movey = int.max;
    }

    int ans = min(movex, movey);
    if (ans == int.max) {
      writeln(-1);
    } else {
      writefln("%.9f", cast(double)ans);
    }
  }
}

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

void theCode(){
    ll W = scan; ll H = scan;
    ll x1 = scan; ll y1 = scan;
    ll x2 = scan; ll y2 = scan;
    ll w = scan; ll h = scan;
    // Height
    ll wdis = max(W - x2, x1);
    ll hdis = max(H - y2, y1);
    ll wdiff = max(w - wdis, 0);
    ll hdiff = max(h - hdis, 0);
    /* show(wdis, hdis); */
    /* show(wdiff, hdiff); */
    ll nx, ny;
    bool f = 1;
    if(W - x2 > x1){
        nx = x1 - wdiff;
        if(x1 < 0){
            f = 0;
        }
    }else{
        nx = x1 + wdiff;
        if(x2 + wdiff > W){
            f = 0;
        }
    }
    bool f2 = 1;
    if(H - y2 > y1){
        ny = y1 - hdiff;
        if(y1 < 0){
            if(!f){
                writeln(-1);
                return;
            }else{
                f2 = 0;
            }
        }
    }else{
        ny = y1 + hdiff;
        if(y2 + hdiff > H){
            if(!f){
                writeln(-1);
                return;
            }else{
                f2 = 0;
            }
        }
    }
    show(nx, ny);
    ll dist = -1;
    if(f && f2){
        dist = min(abs(nx - x1), abs(ny - y1));
    }else if(f2){
        dist = abs(ny - y1);
    }else if(f){
        dist = abs(nx - x1);
    }
    if(dist == -1){
        writeln(dist);
        return;
    }
    double dis = dist.to!double;
    writefln("%.10f", dis);
}

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

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

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

void theCode(){
    ll W = scan; ll H = scan;
    ll x1 = scan; ll y1 = scan;
    ll x2 = scan; ll y2 = scan;
    ll w = scan; ll h = scan;
    // Height
    ll wdis = max(W - x2, x1);
    ll hdis = max(H - y2, y1);
    ll wdiff = max(w - wdis, 0);
    ll hdiff = max(h - hdis, 0);
    /* show(wdis, hdis); */
    /* show(wdiff, hdiff); */
    ll nx, ny;
    bool f = 1;
    if(W - x2 > x1){
        nx = x1 - wdiff;
        if(x1 < 0){
            f = 0;
        }
    }else{
        nx = x1 + wdiff;
        if(x2 + wdiff > W){
            f = 0;
        }
    }
    bool f2 = 1;
    if(H - y2 > y1){
        ny = y1 - hdiff;
        if(y1 < 0){
            if(!f){
                writeln(-1);
                return;
            }else{
                f2 = 0;
            }
        }
    }else{
        ny = y1 + hdiff;
        if(y2 + hdiff > H){
            if(!f){
                writeln(-1);
                return;
            }else{
                f2 = 0;
            }
        }
    }
    show(nx, ny);
    ll dist = -1;
    if(f && f2){
        dist = min(abs(nx - x1), abs(ny - y1));
    }else if(f2){
        dist = abs(ny - y1);
    }else if(f){
        dist = abs(nx - x1);
    }
    double dis = dist.to!double;
    writefln("%.10f", dis);
}

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

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

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

void theCode(){
    ll W = scan; ll H = scan;
    ll x1 = scan; ll y1 = scan;
    ll x2 = scan; ll y2 = scan;
    ll w = scan; ll h = scan;
    // Height
    ll wdis = max(W - x2, x1);
    ll hdis = max(H - y2, y1);
    ll wdiff = max(w - wdis, 0);
    ll hdiff = max(h - hdis, 0);
    show(wdis, hdis);
    show(wdiff, hdiff);
    ll nx, ny;
    bool f = 1;
    if(W - x2 > x1){
        nx = x1 - wdiff;
        if(x1 < 0){
            f = 0;
        }
    }else{
        nx = x1 + wdiff;
        if(x2 + wdiff > W){
            f = 0;
        }
    }
    bool f2 = 1;
    if(H - y2 > y1){
        ny = y1 - hdiff;
        if(y1 < 0){
            if(!f){
                writeln(-1);
                return;
            }else{
                f2 = 0;
            }
        }
    }else{
        ny = y1 + hdiff;
        if(y2 + hdiff > H && !f){
            if(!f){
                writeln(-1);
                return;
            }else{
                f2 = 0;
            }
        }
    }
    ll dist = -1;
    if(f && f2){
        dist = min(abs(nx - x1), abs(ny - y1));
    }else if(f2){
        dist = abs(ny - y1);
    }else if(f){
        dist = abs(nx - x1);
    }
    double dis = dist.to!double;
    writefln("%.8f", dis);
}

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

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


Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $$$k$$$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.Now each knight ponders: how many coins he can have if only he kills other knights?You should answer this question for each knight.

The first line contains two integers $$$n$$$ and $$$k$$$ $$$(1 \le n \le 10^5, 0 \le k \le \min(n-1,10))$$$ — the number of knights and the number $$$k$$$ from the statement. The second line contains $$$n$$$ integers $$$p_1, p_2 ,\ldots,p_n$$$ $$$(1 \le p_i \le 10^9)$$$ — powers of the knights. All $$$p_i$$$ are distinct. The third line contains $$$n$$$ integers $$$c_1, c_2 ,\ldots,c_n$$$ $$$(0 \le c_i \le 10^9)$$$ — the number of coins each knight has.

Print $$$n$$$ integers — the maximum number of coins each knight can have it only he kills other knights.

NoteConsider the first example.   The first knight is the weakest, so he can't kill anyone. That leaves him with the only coin he initially has.  The second knight can kill the first knight and add his coin to his own two.  The third knight is the strongest, but he can't kill more than $$$k = 2$$$ other knights. It is optimal to kill the second and the fourth knights: $$$2+11+33 = 46$$$.  The fourth knight should kill the first and the second knights: $$$33+1+2 = 36$$$. In the second example the first knight can't kill anyone, while all the others should kill the one with the index less by one than their own.In the third example there is only one knight, so he can't kill anyone.

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

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

    auto p = readln.chomp.split.map!(to!int).array;
    auto c = readln.chomp.split.map!(to!int).array;

    auto idx = n.iota.array;
    makeIndex(p, idx);

    debug { idx.writeln; }

    auto ans = new long[] (n);

    auto mxs = make!(RedBlackTree!(int, "a < b", true));
    long sum = 0L;
    foreach (i; idx) {
        ans[i] = sum + c[i];

        sum += c[i];
        mxs.insert(c[i]);

        if (mxs.length > k) {
            sum -= mxs.front;
            mxs.removeFront();
        }

        debug { mxs.writeln; }
    }

    ans.writefln!("%(%s %)");
}

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

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

    auto p = readln.chomp.split.map!(to!int).array;
    auto c = readln.chomp.split.map!(to!int).array;

    auto idx = n.iota.array;
    makeIndex(p, idx);

    debug { idx.writeln; }

    auto ans = new long[] (n);

    auto mxs = make!(RedBlackTree!int);
    long sum = 0L;
    foreach (i; idx) {
        ans[i] = sum + c[i];

        sum += c[i];
        mxs.insert(c[i]);

        if (mxs.length > k) {
            sum -= mxs.front;
            mxs.removeFront();
        }

        debug { mxs.writeln; }
    }

    ans.writefln!("%(%s %)");
}