There is an infinite set generated as follows:  $$$1$$$ is in this set.  If $$$x$$$ is in this set, $$$x \cdot a$$$ and $$$x+b$$$ both are in this set. For example, when $$$a=3$$$ and $$$b=6$$$, the five smallest elements of the set are:  $$$1$$$,  $$$3$$$ ($$$1$$$ is in this set, so $$$1\cdot a=3$$$ is in this set),  $$$7$$$ ($$$1$$$ is in this set, so $$$1+b=7$$$ is in this set),  $$$9$$$ ($$$3$$$ is in this set, so $$$3\cdot a=9$$$ is in this set),  $$$13$$$ ($$$7$$$ is in this set, so $$$7+b=13$$$ is in this set). Given positive integers $$$a$$$, $$$b$$$, $$$n$$$, determine if $$$n$$$ is in this set.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 10^5$$$) — the number of test cases. The description of the test cases follows. The only line describing each test case contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$1\leq n,a,b\leq 10^9$$$) separated by a single space.

For each test case, print "Yes" if $$$n$$$ is in this set, and "No" otherwise. You can print each letter in any case.

NoteIn the first test case, $$$24$$$ is generated as follows:  $$$1$$$ is in this set, so $$$3$$$ and $$$6$$$ are in this set;  $$$3$$$ is in this set, so $$$9$$$ and $$$8$$$ are in this set;  $$$8$$$ is in this set, so $$$24$$$ and $$$13$$$ are in this set. Thus we can see $$$24$$$ is in this set.The five smallest elements of the set in the second test case is described in statements. We can see that $$$10$$$ isn't among them.

// Vicfred
// https://codeforces.com/contest/1542/problem/B
// math, greedy
import std.container;
import std.stdio;

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

while(t--) {
    long n, a, b;
    readf("%s %s %s\n", &n, &a, &b);
    if(a == 1L) {
        if((n - 1L) % b == 0L)
            "Yes".writeln;
        else
            "No".writeln;
        continue;
    }
    auto powers = new RedBlackTree!(long,"a > b");
    powers.insert(1L);
    while(powers.front <= n) {
        powers.insert(powers.front * a);
    }
    if(powers.front > n)
        powers.removeFront;
    n = n % b;
    bool found = false;
    while(!powers.empty) {
        if(powers.front % b == n)
            found = true;
        powers.removeFront;
    }
    if(found)
        "Yes".writeln;
    else
        "No".writeln;
}
}

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;

ulong a, b;

bool is_good(ulong n)
{
  ulong val = 1;
  while (true) {
    if (val > n)
      return false;
    if ((n - val) % b == 0)
      return true;
    val *= a;
  }
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    ulong n;
    readf!" %d %d %d "(n, a, b);

    if (a == 1) {
      if ((n - 1) % b == 0)
        writeln("Yes");
      else
        writeln("No");
      continue;
    }

    if (is_good(n))
      writeln("Yes");
    else
      writeln("No");
  }
}

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  immutable(long) mod = 10 ^^ 9 + 7;
  while(tests--) {
    long n, a, b;
    readf!"%s %s %s\n"(n, a, b);
    if (a == 1) {
      if ((n - 1) % b == 0) {
        "Yes".writeln;
      }
      else {
        "No".writeln;
      }
    }
    else {
      bool flag = false;
      for (int i = 0; (a ^^ i) <= n; ++i) {
        if ((n - (a ^^ i)) % b == 0) {
          "Yes".writeln;
          flag = true;
          break;
        }
      }
      if (!flag) "No".writeln;
    }
  }

} // main

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

string FMT_F = "%.10f";

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

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

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

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

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

		long x = 1;
		if (a == 1)
		{
			auto rem = n - x;
			ans[ti] = rem % b == 0;
		}
		else
		{
			while (x <= n)
			{
				if ((n-x) % b == 0)
				{
					ans[ti] = true;
					break;
				}
				x *= a;
			}
		}
	}

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

// Vicfred
// https://codeforces.com/contest/1542/problem/B
// math, greedy
import std.container;
import std.stdio;

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

while(t--) {
    long n, a, b;
    readf("%s %s %s\n", &n, &a, &b);
    if(a == 1) {
        if((n - 1) % b == 0)
            "Yes".writeln;
        else
            "No".writeln;
        continue;
    }
    auto powers = new RedBlackTree!(long,"a > b");
    powers.insert(1L);
    while(powers.front < n) {
        powers.insert(powers.front * a);
    }
    if(powers.front >= n)
        powers.removeFront;
    n = n % b;
    bool found = false;
    while(!powers.empty) {
        if(powers.front % b == n)
            found = true;
        powers.removeFront;
    }
    if(found)
        "Yes".writeln;
    else
        "No".writeln;
}
}

// Vicfred
// https://codeforces.com/contest/1542/problem/B
// math, greedy
import std.container;
import std.stdio;

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

while(t--) {
    long n, a, b;
    readf("%s %s %s\n", &n, &a, &b);
    if(a == 1) {
        if((n - 1) % b == 0)
            "Yes".writeln;
        else
            "No".writeln;
        continue;
    }
    auto powers = new RedBlackTree!(long,"a > b");
    powers.insert(1L);
    while(powers.front < n) {
        powers.insert(powers.front * a);
    }
    powers.removeFront;
    n = n % b;
    bool found = false;
    while(!powers.empty) {
        if(powers.front % b == n)
            found = true;
        powers.removeFront;
    }
    if(found)
        "Yes".writeln;
    else
        "No".writeln;
}
}

// Vicfred
// https://codeforces.com/contest/1542/problem/B
// math, greedy
import std.container;
import std.stdio;

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

while(t--) {
    long n, a, b;
    readf("%s %s %s\n", &n, &a, &b);
    if(a == 1) {
        if((n - 1) % b == 0)
            "Yes".writeln;
        else
            "No".writeln;
        continue;
    }
    auto powers = new RedBlackTree!(long,"a > b");
    powers.insert(1L);
    while(powers.front <= n) {
        powers.insert(powers.front * a);
    }
    n = n % b;
    bool found = false;
    while(!powers.empty) {
        if(powers.front % b == n)
            found = true;
        powers.removeFront;
    }
    if(found)
        "Yes".writeln;
    else
        "No".writeln;
}
}

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;

ulong a, b;

bool is_good(ulong n)
{
  ulong val = 1;
  while (true) {
    if (val > n)
      return false;
    if ((n - val) % b == 0)
      return true;
    val *= a;
  }
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    ulong n;
    readf!" %d %d %d "(n, a, b);

    if (a == 1) {
      if (n % b == 1)
        writeln("Yes");
      else
        writeln("No");
      continue;
    }

    if (is_good(n))
      writeln("Yes");
    else
      writeln("No");
  }
}

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;

long a, b;

bool is_good(long n)
{
  long x = 0;

  long val = 1;
  while (true) {
    if (val > n)
      return false;
    if ((n - val) % b == 0)
      return true;
    val *= a;
  }
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d %d %d "(n, a, b);

    if (a == 1) {
      if (n % b == 1)
        writeln("Yes");
      else
        writeln("No");
      continue;
    }

    if (is_good(n))
      writeln("Yes");
    else
      writeln("No");
  }
}

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;

long a, b;

bool is_good(long n)
{
  long x = 0;

  long val = 1;
  while (true) {
    val *= a;
    if (val > n)
      return false;
    if ((n - val) % b == 0)
      return true;
  }
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d %d %d "(n, a, b);

    if (a == 1) {
      if (n % b == 1)
        writeln("Yes");
      else
        writeln("No");
      continue;
    }

    if (is_good(n))
      writeln("Yes");
    else
      writeln("No");
  }
}

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  immutable(long) mod = 10 ^^ 9 + 7;
  while(tests--) {
    long n, a, b;
    readf!"%s %s %s\n"(n, a, b);
    if (a == 1) {
      if ((n - 1) % b == 0) {
        "Yes".writeln;
      }
      else {
        "No".writeln;
      }
    }
    else {
      bool flag = false;
      for (int i = 0; (a ^^ i) <= n; ++i) {
        if ((n - (a ^^ i)) % b == 0) {
          "Yes".writeln;
          flag = true;
        }
      }
      if (!flag) "No".writeln;
    }
  }

} // main


Zane the wizard is going to perform a magic show shuffling the cups.There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.The problematic bone is initially at the position x = 1. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions x = ui and x = vi. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at x = 4 and the one at x = 6, they will not be at the position x = 5 at any moment during the operation.  Zane’s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.

The first line contains three integers n, m, and k (2 ≤ n ≤ 106, 1 ≤ m ≤ n, 1 ≤ k ≤ 3·105) — the number of cups, the number of holes on the table, and the number of swapping operations, respectively. The second line contains m distinct integers h1, h2, ..., hm (1 ≤ hi ≤ n) — the positions along the x-axis where there is a hole on the table. Each of the next k lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the positions of the cups to be swapped.

Print one integer — the final position along the x-axis of the bone.

NoteIn the first sample, after the operations, the bone becomes at x = 2, x = 5, x = 7, and x = 1, respectively.In the second sample, after the first operation, the bone becomes at x = 2, and falls into the hole onto the ground.

// Codeforces My Practice
// author: Leonardone @ NEETSDKASU
import std.stdio;

void main() {
    int n, m, k;
    readf("%d %d %d ", &n, &m, &k);
    bool[1_000_001] h;
    for (int i = 0; i < m; i++) {
        int hi;
        readf("%d ", &hi);
        h[hi] = true;
    }
    if (h[1]) {
        writeln(1);
        return;
    }
    int ans = 1;
    for (int i = 0; i < k; i++) {
        int u, v;
        readf("%d %d ", &u, &v);
        if (u == ans) {
            ans = v;
            if (h[ans]) {
                break;
            }
        } else if (v == ans) {
            ans = u;
            if (h[ans]) {
                break;
            }
        }
    }
    writeln(ans);
}


You are given an array of $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$.You have to create an array of $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$ such that:   The array $$$b$$$ is a rearrangement of the array $$$a$$$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets $$$\{a_1,a_2,\dots,a_n\}$$$ and $$$\{b_1,b_2,\dots,b_n\}$$$ are equal.For example, if $$$a=[1,-1,0,1]$$$, then $$$b=[-1,1,1,0]$$$ and $$$b=[0,1,-1,1]$$$ are rearrangements of $$$a$$$, but $$$b=[1,-1,-1,0]$$$ and $$$b=[1,0,2,-3]$$$ are not rearrangements of $$$a$$$.  For all $$$k=1,2,\dots,n$$$ the sum of the first $$$k$$$ elements of $$$b$$$ is nonzero. Formally, for all $$$k=1,2,\dots,n$$$, it must hold $$$$$$b_1+b_2+\cdots+b_k\not=0\,.$$$$$$ If an array $$$b_1,b_2,\dots, b_n$$$ with the required properties does not exist, you have to print NO.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t \le 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each testcase contains one integer $$$n$$$ ($$$1\le n\le 50$$$)  — the length of the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\dots, a_n$$$ ($$$-50\le a_i\le 50$$$)  — the elements of $$$a$$$.

For each testcase, if there is not an array $$$b_1,b_2,\dots,b_n$$$ with the required properties, print a single line with the word NO. Otherwise print a line with the word YES, followed by a line with the $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$.  If there is more than one array $$$b_1,b_2,\dots,b_n$$$ satisfying the required properties, you can print any of them.

NoteExplanation of the first testcase: An array with the desired properties is $$$b=[1,-2,3,-4]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$-1$$$.  The sum of the first three elements of $$$b$$$ is $$$2$$$.  The sum of the first four elements of $$$b$$$ is $$$-2$$$. Explanation of the second testcase: Since all values in $$$a$$$ are $$$0$$$, any rearrangement $$$b$$$ of $$$a$$$ will have all elements equal to $$$0$$$ and therefore it clearly cannot satisfy the second property described in the statement (for example because $$$b_1=0$$$). Hence in this case the answer is NO.Explanation of the third testcase: An array with the desired properties is $$$b=[1, 1, -1, 1, -1]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$2$$$.  The sum of the first three elements of $$$b$$$ is $$$1$$$.  The sum of the first four elements of $$$b$$$ is $$$2$$$.  The sum of the first five elements of $$$b$$$ is $$$1$$$. Explanation of the fourth testcase: An array with the desired properties is $$$b=[-40,13,40,0,-9,-31]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$-40$$$.  The sum of the first two elements of $$$b$$$ is $$$-27$$$.  The sum of the first three elements of $$$b$$$ is $$$13$$$.  The sum of the first four elements of $$$b$$$ is $$$13$$$.  The sum of the first five elements of $$$b$$$ is $$$4$$$.  The sum of the first six elements of $$$b$$$ is $$$-27$$$.

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

void play(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    sort(arr);
    ll pls = 0, mins = 0;
    foreach(el; arr){
        if(el < 0){
            mins += el;
        }else{
            pls += el;
        }
    }
    if((mins + pls) == 0){
        writeln("NO");
    }else{
        writeln("YES");
        if(-mins < pls){
            reverse(arr);
        }
        arr.each!((el)=> write(el, " "));
        writeln;
    }
}

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

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = RedBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }

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;
		auto s = a.sum;
		if (s == 0)
		{
			writeln ("NO");
			continue;
		}
		sort (a);
		if (s > 0)
		{
			reverse (a);
		}
		writeln ("YES");
		writefln !("%(%s %)") (a);
	}
}

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 int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt();
        }
        A.sort;

        const ASum = A.sum;
        if (ASum == 0) {
          writeln("NO");
        } else {
          if (ASum > 0) {
            A.reverse;
          }
          writeln("YES");
          foreach (i; 0 .. N) {
            if (i > 0) write(" ");
            write(A[i]);
          }
          writeln;
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 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;
		a.sort();
		auto b = a.dup;

		int tot;
		while (!a.empty)
		{
			if (tot+a.front != 0)
			{
				tot += a.front;
				ans[ti] ~= a.front;
				a.popFront;
			}
			else if (tot+a.back != 0)
			{
				tot += a.back;
				ans[ti] ~= a.back;
				a.popBack;
			}
			else
			{
				ans[ti].length = 0;
				break;
			}
		}
		if (ans[ti].empty)
		{
			tot = 0;
			a = b;
			debug writeln(a);
			while (!a.empty)
			{
				if (tot+a.back != 0)
				{
					tot += a.back;
					ans[ti] ~= a.back;
					a.popBack;
				}
				else if (tot+a.front != 0)
				{
					tot += a.front;
					ans[ti] ~= a.front;
					a.popFront;
				}
				else
				{
					ans[ti].length = 0;
					break;
				}
				debug writeln("ans:", ans[ti]);
			}
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		if (sum (a) == 0)
		{
			writeln ("NO");
		}
		else
		{
			writefln !("%(%s %)") (a);
		}
	}
}

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;
		auto s = a.sum;
		if (s == 0)
		{
			writeln ("NO");
			continue;
		}
		sort (a);
		if (s > 0)
		{
			reverse (a);
		}
		writefln !("%(%s %)") (a);
	}
}


Peter has a sequence of integers a1, a2, ..., an. Peter wants all numbers in the sequence to equal h. He can perform the operation of "adding one on the segment [l, r]": add one to all elements of the sequence with indices from l to r (inclusive). At that, Peter never chooses any element as the beginning of the segment twice. Similarly, Peter never chooses any element as the end of the segment twice. In other words, for any two segments [l1, r1] and [l2, r2], where Peter added one, the following inequalities hold: l1 ≠ l2 and r1 ≠ r2.How many distinct ways are there to make all numbers in the sequence equal h? Print this number of ways modulo 1000000007 (109 + 7). Two ways are considered distinct if one of them has a segment that isn't in the other way.

The first line contains two integers n, h (1 ≤ n, h ≤ 2000). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 2000).

Print a single integer — the answer to the problem modulo 1000000007 (109 + 7).

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

int saiki(int idx, int num, int n, int h, int[] a, int[][] dp)
{
    if (dp[idx][num] != -1)
    {
        return dp[idx][num];
    }
    if (idx == n)
    {
        dp[idx][num] = num ? 0 : 1;
        return dp[idx][num];
    }
    auto d = h - a[idx];
    if (d < num || d > num + 1)
    {
        dp[idx][num] = 0;
        return 0;
    }
    static const int mod = 1000000007;
    auto res = 0;
    if (d == num)
    {
        res += saiki(idx + 1, num, n, h, a, dp);
        if (num > 0)
        {
            res += (cast(long)num * saiki(idx + 1, num - 1, n, h, a, dp)) % mod;
        }
    }
    else
    {
        res += saiki(idx + 1, num + 1, n, h, a, dp);
        res += (cast(long)(num + 1) * saiki(idx + 1, num, n, h, a, dp)) % mod;
    }
    res %= mod;
    dp[idx][num] = res;
    return res;
}

void solve(int[] a, int n, int h)
{
    auto dp = new int[][](n + 1, n + 1);
    foreach (i; 0 .. n + 1)
    {
        fill(dp[i], -1);
    }
    auto ans = saiki(0, 0, n, h, a, dp);
    writeln(ans);
}

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


Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$  $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them.

The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges.

If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them.

NoteHere is the representation of the graph from the first example:

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;

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

    if (M < N - 1) {
        writeln("Impossible");
        return;
    }

    auto X = new int[][](N+1);
    auto Y = new int[][](N+1);

    foreach (i; 2..N+1) {
        if (!X[i].empty) continue;
        for (int j = i; j <= N; j += i) {
            X[j] ~= i;
            Y[i] ~= j;
        }
    }

    int cnt = 0;
    auto ans = new Tuple!(int, int)[](M);

    foreach (i; 2..N+1) {
        ans[cnt] = tuple(1, i);
        cnt += 1;
    }

    for (int i = N - (1 - N%2); i > 2 && cnt < M; i -= 2) {
        auto tmp = new bool[](i);
        foreach (j; X[i]) foreach (k; Y[j]) if (k < i) tmp[k] = true;
        for (int j = 2; j < i && cnt < M; ++j) if (!tmp[j]) ans[cnt] = tuple(j, i), cnt++;
    }
    for (int i = N - N%2; i > 1 && cnt < M; i -= 2) {
        auto tmp = new bool[](i);
        foreach (j; X[i]) foreach (k; Y[j]) if (k < i) tmp[k] = true;
        for (int j = 2; j < i && cnt < M; ++j) if (!tmp[j]) ans[cnt] = tuple(j, i), cnt++;
    }

    if (cnt == M) {
        writeln("Possible");
        ans.each!(a => writeln(a[0], " ", a[1]));
    } else {
        writeln("Impossible");
    }
}

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;

    if (m < n-1) {
        writeln("Impossible");
        return;
    }

    Tuple!(int, int)[] ans;

    outer: foreach (i; 1 .. n+1) {
        foreach (j; i+1 .. n+1) {
            if (gcd(i, j) > 1) continue;

            ans ~= tuple(i, j);

            if (ans.length == m) break outer;
        }
    }

    if (ans.length < m) {
        writeln("Impossible");
        return;
    }

    writeln("Possible");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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;

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

    if (M < N - 1) {
        writeln("Impossible");
        return;
    }

    auto X = new int[][](N+1);
    auto Y = new int[][](N+1);

    foreach (i; 2..N+1) {
        if (!X[i].empty) continue;
        for (int j = i; j <= N; j += i) {
            X[j] ~= i;
            Y[i] ~= j;
        }
    }

    int cnt = 0;
    auto ans = new Tuple!(int, int)[](M);

    foreach (i; 2..N+1) {
        ans[cnt] = tuple(1, i);
        cnt += 1;
    }

    for (int i = N - (1 - N%2); i > 2 && cnt < M; --i) {
        auto tmp = new bool[](i);
        foreach (j; X[i]) foreach (k; Y[j]) if (k < i) tmp[k] = true;
        for (int j = 2; j < i && cnt < M; ++j) if (!tmp[j]) ans[cnt] = tuple(j, i), cnt++;
    }
    for (int i = N - N%2; i > 1 && cnt < M; --i) {
        auto tmp = new bool[](i);
        foreach (j; X[i]) foreach (k; Y[j]) if (k < i) tmp[k] = true;
        for (int j = 2; j < i && cnt < M; ++j) if (!tmp[j]) ans[cnt] = tuple(j, i), cnt++;
    }

    if (cnt == M) {
        writeln("Possible");
        ans.each!(a => writeln(a[0], " ", a[1]));
    } else {
        writeln("Impossible");
    }
}


Do you know the story about the three musketeers? Anyway, you must help them now.Richelimakieu is a cardinal in the city of Bearis. He found three brave warriors and called them the three musketeers. Athos has strength a, Borthos strength b, and Caramis has strength c.The year 2015 is almost over and there are still n criminals to be defeated. The i-th criminal has strength ti. It's hard to defeat strong criminals — maybe musketeers will have to fight together to achieve it.Richelimakieu will coordinate musketeers' actions. In each hour each musketeer can either do nothing or be assigned to one criminal. Two or three musketeers can be assigned to the same criminal and then their strengths are summed up. A criminal can be defeated in exactly one hour (also if two or three musketeers fight him). Richelimakieu can't allow the situation where a criminal has strength bigger than the sum of strengths of musketeers fighting him — a criminal would win then!In other words, there are three ways to defeat a criminal.  A musketeer of the strength x in one hour can defeat a criminal of the strength not greater than x. So, for example Athos in one hour can defeat criminal i only if ti ≤ a.  Two musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of strengths of these two musketeers. So, for example Athos and Caramis in one hour can defeat criminal i only if ti ≤ a + c. Note that the third remaining musketeer can either do nothing or fight some other criminal.  Similarly, all three musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of musketeers' strengths, i.e. ti ≤ a + b + c. Richelimakieu doesn't want musketeers to fight during the New Year's Eve. Thus, he must coordinate their actions in order to minimize the number of hours till all criminals will be defeated.Find the minimum number of hours to defeat all criminals. If musketeers can't defeat them all then print "-1" (without the quotes) instead.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of criminals. The second line contains three integers a, b and c (1 ≤ a, b, c ≤ 108) — strengths of musketeers. The third line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 108) — strengths of criminals.

Print one line with the answer. If it's impossible to defeat all criminals, print "-1" (without the quotes). Otherwise, print the minimum number of hours the three musketeers will spend on defeating all criminals.

NoteIn the first sample Athos has strength 10, Borthos 20, and Caramis 30. They can defeat all criminals in two hours:  Borthos and Caramis should together fight a criminal with strength 50. In the same hour Athos can fight one of four criminals with strength 1.  There are three criminals left, each with strength 1. Each musketeer can fight one criminal in the second hour.  In the second sample all three musketeers must together fight a criminal with strength 51. It takes one hour. In the second hour they can fight separately, each with one criminal. In the third hour one criminal is left and any of musketeers can fight him.

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

immutable int NA = -1;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto p = readln.split.map !(to !(int)).array;
		sort (p);
		auto a = readln.split.map !(to !(int)).array;
		sort (a);

		if (a.back > sum (p))
		{
			writeln (-1);
			continue;
		}

		int res = 0;
		while (!a.empty && a.back > p[1] + p[2])
		{
			assert (a.back <= sum (p));
			res++;
			a.popBack ();
		}
		debug {writeln (res, ' ', a); stdout.flush;}

		while (!a.empty && a.back > p[0] + p[2])
		{
			assert (a.back <= p[1] + p[2]);
			res++;
			a.popBack ();
			if (!a.empty && a.front <= p[0])
			{
				a.popFront ();
			}
		}
		debug {writeln (res, ' ', a); stdout.flush;}

		if (true)
		{
			int to1 = cast (int) (a.length - 1 -
			    a.assumeSorted.upperBound (p[1]).length);

			while (!a.empty && a.back > max (p[0] + p[1], p[2]))
			{
				assert (a.back <= p[0] + p[2]);
				res++;
				a.popBack ();
				if (to1 >= 0)
				{
					assert (a[to1] <= p[1]);
					a[to1] = NA;
					to1--;
				}
			}

			a = a.filter !(x => x != NA).array;
			debug {writeln (res, ' ', a); stdout.flush;}
		}

		foreach (ref c; a)
		{
			assert (c <= p[0] || c <= p[1] || c <= p[2] ||
			    c <= p[0] + p[1]);
		}

		if (p[0] + p[1] > p[2])
		{
			int to2 = cast (int) (a.length - 1 -
			    a.assumeSorted.upperBound (p[2]).length);

			while (!a.empty && a.back > p[2])
			{
				assert (a.back <= p[0] + p[1]);
				res++;
				a.popBack ();
				if (to2 >= 0)
				{
					assert (a[to2] <= p[2]);
					a[to2] = NA;
					to2--;
				}
			}

			a = a.filter !(x => x != NA).array;
			debug {writeln (res, ' ', a); stdout.flush;}
		}

		assert (a.back <= p[2]);

		int add = a.length;
		if (true)
		{
			int to0 = cast (int) (a.length - 1 -
			    a.assumeSorted.upperBound (p[0]).length);
			int to1 = cast (int) (a.length - 1 -
			    a.assumeSorted.upperBound (p[1]).length);
			int to2 = cast (int) (a.length - 1 -
			    a.assumeSorted.upperBound (p[2]).length);
			assert (to2 == a.length - 1);
			int to01 = cast (int) (a.length - 1 -
			    a.assumeSorted.upperBound (p[0] + p[1]).length);
			int cur01 = 0;
			while (true)
			{
				int num0 = to0 + 1;
				int num1 = to1 - to0;
				int num2 = to2 - to1;
				int temp = num2;
				temp = max (temp,
				    (num1 + num2 + 1) / 2);
				temp = max (temp,
				    (num0 + num1 + num2 + 2) / 3);
				add = min (add, cur01 + temp);
				debug {writeln (cur01, " + ", temp);
				    stdout.flush;}

				if (to01 < 0)
				{
					break;
				}

				cur01++;
				to01--;
				if (to01 < to0)
				{
					to0--;
				}
				if (to01 < to1)
				{
					to1--;
				}
				if (to01 < to2)
				{
					to2--;
				}
				if (to2 >= 0)
				{
					to2--;
					if (to2 < to0)
					{
						to0--;
					}
					if (to2 < to1)
					{
						to1--;
					}
					if (to2 < to01)
					{
						to01--;
					}
				}
			}
		}

		res += add;
		writeln (res);
	}
}


Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time (in seconds).Let's suppose that Valera will set v seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most v seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, a seconds, an inequality 2a ≤ v holds.As a result, Valera decided to set v seconds TL, that the following conditions are met:  v is a positive integer;  all correct solutions pass the system testing;  at least one correct solution passes the system testing with some "extra" time;  all wrong solutions do not pass the system testing;  value v is minimum among all TLs, for which points 1, 2, 3, 4 hold. Help Valera and find the most suitable TL or else state that such TL doesn't exist.

The first line contains two integers n, m (1 ≤ n, m ≤ 100). The second line contains n space-separated positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the running time of each of the n correct solutions in seconds. The third line contains m space-separated positive integers b1, b2, ..., bm (1 ≤ bi ≤ 100) — the running time of each of m wrong solutions in seconds.

If there is a valid TL value, print it. Otherwise, print -1.

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

void main() {
    int n, m; readf("%d %d\n", &n, &m);
    auto cs = stdin.readln.split.map!(to!int);
    auto ws = stdin.readln.split.map!(to!int);
    auto cmin = cs.reduce!min;
    auto cmax = cs.reduce!max;
    auto wmin = ws.reduce!min;
    int v = max(cmin * 2, cmax);
    if (v >= wmin) {
        writeln(-1);
    } else {
        writeln(v);
    }
}

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

//	Input
string[] tokens;
int tokenId = 0;
string readToken() { for (; tokenId == tokens.length; ) tokens = readln.split, tokenId = 0; return tokens[tokenId++]; }

int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

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

void main () {
    int N; N = readInt();
    int M; M = readInt();

    int[110] valid;
    int[110] invalid;

    int best = 0;

    foreach (i; 0 .. N) {
        valid[i] = readInt();
        chmax(best, valid[i]);
    }

    foreach (i; 0 .. M) {
        invalid[i] = readInt();
        chmax(best, invalid[i]);
    }

    bool ok = false;

    foreach (i; 1 .. best + 1) {
        bool les = true;
        bool exe = false;
        bool big = true;

        foreach (j; 0 .. N) {
            if (valid[j] > i) {
                les = false;
            }
            if (valid[j] * 2 <= i) {
                exe = true;
            }
        }

        foreach (j; 0 .. M) {
            if (invalid[j] <= i) {
                big = false;
            }
        }

        if (exe && les && big) {
            ok = true;
            writeln("", i);
            break;
        }
    }

    if (!ok) {
        writeln("-1");
    }
}

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

//  Input
string[] tokens;
int tokenId = 0;
string readToken() { for (; tokenId == tokens.length; ) tokens = readln.split, tokenId = 0; return tokens[tokenId++]; }

int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

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

void main () {
    int N; N = readInt();
    int M; M = readInt();

    int[110] valid;
    int[110] invalid;

    int best = 0;

    foreach (i; 0 .. N) {
        valid[i] = readInt();
        chmax(best, valid[i]);
    }

    foreach (i; 0 .. M) {
        invalid[i] = readInt();
        chmax(best, valid[i]);
    }

    bool ok = false;

    foreach (i; 1 .. best + 1) {
        bool les = true;
        bool exe = false;
        bool big = true;

        foreach (j; 0 .. N) {
            if (valid[j] > i) {
                les = false;
            }
            if (valid[j] * 2 < i) {
                exe = true;
            }
        }

        foreach (j; 0 .. M) {
            if (invalid[j] < i) {
                big = false;
            }
        }

        if (exe && les && big) {
            ok = true;
            writeln("", i);
            break;
        }
    }

    if (!ok) {
        writeln("-1");
    }

}


One warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize — big pink plush panda. The king is not good at shooting, so he invited you to help him.The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targets are points on this plane. Each target is described by it's coordinates xi, and yi, by the time of it's appearance ti and by the number pi, which gives the probability that Copa hits this target if he aims at it.A target appears and disappears instantly, so Copa can hit the target only if at the moment ti his gun sight aimed at (xi, yi). Speed of movement of the gun sight on the plane is equal to 1. Copa knows all the information about the targets beforehand (remember, he is a king!). He wants to play in the optimal way, which maximizes the expected value of the amount of hit targets. He can aim at any target at the moment 0.

The first line contains integer n (1 ≤ n ≤ 1000) — amount of targets in the shooting gallery. Then n lines follow, each describing one target. Each description consists of four numbers xi, yi, ti, pi (where xi, yi, ti — integers,  - 1000 ≤ xi, yi ≤ 1000, 0 ≤ ti ≤ 109, real number pi is given with no more than 6 digits after the decimal point, 0 ≤ pi ≤ 1). No two targets may be at the same point.

Output the maximum expected value of the amount of targets that was shot by the king. Your answer will be accepted if it differs from the correct answer by not more than 10 - 6.

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

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

    struct target {
        int x, y, t; double p;
        int opCmp(const ref target t2) const {
            return t - t2.t;
        }
    }

    auto ts = new target[] (n);
    foreach (i; 0 .. n) {
        readf("%s %s %s %s", &ts[i].x, &ts[i].y, &ts[i].t, &ts[i].p);
        readln;
    }

    ts.sort();

    debug { ts.writeln; }

    long dstSq(target t1, target t2) {
        return (t1.x.to!long - t2.x) ^^ 2 + (t1.y.to!long - t2.y) ^^ 2;
    }

    long tmSq(target t1, target t2) {
        return (t1.t.to!long - t2.t) ^^ 2;
    }

    auto dp = new double[] (n+1);
    dp[0] = 0;
    foreach (i; 0 .. n) {
        dp[i+1] = ts[i].p;
        foreach (j; 0 .. i) {
            if (ts[j].t == ts[i].t) { break; }
            if (dstSq(ts[i], ts[j]) > tmSq(ts[i], ts[j])) { continue; }
            dp[i+1] = max(dp[i+1], dp[j+1] + ts[i].p);
        }
    }

    debug { dp.writeln; }

    dp.maxElement.writefln!"%.10f";
}

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

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

    struct target {
        int x, y, t; double p;
        int opCmp(const ref target t2) const {
            return t - t2.t;
        }
    }

    auto ts = new target[] (n);
    foreach (i; 0 .. n) {
        readf("%s %s %s %s", &ts[i].x, &ts[i].y, &ts[i].t, &ts[i].p);
        readln;
    }

    ts.sort();

    debug { ts.writeln; }

    long dstSq(target t1, target t2) {
        return (t1.x.to!long - t2.x) ^^ 2 + (t1.y.to!long - t2.y) ^^ 2;
    }

    long tmSq(target t1, target t2) {
        return (t1.t.to!long - t2.t) ^^ 2;
    }

    auto dp = new double[] (n+1);
    dp[0] = 0;
    foreach (i; 0 .. n) {
        dp[i+1] = ts[i].p;
        foreach (j; 0 .. i) {
            if (ts[j].t == ts[i].t) { break; }
            if (dstSq(ts[i], ts[j]) > tmSq(ts[i], ts[j])) { continue; }
            dp[i+1] = max(dp[i+1], dp[j+1] + ts[i].p);
        }
    }

    dp[n].writefln!"%.10f";
}


Initially, you have the array $$$a$$$ consisting of one element $$$1$$$ ($$$a = [1]$$$).In one move, you can do one of the following things:  Increase some (single) element of $$$a$$$ by $$$1$$$ (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and increase $$$a_i$$$ by one);  Append the copy of some (single) element of $$$a$$$ to the end of the array (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and append $$$a_i$$$ to the end of the array). For example, consider the sequence of five moves:  You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [1, 1]$$$.  You take the first element $$$a_1$$$, increase it by $$$1$$$ and get $$$a = [2, 1]$$$.  You take the second element $$$a_2$$$, append its copy to the end of the array and get $$$a = [2, 1, 1]$$$.  You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [2, 1, 1, 2]$$$.  You take the fourth element $$$a_4$$$, increase it by $$$1$$$ and get $$$a = [2, 1, 1, 3]$$$. Your task is to find the minimum number of moves required to obtain the array with the sum at least $$$n$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the lower bound on the sum of the array.

For each test case, print the answer: the minimum number of moves required to obtain the array with the sum at least $$$n$$$.

// Vicfred
// https://codeforces.com/contest/1426/problem/C
// greedy
import std.algorithm;
import std.stdio;

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

    long n;
    while(t--) {
        readf("%s\n", &n);
        long minima = long.max;
        for(long i = 1L; i * i <= n; ++i) {
            minima = min(minima, i + (n - i - 1L)/i);
        }
        minima.writeln;
    }
}


There are $$$n$$$ candies put from left to right on a table. The candies are numbered from left to right. The $$$i$$$-th candy has weight $$$w_i$$$. Alice and Bob eat candies. Alice can eat any number of candies from the left (she can't skip candies, she eats them in a row). Bob can eat any number of candies from the right (he can't skip candies, he eats them in a row). Of course, if Alice ate a candy, Bob can't eat it (and vice versa).They want to be fair. Their goal is to eat the same total weight of candies. What is the most number of candies they can eat in total?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the number of candies on the table. The second line of each test case contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \leq w_i \leq 10^4$$$) — the weights of candies from left to right. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, print a single integer — the maximum number of candies Alice and Bob can eat in total while satisfying the condition.

NoteFor the first test case, Alice will eat one candy from the left and Bob will eat one candy from the right. There is no better way for them to eat the same total amount of weight. The answer is $$$2$$$ because they eat two candies in total.For the second test case, Alice will eat the first three candies from the left (with total weight $$$7$$$) and Bob will eat the first three candies from the right (with total weight $$$7$$$). They cannot eat more candies since all the candies have been eaten, so the answer is $$$6$$$ (because they eat six candies in total).For the third test case, there is no way Alice and Bob will eat the same non-zero weight so the answer is $$$0$$$.For the fourth test case, Alice will eat candies with weights $$$[7, 3, 20]$$$ and Bob will eat candies with weights $$$[10, 8, 11, 1]$$$, they each eat $$$30$$$ weight. There is no better partition so the answer is $$$7$$$.

import std;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;

		int [int] d;
		int cur = 0;
		foreach (i, ref c; a)
		{
			cur += c;
			d[cur] = i + 1;
		}

		reverse (a);
		int res = 0;
		int next = 0;
		foreach (j, ref c; a)
		{
			next += c;
			if (next in d && j + 1 + d[next] <= n)
			{
				res = j + 1 + d[next];
			}
		}

		writeln (res);
	}
}


To stay woke and attentive during classes, Karen needs some coffee!  Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".She knows n coffee recipes. The i-th recipe suggests that coffee should be brewed between li and ri degrees, inclusive, to achieve the optimal taste.Karen thinks that a temperature is admissible if at least k recipes recommend it.Karen has a rather fickle mind, and so she asks q questions. In each question, given that she only wants to prepare coffee with a temperature between a and b, inclusive, can you tell her how many admissible integer temperatures fall within the range?

The first line of input contains three integers, n, k (1 ≤ k ≤ n ≤ 200000), and q (1 ≤ q ≤ 200000), the number of recipes, the minimum number of recipes a certain temperature must be recommended by to be admissible, and the number of questions Karen has, respectively. The next n lines describe the recipes. Specifically, the i-th line among these contains two integers li and ri (1 ≤ li ≤ ri ≤ 200000), describing that the i-th recipe suggests that the coffee be brewed between li and ri degrees, inclusive. The next q lines describe the questions. Each of these lines contains a and b, (1 ≤ a ≤ b ≤ 200000), describing that she wants to know the number of admissible integer temperatures between a and b degrees, inclusive.

For each question, output a single integer on a line by itself, the number of admissible integer temperatures between a and b degrees, inclusive.

NoteIn the first test case, Karen knows 3 recipes.  The first one recommends brewing the coffee between 91 and 94 degrees, inclusive.  The second one recommends brewing the coffee between 92 and 97 degrees, inclusive.  The third one recommends brewing the coffee between 97 and 99 degrees, inclusive. A temperature is admissible if at least 2 recipes recommend it.She asks 4 questions.In her first question, she wants to know the number of admissible integer temperatures between 92 and 94 degrees, inclusive. There are 3: 92, 93 and 94 degrees are all admissible.In her second question, she wants to know the number of admissible integer temperatures between 93 and 97 degrees, inclusive. There are 3: 93, 94 and 97 degrees are all admissible.In her third question, she wants to know the number of admissible integer temperatures between 95 and 96 degrees, inclusive. There are none.In her final question, she wants to know the number of admissible integer temperatures between 90 and 100 degrees, inclusive. There are 4: 92, 93, 94 and 97 degrees are all admissible.In the second test case, Karen knows 2 recipes.  The first one, "wikiHow to make Cold Brew Coffee", recommends brewing the coffee at exactly 1 degree.  The second one, "What good is coffee that isn't brewed at at least 36.3306 times the temperature of the surface of the sun?", recommends brewing the coffee at exactly 200000 degrees. A temperature is admissible if at least 1 recipe recommends it.In her first and only question, she wants to know the number of admissible integer temperatures that are actually reasonable. There are none.

import std.stdio, std.random;

alias V = long;
alias P = int;

class Node
{
    V value;
    V valueSum;
    V valuePendingAdd;
    Node left;
    Node right;
    int size;

    this(V value, Node left = null, Node right = null)
    {
        this.value = value;
        this.left = left;
        this.right = right;
        update();
    }

    void update()
    {
        size = getSize(left) + getSize(right) + 1;
        valueSum = getValueSum(left) + getValueSum(right) + value;
    }
}

int getSize(Node node)
{
    return node is null ? 0 : node.size;
}

V getValueSum(Node node)
{
    return node is null ? 0 : node.valueSum;
}

void pushPending(Node node)
{
    if (node !is null && node.valuePendingAdd != 0)
    {
        if (node.left !is null) node.left.valuePendingAdd += node.valuePendingAdd;
        if (node.right !is null) node.right.valuePendingAdd += node.valuePendingAdd;

        node.value += node.valuePendingAdd;
        node.valuePendingAdd = 0;
    }
}

Node merge(Node l, Node r)
{
    if (l is null) return r;
    if (r is null) return l;

    l.pushPending();
    r.pushPending();

    if (uniform(-l.size, r.size) < 0)
    {
        l.right = merge(l.right, r);
        l.update();
        return l;
    }
    else
    {
        r.left = merge(l, r.left);
        r.update();
        return r;
    }
}

void split(Node node, int splitIndex, out Node outL, out Node outR)
{
    if (node is null)
    {
        outL = null;
        outR = null;
        return;
    }

    node.pushPending();

    int leftSize = getSize(node.left);
    Node newNode = null;

    if (leftSize < splitIndex)
    {
        if (node.right is null) outR = null;
        else split(node.right, splitIndex - leftSize - 1, newNode, outR);

        node.right = newNode;
        node.update();
        outL = node;
    }
    else
    {
        if (node.left is null) outL = null;
        else split(node.left, splitIndex, outL, newNode);

        node.left = newNode;
        node.update();
        outR = node;
    }
}

void main()
{
    int n, k, q;
    readf("%d %d %d", &n, &k, &q);

    Node root = null;

    for (int i = 0; i < 200010; i++)
    {
        root = merge(root, new Node(0));
    }

    for (int i = 0; i < n; i++)
    {
        int l, r;
        readf(" %d %d", &l, &r);

        Node a, b, c;

        root.split(r, b, c);
        b.split(l-1, a, b);

        b.valuePendingAdd++;
        root = merge(merge(a, b), c);
    }

    Node root2 = null;

    void traverse(Node node)
    {
        if (node is null) return;

        node.pushPending();

        traverse(node.left);

        root2 = merge(root2, new Node(node.value >= k ? 1 : 0));

        traverse(node.right);
    }

    traverse(root);

    for (int i = 0; i < q; i++)
    {
        int l, r;
        readf(" %d %d", &l, &r);

        Node a, b, c;

        root2.split(r, b, c);
        b.split(l-1, a, b);
        writeln(b.valueSum);
        root2 = merge(merge(a, b), c);
    }
}

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

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

    auto cs = new int[](200020);
    foreach (_; 0..N) {
        s = readln.split.map!(to!int);
        cs[s[0]] += 1;
        cs[s[1]+1] -= 1;
    }
    foreach (i; 0..200019) {
        cs[i+1] += cs[i];
    }

    auto st = new SegmentTree(200020);
    foreach (i; 0..200020) if (cs[i] >= K) st.add(i, 1);

    while (Q--) {
        s = readln.split.map!(to!int);
        st.sum(s[0], s[1]).writeln;
    }

}

class SegmentTree {
    int[] table;
    int size;

    this(int n) {
        assert(bsr(n) < 29);
        size = 1 << (bsr(n) + 2);
        table = new int[](size);
    }

    void add(int pos, int num) {
        return add(pos, num, 0, 0, size/2-1);
    }

    void add(int pos, int num, int i, int left, int right) {
        table[i] += num;
        if (left == right) {
            return;
        }
        auto mid = (left + right) / 2;
        if (pos <= mid)
            add(pos, num, i*2+1, left, mid);
        else
            add(pos, num, i*2+2, mid+1, right);
    }

    int sum(int pl, int pr) {
        return sum(pl, pr, 0, 0, size/2-1);
    }

    int sum(int pl, int pr, int i, int left, int right) {
        if (pl > right || pr < left)
            return 0;
        else if (pl <= left && right <= pr)
            return table[i];
        else
            return
                sum(pl, pr, i*2+1, left, (left+right)/2) +
                sum(pl, pr, i*2+2, (left+right)/2+1, right);
    }
}

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

immutable int max = 2 * 10^^5 + 2;

int n, k, q;

void main() {
    scan(n, k, q);

    auto adm = new int[](max);

    int li, ri;

    foreach (i ; 0 .. n) {
        scan(li, ri);
        adm[li]++;
        adm[ri+1]--;
    }

    foreach (i ; 1 .. max) {
        adm[i] += adm[i - 1];
    }

    foreach (i ; 0 .. max) {
        adm[i] = (adm[i] >= k);
    }

    foreach (i ; 1 .. max) {
        adm[i] += adm[i - 1];
    }

    int ai, bi;

    foreach (i ; 0 .. q) {
        scan(ai, bi);
        writeln(adm[bi] - adm[ai - 1]);
    }
}

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

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

immutable int max = 2 * 10^^5 + 10;

int n, k, q;
//int[] l, r;

void main() {
    scan(n, k, q);

    auto adm = new int[](max);

    int li, ri;

    foreach (i ; 0 .. n) {
        scan(li, ri);
        adm[li]++;
        adm[ri+1]--;
    }

    iota(max - 1).each!(i => adm[i + 1] += adm[i]);

    debug {
        stderr.writeln("adm:", adm[0 .. 120]);
    }

    adm = adm.map!(a => (a >= k).to!int).array;

    debug {
        stderr.writeln("adm:", adm[0 .. 120]);
    }

    iota(max - 1).each!(i => adm[i + 1] += adm[i]);

    debug {
        stderr.writeln("adm:", adm[0 .. 150]);
    }

    int ai, bi, ans;

    foreach (i ; 0 .. q) {
        scan(ai, bi);
        ans = adm[bi] - adm[ai - 1];
        ans.writeln;
    }
}

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

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 LIM = 200000 + 10;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      const Q = readInt();
      auto L = new int[N];
      auto R = new int[N];
      foreach (i; 0 .. N) {
        L[i] = readInt();
        R[i] = readInt();
      }
      auto A = new int[Q];
      auto B = new int[Q];
      foreach (q; 0 .. Q) {
        A[q] = readInt();
        B[q] = readInt();
      }

      auto fs = new int[LIM];
      foreach (i; 0 .. N) {
        ++fs[L[i]];
        --fs[R[i] + 1];
      }
      foreach (x; 1 .. LIM) {
        fs[x] += fs[x - 1];
      }
      auto gs = new int[LIM + 1];
      foreach (x; 0 .. LIM) {
        gs[x + 1] = gs[x] + ((fs[x] >= K) ? 1 : 0);
      }

      foreach (q; 0 .. Q) {
        const ans = gs[B[q] + 1] - gs[A[q]];
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately. Valera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe. Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.

The first line contains a single integer n (1 ≤ n ≤ 105), that is the number of cafe visitors. Each of the following n lines has two space-separated integers hi and mi (0 ≤ hi ≤ 23; 0 ≤ mi ≤ 59), representing the time when the i-th person comes into the cafe.  Note that the time is given in the chronological order. All time is given within one 24-hour period.

Print a single integer — the minimum number of cashes, needed to serve all clients next day.

NoteIn the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.In the second sample all visitors will come in different times, so it will be enough one cash.

module main;

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

void main(string[] args)
{
	version(MY_SUPER_PUPER_ONLINE_JUDGE)
	{
		stdin.open("src/input.txt", "rt");
		stdout.open("src/output.txt","wt");
	}

	int n;

	readf("%d\n", &n);
	int count = 1, res = 1;
	int x, y;
	readf("%d %d\n", &x, &y);
	for(int i = 1; i < n; i++)
	{
		int x1, y1;
		readf("%d %d\n", &x1, &y1);
		if(x1 == x && y1 == y)
		{
			count++;
			res = max(res, count);
		}
		else
		{
			count = 1;
		}
		x = x1;
		y = y1;
	}
	write(res);
}


You are playing one RPG from the 2010s. You are planning to raise your smithing skill, so you need as many resources as possible. So how to get resources? By stealing, of course.You decided to rob a town's blacksmith and you take a follower with you. You can carry at most $$$p$$$ units and your follower — at most $$$f$$$ units.In the blacksmith shop, you found $$$cnt_s$$$ swords and $$$cnt_w$$$ war axes. Each sword weights $$$s$$$ units and each war axe — $$$w$$$ units. You don't care what to take, since each of them will melt into one steel ingot.What is the maximum number of weapons (both swords and war axes) you and your follower can carry out from the shop?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$p$$$ and $$$f$$$ ($$$1 \le p, f \le 10^9$$$) — yours and your follower's capacities. The second line of each test case contains two integers $$$cnt_s$$$ and $$$cnt_w$$$ ($$$1 \le cnt_s, cnt_w \le 2 \cdot 10^5$$$) — the number of swords and war axes in the shop. The third line of each test case contains two integers $$$s$$$ and $$$w$$$ ($$$1 \le s, w \le 10^9$$$) — the weights of each sword and each war axe. It's guaranteed that the total number of swords and the total number of war axes in all test cases don't exceed $$$2 \cdot 10^5$$$.

For each test case, print the maximum number of weapons (both swords and war axes) you and your follower can carry.

NoteIn the first test case:   you should take $$$3$$$ swords and $$$3$$$ war axes: $$$3 \cdot 5 + 3 \cdot 6 = 33 \le 33$$$  and your follower — $$$3$$$ swords and $$$2$$$ war axes: $$$3 \cdot 5 + 2 \cdot 6 = 27 \le 27$$$.  $$$3 + 3 + 3 + 2 = 11$$$ weapons in total.In the second test case, you can take all available weapons even without your follower's help, since $$$5 \cdot 10 + 5 \cdot 10 \le 100$$$.In the third test case, you can't take anything, but your follower can take $$$3$$$ war axes: $$$3 \cdot 5 \le 19$$$.

// Vicfred
// https://codeforces.com/contest/1400/problem/B
//
import std.algorithm;
import std.stdio;

void main() {
    long t, p, f, cnts, cntw, s, w;

    readf("%s", &t);
    readln;

    while(t--) {
        readf("%s %s\n", &p, &f);
        readf("%s %s\n", &cnts, &cntw);
        readf("%s %s\n", &s, &w);

        if(s > w) {
            swap(s,w);
            swap(cnts, cntw);
        }

        long ans = long.min;
        for(long swords = 0; swords <= cnts; ++swords) {
            if(p/s < swords)
                continue;

            long goku, freezer, cnt, maxima;
            goku = p;
            freezer = f;

            goku -= swords*s;
            cnt = min(f/s, cnts - swords);
            freezer -= cnt*s;

            maxima = swords + cnt;
            maxima += min(cntw, goku/w + freezer/w);

            //writefln("goku lleva %s espadas", swords);
            //writefln("freezer lleva %s espadas", cnt);
            //writefln("hachas %s", min(cntw, goku/w + freezer/w));

            ans = max(maxima, ans);
        }

        ans.writeln;
    }
}

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

void main ()
{
	foreach (test; 0..readln.strip.to !(int))
	{
		int p, f;
		readf !(" %s %s") (p, f);
		int cs, cw;
		readf !(" %s %s") (cs, cw);
		int s, w;
		readf !(" %s %s") (s, w);
		if (s > w)
		{
			swap (s, w);
			swap (cs, cw);
		}
		int res = 0;
		foreach (ns; 0..cs + 1)
		{
			auto ns1 = min (ns, p / s);
			auto ns2 = min (cs - ns1, f / s);
			auto nw1 = min (cw, (p - ns1 * s) / w);
			auto nw2 = min (cw - nw1, (f - ns2 * s) / w);
			res = max (res, ns1 + ns2 + nw1 + nw2);
		}
		writeln (res);
	}
}


The only difference between the two versions is that in this version $$$n \leq 1000$$$ and the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.A terminal is a row of $$$n$$$ equal segments numbered $$$1$$$ to $$$n$$$ in order. There are two terminals, one above the other. You are given an array $$$a$$$ of length $$$n$$$. For all $$$i = 1, 2, \dots, n$$$, there should be a straight wire from some point on segment $$$i$$$ of the top terminal to some point on segment $$$a_i$$$ of the bottom terminal. You can't select the endpoints of a segment. For example, the following pictures show two possible wirings if $$$n=7$$$ and $$$a=[4,1,4,6,7,7,5]$$$.  A crossing occurs when two wires share a point in common. In the picture above, crossings are circled in red.What is the maximum number of crossings there can be if you place the wires optimally?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the elements of the array. The sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.

For each test case, output a single integer — the maximum number of crossings there can be if you place the wires optimally.

NoteThe first test case is shown in the second picture in the statement.In the second test case, the only wiring possible has the two wires cross, so the answer is $$$1$$$.In the third test case, the only wiring possible has one wire, so the answer is $$$0$$$.

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N);

      auto st = SegTree!("a + b", int)(new int[](N + 1));
      int ans;
      foreach(i, a; A) {
        ans += st.sum(a, N + 1);

        auto x = st.get(a);
        st.update(a, x + 1);
      }

      return ans;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

struct SegTree(alias pred = "a + b", T = long) {
  alias predFun = binaryFun!pred;
  int size;
  T[] data;
  T monoid;

  this(T[] src, T monoid = T.init) {
    this.monoid = monoid;

    for(int i = 2; i < 2L^^32; i *= 2) {
      if (src.length <= i) {
        size = i;
        break;
      }
    }

    data = new T[](size * 2);
    foreach(i, s; src) data[i + size] = s;
    foreach_reverse(b; 1..size) {
      data[b] = predFun(data[b * 2], data[b * 2 + 1]);
    }
  }

  void update(int index, T value) {
    int i = index + size;
    data[i] = value;
    while(i > 0) {
      i /= 2;
      data[i] = predFun(data[i * 2], data[i * 2 + 1]);
    }
  }

  T get(int index) {
    return data[index + size];
  }

  T sum(int a, int b, int k = 1, int l = 0, int r = -1) {
    if (r < 0) r = size;

    if (r <= a || b <= l) return monoid;
    if (a <= l && r <= b) return data[k];

    T leftValue = sum(a, b, 2*k, l, (l + r) / 2);
    T rightValue = sum(a, b, 2*k + 1, (l + r) / 2, r);
    return predFun(leftValue, rightValue);
  }
}

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;
		a[] -= 1;
		auto b = new int [] [n];
		foreach_reverse (i; 0..n)
		{
			b[a[i]] ~= i;
		}

		auto t = new int [n + 1];

		void add (int i)
		{
			for ( ; i <= n; i += i & -i)
			{
				t[i] += 1;
			}
		}

		int ask (int i)
		{
			int res = 0;
			for ( ; i > 0; i -= i & -i)
			{
				res += t[i];
			}
			return res;
		}

		long res = 0;
		foreach (i; 0..n)
		{
			foreach (v; b[i])
			{
				res += ask (n - v);
				add (n - v);
			}
		}
		writeln (res);
	}
}


You are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where ai, j = 1 if the i-th switch turns on the j-th lamp and ai, j = 0 if the i-th switch is not connected to the j-th lamp.Initially all m lamps are turned off.Switches change state only from "off" to "on". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards.It is guaranteed that if you push all n switches then all m lamps will be turned on.Your think that you have too many switches and you would like to ignore one of them. Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other n - 1 switches then all the m lamps will be turned on.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 2000) — the number of the switches and the number of the lamps. The following n lines contain m characters each. The character ai, j is equal to '1' if the i-th switch turns on the j-th lamp and '0' otherwise. It is guaranteed that if you press all n switches all m lamps will be turned on.

Print "YES" if there is a switch that if you will ignore it and press all the other n - 1 switches then all m lamps will be turned on. Print "NO" if there is no such switch.

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;
import std.bigint;

void main()
{
	int n, m;
	readln.chomp.split.tie(n, m);
	char[][] field = new char[][](n);
	foreach (ref a; field) {
		a = readln.chomp.dup;
	}
	int[] cnt = new int[](m);
	foreach (a; field) {
		foreach (i, v; a) {
			if (v == '0') {
				continue;
			}
			cnt[i]++;
		}
	}
	debug verbose(cnt);
	bool ok = false;
	foreach (i; 0..n) {
		// ignore i-th
		bool flag = true;
		foreach (j; 0..m) {
			if (field[i][j] == '0') {
				continue;
			}
			flag &= cnt[j] > 1;
		}
		ok |= flag;
	}
	writeln = ok ? "YES" : "NO";
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    uint [][] a;
    foreach ( _; 0..n ) a ~= readln.chomp.map!(c => c - '0').array;

    auto b = transposed(a.dup).map!array.array;
    ulong[] sums;
    foreach ( j; 0..m ) {
        sums ~= b[ j ].count!(c => c == 1);
    }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == 0 || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

immutable int N = 2 * 1 ^^ 3 + 100;

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] (n, m);
    foreach ( i; 0..n ) a[i] = readln.chomp.array;

    auto b = transposed(a.dup);

    auto sums = new int[] (m);

    foreach ( i; 0..m ) {
        foreach ( j; 0..n ) {
            sums[ i ] += a[ j ][ i ] == '1';
        }
    }

    auto found = false;
    foreach ( i; 0..n ) {
        auto cur = true;
        foreach ( j; 0..m ) {
            cur &= a[ i ][ j ] == '0' || sums[ j ] > 1;
        }
        found |= cur;
    }
    writeln ( found ? "YES" : "NO" );
}

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

immutable int N = 2 * 1 ^^ 3 + 100;

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] (n, m);
    foreach ( i; 0..n ) a[i] = readln.chomp.array;

    auto sums = new int[] (m);

    foreach ( i; 0..m ) {
        foreach ( j; 0..n ) {
            sums[ i ] += a[ j ][ i ] == '1';
        }
    }

    auto found = false;
    foreach ( i; 0..n ) {
        auto cur = true;
        foreach ( j; 0..m ) {
            cur &= a[ i ][ j ] == '0' || sums[ j ] > 1;
        }
        found |= cur;
    }
    writeln ( found ? "YES" : "NO" );
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    uint [][] a;
    foreach ( _; 0..n ) a ~= readln.chomp.map!(c => c - '0').array;

    auto b = new uint [][] ( m, n );
    foreach ( i; 0..m ) {
        foreach ( j; 0..n ) {
            b[ i ][ j ] = a[ j ][ i ];
        }
    }

    ulong[] sums;
    foreach ( j; 0..m ) {
        sums ~= b[ j ].count!(c => c == 1);
    }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == 0 || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

immutable int N = 2 * 1 ^^ 3 + 100;

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] (n, m);
    foreach ( i; 0..n ) a[i] = readln.chomp.array;

    auto b = transposed(a.dup);
    auto sums = b.map!(a => a.count!(c => c == '1')).array;

    auto found = false;
    foreach ( i; 0..n ) {
        auto cur = true;
        foreach ( j; 0..m ) {
            cur &= a[ i ][ j ] == '0' || sums[ j ] > 1;
        }
        found |= cur;
    }
    writeln ( found ? "YES" : "NO" );
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] ( n, m );
    foreach ( i; 0..n ) a[ i ] = readln.chomp.array;

    auto b = transposed(a.dup);
    auto sums = new int[] (m);
    foreach ( j; 0..m ) {
        foreach ( i; 0..n ) {
            sums[ j ] += a[ i ][ j ] == '1';
        }
    }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == '0' || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    uint [][] a;
    foreach ( _; 0..n ) a ~= readln.chomp.map!(c => c - '0').array;

    auto b = new uint [][] ( m, n );
    foreach ( i; 0..m ) {
        foreach ( j; 0..n ) {
            b[ i ][ j ] = a[ j ][ i ];
        }
    }

    ulong[] sums;
    foreach ( j; 0..m ) {
        sums ~= b[ j ].sum;
    }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == 0 || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    string[] a;
    foreach ( i; 0..n ) a ~= readln.chomp;

    auto b = transposed(a.dup);
    auto sums = new int[] (m);
    foreach ( j; 0..m ) {
        foreach ( i; 0..n ) {
            sums[ j ] += a[ i ][ j ] == '1';
        }
    }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == '0' || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

immutable int N = 2 * 1 ^^ 3 + 100;

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] ( n, m );
    foreach ( i; 0..n ) a[ i ] = readln.chomp.array;

    auto b = transposed( a.dup );
    auto sums = b.map!( row => row.count!( c => c == '1' ) ).array;

    auto found = n.iota.any!( i => m.iota.all!( j => a[ i ][ j ] == '0' || sums[ j ] > 1 ) );
    writeln( found ? "YES" : "NO" );
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    uint [][] a;
    foreach ( i; 0..n ) a ~= readln.chomp.map!(c => c - '0').array;

    auto b = transposed(a.dup);
    auto sums = new int[] (m);
    foreach ( j; 0..m ) {
        foreach ( i; 0..n ) {
            sums[ j ] += a[ i ][ j ];
        }
    }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == 0 || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

immutable int N = 2 * 10 ^^ 3 + 100;

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] ( n, m );
    foreach ( i; 0..n ) a[ i ] = readln.chomp.array;

    auto sums = new int [] ( m );
    foreach ( i; 0..m ) {
        foreach ( j; 0..n ) {
            sums[ i ] += a[ j ][ i ] == '1' ;
        }
    }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == '0' || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

immutable int N = 2 * 1 ^^ 3 + 100;

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] ( n, m );
    foreach ( i; 0..n ) a[ i ] = readln.chomp.array;

    auto b = transposed( a.dup );
    auto sums = b.map!( row => row.count!( c => c == '1' ) ).array;

    auto goodCell = ( int i, int j ) => a[ i ][ j ] == '0' || sums[ j ] > 1 ;
    auto goodRow = ( int i ) => m.iota.all!( j => goodCell( i , j ) );
    auto found = n.iota.any!( goodRow );
    writeln( found ? "YES" : "NO" );
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    uint [][] a;
    foreach ( _; 0..n ) a ~= readln.chomp.map!(c => c - '0').array;

    auto b = new uint [][] ( m, n );
    foreach ( i; 0..m ) {
        foreach ( j; 0..n ) {
            b[ i ][ j ] = a[ j ][ i ];
        }
    }

    uint[] sums;
    foreach ( j; 0..m ) {
        sums ~= b[ j ].sum;
    }

    debug { writeln(a, ' ', sums); }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == 0 || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

immutable int N = 2 * 1 ^^ 3 + 100;

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new int [][] (n, m);
    foreach ( i; 0..n ) a[i] = readln.chomp.map!( c => cast(int)c - cast(int)'0' ).array;

    auto b = transposed(a.dup);
    auto sums = b.map!sum.array;

    auto found = false;
    foreach ( i; 0..n ) {
        auto cur = true;
        foreach ( j; 0..m ) {
            cur &= a[ i ][ j ] == 0 || sums[ j ] > 1;
        }
        found |= cur;
    }
    writeln ( found ? "YES" : "NO" );
}

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

immutable int N = 2 * 1 ^^ 3 + 100;

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] ( n, m );
    foreach ( i; 0..n ) a[ i ] = readln.chomp.array;

    auto b = new dchar [][] ( m, n );
    foreach ( i; 0..m ) {
        foreach ( j; 0..n ) {
            b[ i ][ j ] = a[ j ][ i ];
        }
    }
    auto sums = b.map!( row => row.count!( c => c == '1' ) ).array;

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == '0' || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

immutable int N = 2 * 1 ^^ 3 + 100;

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] ( n, m );
    foreach ( i; 0..n ) a[ i ] = readln.chomp.array;

    auto b = transposed( a.dup );
    auto sums = b.map!( row => row.count!( c => c == '1' ) ).array;

    auto found = false;
    foreach ( i; 0..n ) {
        auto cur = true;
        foreach ( j; 0..m ) {
            cur &= a[ i ][ j ] == '0' || sums[ j ] > 1;
        }
        found |= cur;
    }
    writeln( found ? "YES" : "NO" );
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    uint [][] a;
    foreach ( _; 0..n ) a ~= readln.chomp.map!(c => c - '0').array;

    auto b = new uint [][] ( m, n );
    foreach ( i; 0..m ) {
        foreach ( j; 0..n ) {
            b[ i ][ j ] = a[ j ][ i ];
        }
    }

    uint[] sums;
    foreach ( j; 0..m ) {
        sums ~= b[ j ].sum;
    }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == 0 || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] ( n, m );
    foreach ( i; 0..n ) a[ i ] = readln.chomp.array;

    auto b = transposed( a.dup );
    auto sums = b.map!( row => row.count!( c => c == '1' ) ).array;

    auto found = false;
    foreach ( i; 0..n ) {
        found |= m.iota.all!(j => a[ i ][ j ] == '0' || sums[ j ] > 1);
    }
    writeln( found ? "YES" : "NO" );
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    uint [][] a;
    foreach ( _; 0..n ) a ~= readln.chomp.map!(c => c - '0').array;

    auto b = new uint [][] ( m, n );
    foreach ( i; 0..m ) {
        foreach ( j; 0..n ) {
            b[ i ][ j ] = a[ j ][ i ];
        }
    }

    int[] sums;
    foreach ( j; 0..m ) {
        sums ~= b[ j ].sum;
    }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == 0 || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new uint [][] ( n, m );
    foreach ( i; 0..n ) a[ i ] = readln.chomp.map!(q{a - '0'}).array;

    auto b = transposed(a.dup);
    auto sums = new int[] (m);
    foreach ( j; 0..m ) {
        foreach ( i; 0..n ) {
            sums[ j ] += a[ i ][ j ];
        }
    }

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == 0 || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}

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

immutable int N = 2 * 1 ^^ 3 + 100;

void main()
{
    int n, m;
    readf( "%s %s", &n, &m );
    readln;
    auto a = new dchar [][] ( n, m );
    foreach ( i; 0..n ) a[ i ] = readln.chomp.array;

    auto b = transposed( a.dup ).array.map!array;
    auto sums = b.map!( row => row.count!( c => c == '1' ) ).array;

    auto replaceableCell = ( int i, int j ) => a[ i ][ j ] == '0' || sums[ j ] > 1;
    auto redundantRow = ( int i ) => m.iota.all!( j => replaceableCell( i , j ) );
    auto found = n.iota.any!( redundantRow );
    writeln( found ? "YES" : "NO" );
}