You are given a number $$$n$$$ and an array $$$b_1, b_2, \ldots, b_{n+2}$$$, obtained according to the following algorithm:   some array $$$a_1, a_2, \ldots, a_n$$$ was guessed;  array $$$a$$$ was written to array $$$b$$$, i.e. $$$b_i = a_i$$$ ($$$1 \le i \le n$$$);  The $$$(n+1)$$$-th element of the array $$$b$$$ is the sum of the numbers in the array $$$a$$$, i.e. $$$b_{n+1} = a_1+a_2+\ldots+a_n$$$;  The $$$(n+2)$$$-th element of the array $$$b$$$ was written some number $$$x$$$ ($$$1 \le x \le 10^9$$$), i.e. $$$b_{n+2} = x$$$; The  array $$$b$$$ was shuffled. For example, the array $$$b=[2, 3, 7, 12 ,2]$$$ it could be obtained in the following ways:   $$$a=[2, 2, 3]$$$ and $$$x=12$$$;  $$$a=[3, 2, 7]$$$ and $$$x=2$$$. For the given array $$$b$$$, find any array $$$a$$$ that could have been guessed initially.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second row of each test case contains $$$n+2$$$ integers $$$b_1, b_2, \ldots, b_{n+2}$$$ ($$$1 \le b_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output:    "-1", if the array $$$b$$$ could not be obtained from any array $$$a$$$;  $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, otherwise.  If there are several arrays of $$$a$$$, you can output any.

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

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

  while(t--) {
    long n = readln.chomp.to!long;
    long[] b = readln.split.map!(to!long).array;

    b.sort;

    long maxima = b[$-1];
    long cum = sum(b[0 .. $-1]);

    int x = -1;
    for(int i = 0; i < n + 1; ++i) {
      if(cum - b[i] == maxima) {
        x = i;
        break;
      }
    }

    if(x != -1) {
      b = b.remove(x);
      writef("%(%d %)\n", b[0 .. $-1]);
      continue;
    }

    cum = sum(b[0 .. $-2]);
    if(cum == b[$-2])
      writef("%(%d %)\n", b[0 .. $-2]);
    else
      writeln("-1");
  }
}

// Vicfred
// https://codeforces.com/contest/1512/problem/D
// greedy
import std.algorithm;
import std.array;
import std.conv;
import std.range;
import std.stdio;
import std.string;

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

while(t--) {
    long n = readln.chomp.to!long;
    long[] b = readln.split.map!(to!long).array;

    b.sort;

    long maxima = b[$ - 1];
    long cum = sum(b[0..$ - 1]);

    long x = -1L;
    for(uint i = 0L; i < n + 1L; ++i) {
        if(cum - b[i] == maxima) {
            x = b[i];
            b[i] = -1;
            break;
        }
    }

    if(x != -1L) {
        for(uint i = 0; i < n + 1L; ++i) {
            if(b[i] == -1L) {
                continue;
            }
            writef("%s ", b[i]);
        }
        "".writeln;
        continue;
    }

    maxima = b[$ - 2];
    cum = sum(b[0..$ - 2]);
    if(cum == maxima) {
        for(uint i = 0; i < n; i++) {
            writef("%s ", b[i]);
        }
        "".writeln;
    } else {
        "-1".writeln;
    }
}
}

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

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

  while(t--) {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;

    b.sort;

    int maxima = b[$-1];
    int cum = sum(b[0 .. $-1]);

    int x = -1;
    for(int i = 0; i < n + 1; ++i) {
      if(cum - b[i] == maxima) {
        x = i;
        break;
      }
    }

    if(x != -1) {
      b = b.remove(x);
      writef("%(%d %)\n", b[0 .. $-1]);
      continue;
    }

    cum = sum(b[0 .. $-2]);
    if(cum == b[$-2])
      writef("%(%d %)\n", b[0 .. $-2]);
    else
      writeln("-1");
  }
}

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

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

  while(t--) {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;

    b.sort;

    int maxima = b[$-1];
    int cum = sum(b[0 .. $-1]);

    int x = -1;
    for(int i = 0; i < n - 1; ++i) {
      if(cum - b[i] == maxima) {
        x = i;
        break;
      }
    }

    if(x != -1) {
      b = b.remove(x);
      writef("%(%d %)\n", b[0 .. $-1]);
      continue;
    }

    cum = sum(b[0 .. $-2]);
    if(cum == b[$-2])
      writef("%(%d %)\n", b[0 .. $-2]);
    else
      writeln("-1");
  }
}

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

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

  while(t--) {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;

    b.sort;

    int maxima = b[$-1];
    int cum = sum(b[0 .. $-1]);

    int x = -1;
    for(int i = 0; i < n - 1; ++i) {
      if(cum - b[i] == maxima) {
        x = i;
        break;
      }
    }

    if(x != -1) {
      b = b.remove(x);
      writef("%(%d %)\n", b[0 .. $-1]);
      continue;
    }

    cum = sum(b[0 .. $-2]);
    if(cum + b[$-1] == b[$-2])
      writef("%(%d %)\n", b[0 .. $-2]);
    else
      writeln("-1");
  }
}

// Vicfred
// https://codeforces.com/contest/1512/problem/D
// greedy
import std.algorithm;
import std.array;
import std.conv;
import std.range;
import std.stdio;
import std.string;

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

while(t--) {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;

    b.sort;

    int maxima = b[$ - 1];
    int cum = sum(b[0..$ - 1]);

    int x = -1;
    for(int i = 0; i < n + 1; ++i) {
        if(cum - b[i] == maxima) {
            x = b[i];
            b[i] = -1;
            break;
        }
    }

    if(x != -1) {
        for(int i = 0; i < n + 1; ++i) {
            if(b[i] == -1) {
                continue;
            }
            writef("%s ", b[i]);
        }
        "".writeln;
        continue;
    }

    maxima = b[$ - 2];
    cum = sum(b[0..$ - 2]);
    if(cum == maxima) {
        for(int i = 0; i < n; i++) {
            writef("%s ", b[i]);
        }
        "".writeln;
    } else {
        "-1".writeln;
    }
}
}

// Vicfred
// https://codeforces.com/contest/1512/problem/D
// greedy
import std.algorithm;
import std.array;
import std.conv;
import std.range;
import std.stdio;
import std.string;

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

while(t--) {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;

    b.sort;

    int maxima = b[$ - 1];
    int cum = sum(b[0..$ - 1]);

    int x = -1;
    for(int i = 0; i < n - 1; ++i) {
        if(cum - b[i] == maxima) {
            x = b[i];
            b[i] = -1;
            break;
        }
    }

    if(x != -1) {
        for(int i = 0; i < n + 1; ++i) {
            if(b[i] == -1) {
                continue;
            }
            writef("%s ", b[i]);
        }
        "".writeln;
        continue;
    }

    maxima = b[$ - 2];
    cum = sum(b[0..$ - 2]);
    if(cum == maxima) {
        for(int i = 0; i < n; i++) {
            writef("%s ", b[i]);
        }
        "".writeln;
    } else {
        "-1".writeln;
    }
}
}

// Vicfred
// https://codeforces.com/contest/1512/problem/D
// greedy
import std.algorithm;
import std.array;
import std.conv;
import std.range;
import std.stdio;
import std.string;

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

while(t--) {
    int n = readln.chomp.to!int;
    int[] b = readln.split.map!(to!int).array;

    b.sort;

    int maxima = b[$ - 1];
    int cum = sum(b[0..$ - 1]);

    int x = -1;
    for(int i = 0; i < n - 1; ++i) {
        if(cum - b[i] == maxima) {
            x = b[i];
            b[i] = -1;
            break;
        }
    }

    if(x != -1) {
        for(int i = 0; i < n + 1; ++i) {
            if(b[i] == -1) {
                continue;
            }
            writef("%s ", b[i]);
        }
        "".writeln;
        continue;
    }

    maxima = b[$ - 2];
    cum = sum(b[0..$ - 2]);
    if(cum == maxima) {
        b[0.. $ - 2].writeln;
    } else {
        "-1".writeln;
    }
}
}


There is a river of width $$$n$$$. The left bank of the river is cell $$$0$$$ and the right bank is cell $$$n + 1$$$ (more formally, the river can be represented as a sequence of $$$n + 2$$$ cells numbered from $$$0$$$ to $$$n + 1$$$). There are also $$$m$$$ wooden platforms on a river, the $$$i$$$-th platform has length $$$c_i$$$ (so the $$$i$$$-th platform takes $$$c_i$$$ consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed $$$n$$$.You are standing at $$$0$$$ and want to reach $$$n+1$$$ somehow. If you are standing at the position $$$x$$$, you can jump to any position in the range $$$[x + 1; x + d]$$$. However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if $$$d=1$$$, you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells $$$0$$$ and $$$n+1$$$ belong to wooden platforms.You want to know if it is possible to reach $$$n+1$$$ from $$$0$$$ if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping).For example, if $$$n=7$$$, $$$m=3$$$, $$$d=2$$$ and $$$c = [1, 2, 1]$$$, then one of the ways to reach $$$8$$$ from $$$0$$$ is follow:    The first example: $$$n=7$$$.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$d$$$ ($$$1 \le n, m, d \le 1000, m \le n$$$) — the width of the river, the number of platforms and the maximum distance of your jump, correspondingly. The second line of the input contains $$$m$$$ integers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le n, \sum\limits_{i=1}^{m} c_i \le n$$$), where $$$c_i$$$ is the length of the $$$i$$$-th platform.

If it is impossible to reach $$$n+1$$$ from $$$0$$$, print NO in the first line. Otherwise, print YES in the first line and the array $$$a$$$ of length $$$n$$$ in the second line — the sequence of river cells (excluding cell $$$0$$$ and cell $$$n + 1$$$). If the cell $$$i$$$ does not belong to any platform, $$$a_i$$$ should be $$$0$$$. Otherwise, it should be equal to the index of the platform ($$$1$$$-indexed, platforms are numbered from $$$1$$$ to $$$m$$$ in order of input) to which the cell $$$i$$$ belongs. Note that all $$$a_i$$$ equal to $$$1$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_1$$$, all $$$a_i$$$ equal to $$$2$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_2$$$, ..., all $$$a_i$$$ equal to $$$m$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_m$$$. The leftmost position of $$$2$$$ in $$$a$$$ should be greater than the rightmost position of $$$1$$$, the leftmost position of $$$3$$$ in $$$a$$$ should be greater than the rightmost position of $$$2$$$, ..., the leftmost position of $$$m$$$ in $$$a$$$ should be greater than the rightmost position of $$$m-1$$$. See example outputs for better understanding.

NoteConsider the first example: the answer is $$$[0, 1, 0, 2, 2, 0, 3]$$$. The sequence of jumps you perform is $$$0 \rightarrow 2 \rightarrow 4 \rightarrow 5 \rightarrow 7 \rightarrow 8$$$.Consider the second example: it does not matter how to place the platform because you always can jump from $$$0$$$ to $$$11$$$.Consider the third example: the answer is $$$[0, 0, 0, 0, 1, 1, 0, 0, 0, 0]$$$. The sequence of jumps you perform is $$$0 \rightarrow 5 \rightarrow 6 \rightarrow 11$$$.

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

void main()
{
    auto v = readln.chomp.split.map!(to!int);
    auto n = v[0], m = v[1], d = v[2];
    auto c = readln.chomp.split.map!(to!int).array;

    if ((d-1) * (m+1) + c.sum < n) {
        writeln("No");
        return;
    }

    auto ans = new int[] (n);
    ans[] = 0;
    int sm = c.sum;
    int lst = 0;
    foreach (i; 0 .. m) {
        int cur = max(lst, n - sm - (m - i) * (d - 1));
        foreach (j; cur .. cur + c[i]) {
            ans[j] = i+1;
        }

        sm -= c[i];
        lst = cur + c[i];
    }

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


The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem.  One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of hi centimeters above the floor of the house, its mass is mi. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most x centimeter high jumps. When Om Nom eats a candy of mass y, he gets stronger and the height of his jump increases by y centimeters.What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?

The first line contains two integers, n and x (1 ≤ n, x ≤ 2000) — the number of sweets Evan has and the initial height of Om Nom's jump.  Each of the following n lines contains three integers ti, hi, mi (0 ≤ ti ≤ 1; 1 ≤ hi, mi ≤ 2000) — the type, height and the mass of the i-th candy. If number ti equals 0, then the current candy is a caramel drop, otherwise it is a fruit drop.

Print a single integer — the maximum number of candies Om Nom can eat.

NoteOne of the possible ways to eat 4 candies is to eat them in the order: 1, 5, 3, 2. Let's assume the following scenario:  Initially, the height of Om Nom's jump equals 3. He can reach candies 1 and 2. Let's assume that he eats candy 1. As the mass of this candy equals 4, the height of his jump will rise to 3 + 4 = 7.  Now Om Nom can reach candies 2 and 5. Let's assume that he eats candy 5. Then the height of his jump will be 7 + 5 = 12.  At this moment, Om Nom can reach two candies, 2 and 3. He won't eat candy 2 as its type matches the type of the previously eaten candy. Om Nom eats candy 3, the height of his jump is 12 + 3 = 15.  Om Nom eats candy 2, the height of his jump is 15 + 1 = 16. He cannot reach candy 4.

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, x;
	while (readf (" %s %s", &n, &x) > 0)
	{
		alias pair = Tuple !(int, "h", int, "m");
		pair [] [2] a;
		foreach (i; 0..n)
		{
			int t, h, m;
			readf (" %s %s %s", &t, &h, &m);
			a[t] ~= pair (h, m);
		}
		sort (a[0]);
		sort (a[1]);

		long res = 0;
		foreach (s; 0..2)
		{
			pair [] [2] b;
			b[0] = a[0].dup;
			b[1] = a[1].dup;
			long cur = 0;
			int cx = x;
			int t = s;
			int j;
			int m;
			while (true)
			{
				m = NA;
				j = NA;
				foreach (i, p; b[t])
				{
					if (p != pair (NA, NA) &&
					    p.h <= cx &&
					    m < p.m)
					{
						m = p.m;
						j = i;
					}
				}
				if (j == NA)
				{
					break;
				}
				cx += b[t][j].m;
				b[t][j] = pair (NA, NA);
				cur++;
				t ^= 1;
			}
			res = max (res, cur);
		}

		writeln (res);
	}
}

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

unittest{
  assert(solve(1) == [1], "Teste 1");
}

long[] solve(long a){
  debug(1) writefln("%s",a);
  return [1];
}

class Candy{
  struct CandyV{
    int id;
    int t;
    int h;
    int m;
    bool ate;
  }
  CandyV cv;

  this(int i, int t, int h, int m, bool ate){
    cv = CandyV(i,t,h,m,ate);
  }

  bool canEat(int j, int t){
    return (cv.t == t && cv.ate == false && cv.h <= j);
  }

  override string toString(){
    return text(cv);
  }
}

void main(){
  int c,j;
  readf("%s %s\n",&c,&j);
  immutable int fj = j;

  Candy[] cnds;
  for(int i = 0; i < c; i++){
    int t,h,m;
    readf("%s %s %s\n",&t,&h,&m);
    Candy cc = new Candy(i,t,h,m,false);
    cnds ~= cc;
  }

  Candy[] byMaxM = cnds.dup;
  sort!((a,b){return a.cv.m > b.cv.m;})(byMaxM);
  //writeln(byMaxM);

  //Candy[] byMinH = cnds.dup;
  //sort!((a,b){return a.cv.h < b.cv.h;})(byMinH);
  //writeln(byMinH);

  //start with 1

  //start with 0
  int type = 0;
  int cnt0 = 0;
  for(int i = 0; i < c; i++){
    if(byMaxM[i].canEat(j,type % 2)){
      //writeln(j);
      j += byMaxM[i].cv.m;
      byMaxM[i].cv.ate = true;
      type += 1;
      cnt0++;
      i = -1;
    }
  }

  foreach(ccc;cnds){
    ccc.cv.ate = false;
  }
  j = fj;
  //writeln();

  type = 1;
  int cnt1 = 0;
  for(int i = 0; i < c; i++){
    if(byMaxM[i].canEat(j,type % 2)){
      //writeln(j);
      j += byMaxM[i].cv.m;
      byMaxM[i].cv.ate = true;
      type += 1;
      cnt1++;
      i = -1;
    }
  }

  // writeln(cnt0);
  // writeln(cnt1);
  writeln(max(cnt0,cnt1));
}

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

void main ()
{
	int n, x;
	while (readf (" %s %s", &n, &x) > 0)
	{
		alias pair = Tuple !(int, "h", int, "m");
		pair [] [2] a;
		foreach (i; 0..n)
		{
			int t, h, m;
			readf (" %s %s %s", &t, &h, &m);
			a[t] ~= pair (h, m);
		}
		sort (a[0]);
		sort (a[1]);

		long res = 0;
		foreach (s; 0..2)
		{
			long cur = 0;
			int cx = x;
			int p = 0;
			int t = s;
			while (true)
			{
				if (a[t].length <= p || a[t][p].h > cx)
				{
					break;
				}
				cx += a[t][p].m;
				cur++;
				t ^= 1;
				if (a[t].length <= p || a[t][p].h > cx)
				{
					break;
				}
				cx += a[t][p].m;
				cur++;
				t ^= 1;
				p++;
			}
			res = max (res, cur);
		}

		writeln (res);
	}
}

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

unittest{
  assert(solve(1) == [1], "Teste 1");
}

long[] solve(long a){
  debug(1) writefln("%s",a);
  return [1];
}

class Candy{
  struct CandyV{
    int id;
    int t;
    int h;
    int m;
    bool ate;
  }
  CandyV cv;

  this(int i, int t, int h, int m, bool ate){
    cv = CandyV(i,t,h,m,ate);
  }

  bool canEat(int j, int t){
    return (cv.t == t && cv.ate == false && cv.h <= j);
  }

  override string toString(){
    return text(cv);
  }
}

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

  Candy[] cnds;
  for(int i = 0; i < c; i++){
    int t,h,m;
    readf("%s %s %s\n",&t,&h,&m);
    Candy cc = new Candy(i,t,h,m,false);
    cnds ~= cc;
  }

  Candy[] byMaxM = cnds.dup;
  sort!((a,b){return a.cv.m > b.cv.m;})(byMaxM);
  //writeln(byMaxM);

  Candy[] byMinH = cnds.dup;
  sort!((a,b){return a.cv.h < b.cv.h;})(byMinH);
  //writeln(byMinH);

  //start with 1

  //start with 0
  int type = 0;
  int cnt0 = 0;
  for(int i = 0; i < c; i++){
    if(cnds[i].canEat(j,type % 2)){
      j += cnds[i].cv.m;
      type += 1;
      cnt0++;
    }
  }

  foreach(ccc;cnds){
    ccc.cv.ate = false;
  }

  type = 1;
  int cnt1 = 0;
  for(int i = 0; i < c; i++){
    if(cnds[i].canEat(j,type % 2)){
      j += cnds[i].cv.m;
      type += 1;
      cnt1++;
    }
  }

  writeln(max(cnt0,cnt1));
}

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

unittest{
  assert(solve(1) == [1], "Teste 1");
}

long[] solve(long a){
  debug(1) writefln("%s",a);
  return [1];
}

class Candy{
  struct CandyV{
    int id;
    int t;
    int h;
    int m;
    bool ate;
  }
  CandyV cv;

  this(int i, int t, int h, int m, bool ate){
    cv = CandyV(i,t,h,m,ate);
  }

  bool canEat(int j, int t){
    return (cv.t == t && cv.ate == false && cv.h <= j);
  }

  override string toString(){
    return text(cv);
  }
}

void main(){
  int c,j;
  readf("%s %s\n",&c,&j);
  immutable int fj = j;

  Candy[] cnds;
  for(int i = 0; i < c; i++){
    int t,h,m;
    readf("%s %s %s\n",&t,&h,&m);
    Candy cc = new Candy(i,t,h,m,false);
    cnds ~= cc;
  }

  Candy[] byMaxM = cnds.dup;
  sort!((a,b){return a.cv.m > b.cv.m;})(byMaxM);
  //writeln(byMaxM);

  //Candy[] byMinH = cnds.dup;
  //sort!((a,b){return a.cv.h < b.cv.h;})(byMinH);
  //writeln(byMinH);

  //start with 1

  //start with 0
  int type = 0;
  int cnt0 = 0;
  for(int i = 0; i < c; i++){
    if(byMaxM[i].canEat(j,type % 2)){
      //writeln(j);
      j += byMaxM[i].cv.m;
      byMaxM[i].cv.ate = true;
      type += 1;
      cnt0++;
      i = 0;
    }
  }

  foreach(ccc;cnds){
    ccc.cv.ate = false;
  }
  j = fj;
  //writeln();

  type = 1;
  int cnt1 = 0;
  for(int i = 0; i < c; i++){
    if(byMaxM[i].canEat(j,type % 2)){
      //writeln(j);
      j += byMaxM[i].cv.m;
      byMaxM[i].cv.ate = true;
      type += 1;
      cnt1++;
      i = 0;
    }
  }

  // writeln(cnt0);
  // writeln(cnt1);
  writeln(max(cnt0,cnt1));
}


There are n piles of pebbles on the table, the i-th pile contains ai pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.In other words, let's say that bi, c is the number of pebbles of color c in the i-th pile. Then for any 1 ≤ c ≤ k, 1 ≤ i, j ≤ n the following condition must be satisfied |bi, c - bj, c| ≤ 1. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then bi, c is considered to be zero.

The first line of the input contains positive integers n and k (1 ≤ n, k ≤ 100), separated by a space — the number of piles and the number of colors respectively. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) denoting number of pebbles in each of the piles.

If there is no way to paint the pebbles satisfying the given condition, output "NO" (without quotes) . Otherwise in the first line output "YES" (without quotes). Then n lines should follow, the i-th of them should contain ai space-separated integers. j-th (1 ≤ j ≤ ai) of these integers should be equal to the color of the j-th pebble in the i-th pile. If there are several possible answers, you may output any of them.


You are given a string $$$s=s_1s_2\dots s_n$$$ of length $$$n$$$, which only contains digits $$$1$$$, $$$2$$$, ..., $$$9$$$.A substring $$$s[l \dots r]$$$ of $$$s$$$ is a string $$$s_l s_{l + 1} s_{l + 2} \ldots s_r$$$. A substring $$$s[l \dots r]$$$ of $$$s$$$ is called even if the number represented by it is even. Find the number of even substrings of $$$s$$$. Note, that even if some substrings are equal as strings, but have different $$$l$$$ and $$$r$$$, they are counted as different substrings.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 65000$$$) — the length of the string $$$s$$$. The second line contains a string $$$s$$$ of length $$$n$$$. The string $$$s$$$ consists only of digits $$$1$$$, $$$2$$$, ..., $$$9$$$.

Print the number of even substrings of $$$s$$$.

NoteIn the first example, the $$$[l, r]$$$ pairs corresponding to even substrings are:   $$$s[1 \dots 2]$$$ $$$s[2 \dots 2]$$$ $$$s[1 \dots 4]$$$ $$$s[2 \dots 4]$$$ $$$s[3 \dots 4]$$$ $$$s[4 \dots 4]$$$ In the second example, all $$$10$$$ substrings of $$$s$$$ are even substrings. Note, that while substrings $$$s[1 \dots 1]$$$ and $$$s[2 \dots 2]$$$ both define the substring "2", they are still counted as different substrings.

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;

    long ans = 0;
    foreach (i; 0..N) {
        if ((S[i] - '0') % 2 == 0) {
            ans += (i + 1);
        }
    }

    ans.writeln;
}


Eshag has an array $$$a$$$ consisting of $$$n$$$ integers.Eshag can perform the following operation any number of times: choose some subsequence of $$$a$$$ and delete every element from it which is strictly larger than $$$AVG$$$, where $$$AVG$$$ is the average of the numbers in the chosen subsequence.For example, if $$$a = [1 , 4 , 3 , 2 , 4]$$$ and Eshag applies the operation to the subsequence containing $$$a_1$$$, $$$a_2$$$, $$$a_4$$$ and $$$a_5$$$, then he will delete those of these $$$4$$$ elements which are larger than $$$\frac{a_1+a_2+a_4+a_5}{4} = \frac{11}{4}$$$, so after the operation, the array $$$a$$$ will become $$$a = [1 , 3 , 2]$$$.Your task is to find the maximum number of elements Eshag can delete from the array $$$a$$$ by applying the operation described above some number (maybe, zero) times.A sequence $$$b$$$ is a subsequence of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements.

The first line contains an integer $$$t$$$ $$$(1\le t\le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1\le n\le 100)$$$ — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1\le a_i \le 100)$$$ — the elements of the array $$$a$$$.

For each test case print a single integer — the maximum number of elements Eshag can delete from the array $$$a$$$.

NoteConsider the first test case.Initially $$$a = [1, 1, 1, 2, 2, 3]$$$.In the first operation, Eshag can choose the subsequence containing $$$a_1$$$, $$$a_5$$$ and $$$a_6$$$, their average is equal to $$$\frac{a_1 + a_5 + a_6}{3} = \frac{6}{3} = 2$$$. So $$$a_6$$$ will be deleted.After this $$$a = [1, 1, 1, 2, 2]$$$.In the second operation, Eshag can choose the subsequence containing the whole array $$$a$$$, the average of all its elements is equal to $$$\frac{7}{5}$$$. So $$$a_4$$$ and $$$a_5$$$ will be deleted.After this $$$a = [1, 1, 1]$$$.In the second test case, Eshag can't delete any element.

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array;
        auto m = arr.minElement;

        writeln(arr.filter!(i => i > m).count());
    }
}

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array;
        auto m = arr.minElement;
        double avg = arr.mean;
        int res = 0;
        foreach(i; arr)
        {
            if(i > m)
            {
                res++;
            }
        }

        writeln(res);
    }
}

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

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

while(t--) {
    int n;
    readf("%s\n", &n);
    int[] a = readln.split.map!(to!int).array;
    int minima = a.minElement;
    int ans = 0;
    foreach(i; a) {
        if(i != minima) {
            ans += 1;
        }
    }
    ans.writeln;
}
}

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

void main() {
    foreach(t; 0 .. to!int(readln.strip)) {
        int n = to!int(readln.strip);
        auto ar = readln.split.map!(to!int).array.sort.group;
        writeln(n-ar.array[0][1]);
    }
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
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 long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;

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

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

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array;

        double avg = arr.mean;
        int res = 0;
        foreach(i; arr)
        {
            if(i > avg)
            {
                res++;
            }
        }

        writeln(res);
    }
}

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array.sort.array;

        int res = 0;
        int cur = 0;

        foreach(i; arr)
        {
            if(i != cur)
            {
                cur = i;
                res++;
            }
        }

        if(res > 1)
            writeln(res);
        else writeln(0);
    }
}


One department of some software company has $$$n$$$ servers of different specifications. Servers are indexed with consecutive integers from $$$1$$$ to $$$n$$$. Suppose that the specifications of the $$$j$$$-th server may be expressed with a single integer number $$$c_j$$$ of artificial resource units.In order for production to work, it is needed to deploy two services $$$S_1$$$ and $$$S_2$$$ to process incoming requests using the servers of the department. Processing of incoming requests of service $$$S_i$$$ takes $$$x_i$$$ resource units.The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service $$$S_i$$$ is deployed using $$$k_i$$$ servers, then the load is divided equally between these servers and each server requires only $$$x_i / k_i$$$ (that may be a fractional number) resource units.Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services.

The first line contains three integers $$$n$$$, $$$x_1$$$, $$$x_2$$$ ($$$2 \leq n \leq 300\,000$$$, $$$1 \leq x_1, x_2 \leq 10^9$$$) — the number of servers that the department may use, and resource units requirements for each of the services. The second line contains $$$n$$$ space-separated integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 10^9$$$) — the number of resource units provided by each of the servers.

If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes). Otherwise print the word "Yes" (without the quotes).  In the second line print two integers $$$k_1$$$ and $$$k_2$$$ ($$$1 \leq k_1, k_2 \leq n$$$) — the number of servers used for each of the services. In the third line print $$$k_1$$$ integers, the indices of the servers that will be used for the first service. In the fourth line print $$$k_2$$$ integers, the indices of the servers that will be used for the second service. No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them.

NoteIn the first sample test each of the servers 1, 2 and 6 will will provide $$$8 / 3 = 2.(6)$$$ resource units and each of the servers 5, 4 will provide $$$16 / 2 = 8$$$ resource units.In the second sample test the first server will provide $$$20$$$ resource units and each of the remaining servers will provide $$$32 / 3 = 10.(6)$$$ resource units.

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

struct CI { int c, i; }

void main()
{
  int n, x1, x2; readV(n, x1, x2);
  int[] c; readA(n, c);

  auto ci = new CI[](n);
  foreach (i; 0..n) ci[i] = CI(c[i], i+1);
  auto cis = ci.sort!"a.c < b.c";

  auto r1 = calc(n, x1, x2, cis);
  if (r1[0] > 0) {
    put(r1[0], r1[1], r1[2], r1[3]);
    return;
  }

  auto r2 = calc(n, x2, x1, cis);
  if (r2[0] > 0) {
    put(r2[1], r2[0], r2[3], r2[2]);
    return;
  }

  writeln("No");
}

auto calc(R)(int n, int x1, int x2, R cis)
{
  auto calcK2()
  {
    foreach (k2; 1..n) {
      if (cis[$-k2].c >= (x2+k2-1)/k2) return k2;
    }
    return 0;
  }

  auto k2 = calcK2;
  if (k2 == 0) return tuple(0, 0, cast(int[])[], cast(int[])[]);

  foreach (k1; 1..n) {
    auto r = cis.upperBound(CI((x1+k1-1)/k1-1, 0));
    if (r.length >= k1+k2) {
      auto s = r.map!"a.i".array;
      return tuple(k1, k2, s[0..k1], s[$-k2..$]);
    }
  }

  return tuple(0, 0, cast(int[])[], cast(int[])[]);
}

auto put(int k1, int k2, int[] r1, int[] r2)
{
  writeln("Yes");
  writeln(k1, " ", k2);

  foreach (i; 0..k1) {
    write(r1[i]);
    if (i < k1-1) write(" ");
  }
  writeln;

  foreach (i; 0..k2) {
    write(r2[i]);
    if (i < k2-1) write(" ");
  }
}

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;
    int[2] x;
    readf("%s %s %s", &n, &x[0], &x[1]);
    readln;

    auto arr = readln.chomp.split.map!(to!int).enumerate(1).array;
    arr.sort!"a[1] > b[1]";

    debug { arr.writeln; }

    auto ans = new int[][] (2);

    bool go(int idx, int x1, int x2) {
        int need = (x[x1] + arr[idx].value - 1) / arr[idx].value;

        int lft = idx - need;
        if (lft < 0) { return false; }

        long totalLeft = arr[lft].value.to!long * (lft + 1);

        if (totalLeft < x[x2]) { return false; }

        foreach (i; 0 .. lft+1) { ans[x2] ~= arr[i].index; }
        foreach (i; lft+1 .. idx+1) { ans[x1] ~= arr[i].index; }

        return true;
    }

    bool found = false;
    foreach (i; 1 .. n) {
        found = go(i, 0, 1) || go(i, 1, 0);
        if (found) { break; }
    }

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

    writeln("Yes");
    writeln(ans[0].length, ' ', ans[1].length);
    foreach (i; 0 .. 2) {
        ans[i].writefln!"%(%s %)";
    }
}


You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have $$$n$$$ tiles in your hand. Each tile has an integer between $$$1$$$ and $$$m$$$ written on it.To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tiles are either all the same or consecutive. For example, $$$7, 7, 7$$$ is a valid triple, and so is $$$12, 13, 14$$$, but $$$2,2,3$$$ or $$$2,4,6$$$ are not. You can only use the tiles in your hand to form triples. Each tile can be used in at most one triple.To determine how close you are to the win, you want to know the maximum number of triples you can form from the tiles in your hand.

The first line contains two integers integer $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^6$$$) — the number of tiles in your hand and the number of tiles types. The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$), where $$$a_i$$$ denotes the number written on the $$$i$$$-th tile.

Print one integer: the maximum number of triples you can form.

NoteIn the first example, we have tiles $$$2, 3, 3, 3, 4, 4, 4, 5, 5, 6$$$. We can form three triples in the following way: $$$2, 3, 4$$$; $$$3, 4, 5$$$; $$$4, 5, 6$$$. Since there are only $$$10$$$ tiles, there is no way we could form $$$4$$$ triples, so the answer is $$$3$$$.In the second example, we have tiles $$$1$$$, $$$2$$$, $$$3$$$ ($$$7$$$ times), $$$4$$$, $$$5$$$ ($$$2$$$ times). We can form $$$3$$$ triples as follows: $$$1, 2, 3$$$; $$$3, 3, 3$$$; $$$3, 4, 5$$$. One can show that forming $$$4$$$ triples is not possible.

// wtf, IL on compilation? trying again 001
import std.algorithm;
import std.conv;
import std.exception;
import std.range;
import std.stdio;
import std.string;

immutable int limit = 8;
immutable int infinity = int.max / 4;

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto c = new int [m + 4];
		readln;
		foreach (x; readln.splitter.map !(to !(int)))
		{
			enforce (1 <= x && x <= m);
			c[x] += 1;
		}

		long res = 0;
		foreach (ref w; c)
		{
			while (w >= limit)
			{
				w -= 3;
				res += 1;
			}
		}

		int [limit] [limit] [2] f;
		int b = 0;
		foreach (ref g; f[b][])
		{
			g[] = -infinity;
		}
		f[b][0][0] = 0;

		foreach (ref w; c)
		{
			b ^= 1;
			foreach (ref g; f[b][])
			{
				g[] = -infinity;
			}
			foreach_reverse (u; 0..limit)
			{
				foreach_reverse (v; 0..limit)
				{
					auto cur = f[!b][u][v];
					if (cur < 0)
					{
						continue;
					}
					if (u >= 3)
					{
						f[!b][u - 3][v] =
						    max (f[!b][u - 3][v],
						    cur + 1);
					}
					if (v >= 3)
					{
						f[!b][u][v - 3] =
						    max (f[!b][u][v - 3],
						    cur + 1);
					}
					int z = min (u, v, w);
					foreach (y; 0..z + 1)
					{
						f[b][v - y][w - y] =
						    max (f[b][v - y][w - y],
						    cur + y);
					}
				}
			}
		}
		writeln (res + f[b][0][0]);
	}
}

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

immutable int limit = 6;
immutable int infinity = int.max / 4;

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto c = new int [m + 4];
		readln;
		foreach (x; readln.splitter.map !(to !(int)))
		{
			c[x] += 1;
		}

		long res = 0;
		foreach (i; 0..m + 1)
		{
			while (c[i] >= limit)
			{
				c[i] -= 3;
				res += 1;
			}
		}

		int [limit] [limit] [2] f;
		int b = 0;
		foreach (ref g; f[b][])
		{
			g[] = -infinity;
		}
		f[b][0][0] = 0;

		foreach (ref w; c)
		{
			b ^= 1;
			foreach (ref g; f[b][])
			{
				g[] = -infinity;
			}
			foreach_reverse (u; 0..limit)
			{
				foreach_reverse (v; 0..limit)
				{
					auto cur = f[!b][u][v];
					if (cur < 0)
					{
						continue;
					}
					if (u >= 3)
					{
						f[!b][u - 3][v] =
						    max (f[!b][u - 3][v],
						    cur + 1);
					}
					if (v >= 3)
					{
						f[!b][u][v - 3] =
						    max (f[!b][u][v - 3],
						    cur + 1);
					}
					int z = min (u, v, w);
					foreach (y; 0..z + 1)
					{
						f[b][v - y][w - y] =
						    max (f[b][v - y][w - y],
						    cur + y);
					}
				}
			}
		}
		writeln (res + f[b][0][0]);
	}
}


You are walking with your dog, and now you are at the promenade. The promenade can be represented as an infinite line. Initially, you are in the point $$$0$$$ with your dog. You decided to give some freedom to your dog, so you untied her and let her run for a while. Also, you watched what your dog is doing, so you have some writings about how she ran. During the $$$i$$$-th minute, the dog position changed from her previous position by the value $$$a_i$$$ (it means, that the dog ran for $$$a_i$$$ meters during the $$$i$$$-th minute). If $$$a_i$$$ is positive, the dog ran $$$a_i$$$ meters to the right, otherwise (if $$$a_i$$$ is negative) she ran $$$a_i$$$ meters to the left.During some minutes, you were chatting with your friend, so you don't have writings about your dog movement during these minutes. These values $$$a_i$$$ equal zero.You want your dog to return to you after the end of the walk, so the destination point of the dog after $$$n$$$ minutes should be $$$0$$$.Now you are wondering: what is the maximum possible number of different integer points of the line your dog could visit on her way, if you replace every $$$0$$$ with some integer from $$$-k$$$ to $$$k$$$ (and your dog should return to $$$0$$$ after the walk)? The dog visits an integer point if she runs through that point or reaches in it at the end of any minute. Point $$$0$$$ is always visited by the dog, since she is initially there.If the dog cannot return to the point $$$0$$$ after $$$n$$$ minutes regardless of the integers you place, print -1.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 3000; 1 \le k \le 10^9$$$) — the number of minutes and the maximum possible speed of your dog during the minutes without records. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ is the number of meters your dog ran during the $$$i$$$-th minutes (to the left if $$$a_i$$$ is negative, to the right otherwise). If $$$a_i = 0$$$ then this value is unknown and can be replaced with any integer from the range $$$[-k; k]$$$.

If the dog cannot return to the point $$$0$$$ after $$$n$$$ minutes regardless of the set of integers you place, print -1. Otherwise, print one integer — the maximum number of different integer points your dog could visit if you fill all the unknown values optimally and the dog will return to the point $$$0$$$ at the end of the walk.

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

immutable long NA = -1;

long solve (int [] a0, int n, int k)
{
	auto a = a0.dup;
	auto total = sum (a, 0L);
	auto zeroes = a.count (0);
	if (zeroes * 1L * k < abs (total))
	{
		return NA;
	}
	int lo = 0;
	int hi = n - 1;
	while (zeroes > 0)
	{
		while (a[lo] != 0)
		{
			lo += 1;
		}
		while (a[hi] != 0)
		{
			hi -= 1;
		}
		debug {writeln (lo, " ", hi, " ", a, " ", total);}
		if (total <= -k || (zeroes > 1 && total <= 0))
		{
			a[lo] = +k;
			lo += 1;
			total += k;
			zeroes -= 1;
		}
		else if (total >= +k || (zeroes > 1 && total >= 0))
		{
			a[hi] = -k;
			hi -= 1;
			total -= k;
			zeroes -= 1;
		}
		else
		{
			assert (zeroes == 1);
			assert (abs (total) <= k);
			a[lo] = -total.to !(int);
			lo += 1;
			total -= total;
			zeroes -= 1;
		}
	}
	assert (total == 0);

	debug {writeln (a);}
	long x = 0;
	long y = 0;
	long z = 0;
	foreach (ref c; a)
	{
		z += c;
		x = min (x, z);
		y = max (y, z);
	}
	assert (z == 0);
	return y - x + 1;
}

void main ()
{
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		long res = NA;
		foreach (i; 0..n)
		{
			res = max (res, solve (a, n, k));
			a[] *= -1;
			res = max (res, solve (a, n, k));
			a[] *= -1;
			bringToFront (a[0..1], a[1..$]);
		}
		writeln (res);
	}
}

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

immutable long NA = -1;

long solve (int [] a0, int n, int k)
{
	auto a = a0.dup;
	auto total = sum (a, 0L);
	auto zeroes = a.count (0);
	if (zeroes * 1L * k < abs (total))
	{
		return NA;
	}
	int lo = 0;
	int hi = n - 1;
	while (zeroes > 0)
	{
		while (a[lo] != 0)
		{
			lo += 1;
		}
		while (a[hi] != 0)
		{
			hi -= 1;
		}
		debug {writeln (lo, " ", hi, " ", a, " ", total);}
		if (total <= -k || (zeroes > 1 && total <= 0))
		{
			a[lo] = +k;
			lo += 1;
			total += k;
			zeroes -= 1;
		}
		else if (total >= +k || (zeroes > 1 && total >= 0))
		{
			a[hi] = -k;
			hi -= 1;
			total -= k;
			zeroes -= 1;
		}
		else
		{
			assert (zeroes == 1);
			assert (abs (total) <= k);
			a[lo] = -total.to !(int);
			lo += 1;
			total -= total;
			zeroes -= 1;
		}
	}
	assert (total == 0);

	debug {writeln (a);}
	long x = 0;
	long y = 0;
	long z = 0;
	foreach (ref c; a)
	{
		z += c;
		x = min (x, z);
		y = max (y, z);
	}
	assert (z == 0);
	return y - x + 1;
}

void main ()
{
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		long res = 1;
		foreach (i; 0..n)
		{
			res = max (res, solve (a, n, k));
			a[] *= -1;
			res = max (res, solve (a, n, k));
			a[] *= -1;
			bringToFront (a[0..1], a[1..$]);
		}
		writeln (res);
	}
}


You are given a set of $$$n$$$ points in a 2D plane. No three points are collinear.A pentagram is a set of $$$5$$$ points $$$A,B,C,D,E$$$ that can be arranged as follows.  Note the length of the line segments don't matter, only that those particular intersections exist.Count the number of ways to choose $$$5$$$ points from the given set that form a pentagram.

The first line contains an integer $$$n$$$ ($$$5 \leq n \leq 300$$$) — the number of points. Each of the next $$$n$$$ lines contains two integers $$$x_i, y_i$$$ ($$$-10^6 \leq x_i,y_i \leq 10^6$$$) — the coordinates of the $$$i$$$-th point. It is guaranteed that no three points are collinear.

Print a single integer, the number of sets of $$$5$$$ points that form a pentagram.

NoteA picture of the first sample:  A picture of the second sample:  A picture of the third sample:

import std.conv, std.functional, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, std.numeric, std.range, 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 K = 5;

int N;
real[] X, Y;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      X = new real[N];
      Y = new real[N];
      foreach (i; 0 .. N) {
        X[i] = readReal();
        Y[i] = readReal();
      }

      Tuple!(real, int, int)[] edges;
      foreach (i; 0 .. N) foreach (j; 0 .. N) {
        if (i != j) {
          edges ~= tuple(atan2(Y[j] - Y[i], X[j] - X[i]), i, j);
        }
      }
      edges.sort;

      auto dp = new long[][][](K + 1, N, N);
      foreach (i; 0 .. N) {
        dp[0][i][i] = 1;
      }
      foreach (const ref edge; edges) {
        const j = edge[1], k = edge[2];
        foreach (t; 0 .. K) {
          foreach (i; 0 .. N) {
            dp[t + 1][i][k] += dp[t][i][j];
          }
        }
      }
      long ans;
      foreach (i; 0 .. N) {
        ans += dp[K][i][i];
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

/*
	Xmas Contest 2012
	Problem G: Galaxy View
	Solution
	O(N^3 log N)
*/

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

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

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

void prepare() {

}

class Solver : Thread {
	int caseId;
	this(int caseId) {
		this.caseId = caseId;
		super(&main);
	}
	void main() {
		try {
			run;
			stderr.writeln("DONE  Case #", caseId);
		} catch (Throwable e) {
			stderr.writeln("ERROR Case #", caseId, ": ", e.msg);
		} finally {
			stderr.flush;
		}
	}

	struct Pt {
		long x, y;
	}
	struct Entry {
		long x, y;
		int id;
	}

	int N;
	Pt[] P;
	long ans;

	void run() {
		long cnt1, cnt2;
		P.sort!"(a.x != b.x) ? (a.x < b.x) : (a.y < b.y)";
		foreach (i; 0 .. N) {
			Pt[] ps;
			foreach (j; i + 1 .. N) {
				ps ~= Pt(P[j].x - P[i].x, P[j].y - P[i].y);
			}
			ps.sort!"(a.x * b.y > a.y * b.x)";
			foreach (j; 0 .. ps.length) {
				Entry[] es;
				foreach (k; j + 1 .. ps.length) {
					es ~= Entry(ps[k].x - ps[j].x, ps[k].y - ps[j].y, k - j - 1);
				}
				es.sort!"(a.x * b.y < a.y * b.x)";
				int[] as = new int[es.length];
				foreach (k, e; es) {
					as[e.id] = k;
				}
				int[] bit = new int[es.length];
				void add(int pos) {
					for (int x = pos; x < es.length; x |= x + 1) {
						++bit[x];
					}
				}
				int cal(int pos) {
					int ret;
					for (int x = pos - 1; x >= 0; x = (x & x + 1) - 1) {
						ret += bit[x];
					}
					return ret;
				}
				foreach (a; as) {
					long m = cal(a);
					cnt1 += m;
					cnt2 += m * (m - 1) / 2;
					add(a);
				}
			}
		}
		long n = N;
		ans = n * (n - 1) * (n - 2) * (n - 3) * (n - 4) / 120 - (cnt1 * (n - 4) - cnt2 * 4) / 2 - cnt2;
	}

	void input() {
		N = readInt;
		P = new Pt[N];
		foreach (i; 0 .. N) {
			P[i].x = readLong;
			P[i].y = readLong;
		}
	}

	void output() {
		write(ans);
		stdout.rawWrite("\n");
		stdout.flush;
	}
}

void main(string[] args) {
	bool parallel = false;
	foreach (arg; args) if (arg == "-p") parallel = true;
	prepare;
	// auto solvers = new Solver[readInt];
	auto solvers = new Solver[1];
	foreach (caseId, ref solver; solvers) solver = new Solver(caseId + 1);
	if (parallel) {
		foreach (solver; solvers) solver.input, solver.start;
		foreach (solver; solvers) solver.join, solver.output;
	} else {
		foreach (caseId, solver; solvers) {
			solver.input;
			solver.run;
			solver.output;
			stderr.writeln("DONE  Case #", caseId + 1);
			stderr.flush;
		}
	}
}

import std.conv, std.functional, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, std.numeric, std.range, 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 K = 5;

int N;
real[] X, Y;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      X = new real[N];
      Y = new real[N];
      foreach (i; 0 .. N) {
        X[i] = readReal();
        Y[i] = readReal();
      }

      Tuple!(real, int, int)[] edges;
      foreach (i; 0 .. N) foreach (j; 0 .. N) {
        if (i != j) {
          edges ~= tuple(atan2(Y[j] - Y[i], X[j] - X[i]), i, j);
        }
      }
      edges.sort;

      auto dp = new long[][][](K + 1, N, N);
      foreach (i; 0 .. N) {
        dp[0][i][i] = 1;
      }
      foreach (edge; edges) {
        foreach (k; 0 .. K) {
          foreach (i; 0 .. N) {
            dp[k + 1][i][edge[2]] += dp[k][i][edge[1]];
          }
        }
      }
      long ans;
      foreach (i; 0 .. N) {
        ans += dp[K][i][i];
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are given an undirected tree of $$$n$$$ vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.How many nice edges are there in the given tree?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of vertices in the tree. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2$$$) — the colors of the vertices. $$$a_i = 1$$$ means that vertex $$$i$$$ is colored red, $$$a_i = 2$$$ means that vertex $$$i$$$ is colored blue and $$$a_i = 0$$$ means that vertex $$$i$$$ is uncolored. The $$$i$$$-th of the next $$$n - 1$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$v_i \ne u_i$$$) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.

Print a single integer — the number of nice edges in the given tree.

NoteHere is the tree from the first example:  The only nice edge is edge $$$(2, 4)$$$. Removing it makes the tree fall apart into components $$$\{4\}$$$ and $$$\{1, 2, 3, 5\}$$$. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices.Here is the tree from the second example:  Every edge is nice in it.Here is the tree from the third example:  Edge $$$(1, 3)$$$ splits the into components $$$\{1\}$$$ and $$$\{3, 2\}$$$, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge $$$(2, 3)$$$ splits the into components $$$\{1, 3\}$$$ and $$$\{2\}$$$, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0.

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

immutable int INF = 10L ^^ 9 + 23;

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

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

    auto g = new int[][] (n);
    foreach (_; 0 .. n-1) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        --u, --v;
        g[u] ~= v;
        g[v] ~= u;
    }

    int[2] tot;
    foreach (i; 0 .. 2) { tot[i] = c.count!(x => x == i+1).to!int; }

    Tuple!(int, int) dfs(int v, int fr, ref int ans) {
        auto cnt = tuple(0, 0);
        foreach (u; g[v]) {
            if (u == fr) { continue; }

            auto res = dfs(u, v, ans);
            cnt[0] += res[0];
            cnt[1] += res[1];
        }

        cnt[0] += c[v] == 1;
        cnt[1] += c[v] == 2;

        if (v != 0) {
            if (cnt[0] == 0 && cnt[1] == tot[1]) { ans += 1; }
            else if (cnt[0] == tot[0] && cnt[1] == 0) { ans += 1; }
        }

        debug { writeln(v, ' ', cnt, ' ', ans); }

        return cnt;
    }

    int ans = 0;
    dfs(0, -1, ans);

    ans.writeln;
}

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

  int n;
  rd(n);
  auto a = readln.split.to!(int[]);
  auto g = new int[][](n);
  foreach (_; 1 .. n) {
    int u, v;
    rd(u, v);
    g[u - 1] ~= v - 1;
    g[v - 1] ~= u - 1;
  }
  auto num_r = new int[](n), num_b = new int[](n);
  void f(int i, int p) {
    if (a[i] == 1) {
      num_r[i] = 1;
    } else if (a[i] == 2) {
      num_b[i] = 1;
    }
    foreach (j; g[i]) {
      if (j != p) {
        f(j, i);
        num_r[i] += num_r[j];
        num_b[i] += num_b[j];
      }
    }
  }

  f(0, -1);
  int bad = 0;
  void f2(int i, int p) {
    foreach (j; g[i]) {
      if (j != p) {
        if (num_r[j] > 0 && num_b[j]) {
          bad++;
        } else if (num_r[0] - num_r[j] > 0 && num_b[0] - num_b[j] > 0) {
          bad++;
        }
        f2(j, i);
      }
    }
  }

  f2(0, -1);
  writeln(n - 1 - bad);
}

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

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


There is a rectangular grid of size $$$n \times m$$$. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell $$$(i, j)$$$ is $$$c_{i, j}$$$. You are also given a map of directions: for each cell, there is a direction $$$s_{i, j}$$$ which is one of the four characters 'U', 'R', 'D' and 'L'.  If $$$s_{i, j}$$$ is 'U' then there is a transition from the cell $$$(i, j)$$$ to the cell $$$(i - 1, j)$$$;  if $$$s_{i, j}$$$ is 'R' then there is a transition from the cell $$$(i, j)$$$ to the cell $$$(i, j + 1)$$$;  if $$$s_{i, j}$$$ is 'D' then there is a transition from the cell $$$(i, j)$$$ to the cell $$$(i + 1, j)$$$;  if $$$s_{i, j}$$$ is 'L' then there is a transition from the cell $$$(i, j)$$$ to the cell $$$(i, j - 1)$$$. It is guaranteed that the top row doesn't contain characters 'U', the bottom row doesn't contain characters 'D', the leftmost column doesn't contain characters 'L' and the rightmost column doesn't contain characters 'R'.You want to place some robots in this field (at most one robot in a cell). The following conditions should be satisfied.  Firstly, each robot should move every time (i.e. it cannot skip the move). During one move each robot goes to the adjacent cell depending on the current direction.  Secondly, you have to place robots in such a way that there is no move before which two different robots occupy the same cell (it also means that you cannot place two robots in the same cell). I.e. if the grid is "RL" (one row, two columns, colors does not matter there) then you can place two robots in cells $$$(1, 1)$$$ and $$$(1, 2)$$$, but if the grid is "RLL" then you cannot place robots in cells $$$(1, 1)$$$ and $$$(1, 3)$$$ because during the first second both robots will occupy the cell $$$(1, 2)$$$. The robots make an infinite number of moves.Your task is to place the maximum number of robots to satisfy all the conditions described above and among all such ways, you have to choose one where the number of black cells occupied by robots before all movements is the maximum possible. Note that you can place robots only before all movements.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 < nm \le 10^6$$$) — the number of rows and the number of columns correspondingly. The next $$$n$$$ lines contain $$$m$$$ characters each, where the $$$j$$$-th character of the $$$i$$$-th line is $$$c_{i, j}$$$ ($$$c_{i, j}$$$ is either '0' if the cell $$$(i, j)$$$ is black or '1' if the cell $$$(i, j)$$$ is white). The next $$$n$$$ lines also contain $$$m$$$ characters each, where the $$$j$$$-th character of the $$$i$$$-th line is $$$s_{i, j}$$$ ($$$s_{i, j}$$$ is 'U', 'R', 'D' or 'L' and describes the direction of the cell $$$(i, j)$$$). It is guaranteed that the sum of the sizes of fields does not exceed $$$10^6$$$ ($$$\sum nm \le 10^6$$$).

For each test case, print two integers — the maximum number of robots you can place to satisfy all the conditions described in the problem statement and the maximum number of black cells occupied by robots before all movements if the number of robots placed is maximized. Note that you can place robots only before all movements.

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

immutable int dirs = 4;
immutable int  [dirs] dRow  = [ -1,   0,  +1,   0];
immutable int  [dirs] dCol  = [  0,  -1,   0,  +1];
immutable char [dirs] dName = ['U', 'L', 'D', 'R'];
immutable int NA = -1;
immutable int CUR = -2;

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		bool [] [] isBlack;
		foreach (row; 0..rows)
		{
			isBlack ~= readln.strip.map
			    !(c => c == '0').array;
		}
		byte [] [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip.map
			    !(c => dName[].countUntil (c).to !(byte)).array;
		}

		auto part = new int [] [] (rows, cols);
		foreach (ref line; part)
		{
			line[] = NA;
		}
		auto loopPos = new int [] [] (rows, cols);

		int parts = 0;
		int curPart = 0;
		int [] loopLength;

		int recur (int row, int col, int num)
		{
			if (part[row][col] != NA)
			{
				if (part[row][col] == CUR)
				{
					curPart = parts;
					parts += 1;
					loopLength ~= num - loopPos[row][col];
					loopPos[row][col] = 0;
				}
				else
				{
					curPart = part[row][col];
				}
				part[row][col] = curPart;
				return (loopPos[row][col] + 1) %
				    loopLength[curPart];
			}

			part[row][col] = CUR;
			loopPos[row][col] = num;
			auto dir = board[row][col];
			auto nRow = row + dRow[dir];
			auto nCol = col + dCol[dir];
			auto nPos = recur (nRow, nCol, num + 1);
			part[row][col] = curPart;
			loopPos[row][col] = nPos;
			return (nPos + 1) % loopLength[curPart];
		}

		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (part[row][col] == NA)
				{
					recur (row, col, 0);
				}
			}
		}

		debug
		{
			foreach (row; 0..rows)
			{
				foreach (col; 0..cols)
				{
					write (part[row][col],
					    loopPos[row][col], " ");
				}
				writeln;
			}
			writeln;
		}

		int res1 = loopLength.sum;
		alias Pair = Tuple !(int, q{part}, int, q{loopPos});
		bool [Pair] res2;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (isBlack[row][col])
				{
					res2[Pair (part[row][col],
					    loopPos[row][col])] = true;
				}
			}
		}
		writeln (res1, " ", res2.length);
	}
}

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

immutable int dirs = 4;
immutable int  [dirs] dRow  = [ -1,   0,  +1,   0];
immutable int  [dirs] dCol  = [  0,  -1,   0,  +1];
immutable char [dirs] dName = ['U', 'L', 'D', 'R'];
immutable int NA = -1;
immutable int CUR = -2;

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		bool [] [] isBlack;
		foreach (row; 0..rows)
		{
			isBlack ~= readln.strip.map
			    !(c => c == '0').array;
		}
		byte [] [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip.map
			    !(c => dName[].countUntil (c).to !(byte)).array;
		}

		auto part = new int [] [] (rows, cols);
		foreach (ref line; part)
		{
			line[] = NA;
		}
		auto loopPos = new int [] [] (rows, cols);

		int parts = 0;
		int curPart = 0;
		int [] loopLength;

		int recur (int row, int col, int num)
		{
			if (part[row][col] != NA)
			{
				if (part[row][col] == CUR)
				{
					curPart = parts;
					parts += 1;
					loopLength ~= num - loopPos[row][col];
					loopPos[row][col] = 0;
				}
				part[row][col] = curPart;
				return (loopPos[row][col] + 1) %
				    loopLength[curPart];
			}

			part[row][col] = CUR;
			loopPos[row][col] = num;
			auto dir = board[row][col];
			auto nRow = row + dRow[dir];
			auto nCol = col + dCol[dir];
			auto nPos = recur (nRow, nCol, num + 1);
			part[row][col] = curPart;
			loopPos[row][col] = nPos;
			return (nPos + 1) % loopLength[curPart];
		}

		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (part[row][col] == NA)
				{
					recur (row, col, 0);
				}
			}
		}

		debug
		{
			foreach (row; 0..rows)
			{
				foreach (col; 0..cols)
				{
					write (part[row][col],
					    loopPos[row][col], " ");
				}
				writeln;
			}
			writeln;
		}

		int res1 = loopLength.sum;
		alias Pair = Tuple !(int, q{part}, int, q{loopPos});
		bool [Pair] res2;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (isBlack[row][col])
				{
					res2[Pair (part[row][col],
					    loopPos[row][col])] = true;
				}
			}
		}
		writeln (res1, " ", res2.length);
	}
}


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position $$$3$$$ and ends in position $$$6$$$), but "aa" or "d" aren't substrings of this string. So the substring of the string $$$s$$$ from position $$$l$$$ to position $$$r$$$ is $$$s[l; r] = s_l s_{l + 1} \dots s_r$$$.You have to choose exactly one of the substrings of the given string and reverse it (i. e. make $$$s[l; r] = s_r s_{r - 1} \dots s_l$$$) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring.String $$$x$$$ is lexicographically less than string $$$y$$$, if either $$$x$$$ is a prefix of $$$y$$$ (and $$$x \ne y$$$), or there exists such $$$i$$$ ($$$1 \le i \le min(|x|, |y|)$$$), that $$$x_i < y_i$$$, and for any $$$j$$$ ($$$1 \le j < i$$$) $$$x_j = y_j$$$. Here $$$|a|$$$ denotes the length of the string $$$a$$$. The lexicographic comparison of strings is implemented by operator < in modern programming languages.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.

If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) denoting the substring you have to reverse. If there are multiple answers, you can print any.

NoteIn the first testcase the resulting string is "aacabba".

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

void main() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;

    foreach (i; 0..N-1) {
        if (S[i] > S[i+1]) {
            writeln("YES");
            writeln(i+1, " ", i+2);
            return;
        }
    }

    writeln("NO");
}

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

void main()
{
	int elemanSayısı = stdin.readln.strip.to!int;
	string harfler = stdin.readln.strip.to!string;

	int enBüyükIndeksi = 0;
	char enBüyükHarf = 'a';
	for ( int i = 0; i < harfler.length; i++ )
	{
		if ( harfler[i] >= enBüyükHarf )
		{
			enBüyükIndeksi = i;
			enBüyükHarf = harfler[i];
		}
		else
		{
			writeln("YES");
			return writeln( enBüyükIndeksi+1, " ", i+1 );
		}

	}
	writeln("NO");

}

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

void main() {
  auto n = readln.strip.to!int;
  auto s = readln.strip[0 .. n];
  foreach (i; 1 .. n) {
    if (s[i-1] > s[i]) {
      debug stderr.writeln (i);
      writeln ("YES");
      writeln (i, ' ', i + 1);
      return;
    }
  }
  writeln ("NO");
}

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

/*
If you find s_i > s_(i + 1), swap them.
Othewise, NO.
*/

void solve(){
	int n = read!int;
	string s = readln.chomp;

	int i1;
	bool f = 0;
	foreach(i; 0 .. n - 1){
		if(s[i] > s[i + 1]){
			i1 = i;
			f = 1;
			break;
		}
	}
	if(f == 0) writeln("NO");
	else writeln("YES"), writeln(i1 + 1, " ", i1 + 2);
}

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto N = RD!int;
	auto s = RD!string;

	long[2] ans;
	foreach (i; 1..N)
	{
		if (s[i-1] > s[i])
		{
			ans = [i-1, i];
			break;
		}
	}

	if (ans == [0, 0])
		writeln("NO");
	else
	{
		writeln("YES");
		writeln(ans[0]+1, " ", ans[1]+1);
	}
	stdout.flush();
	debug readln();
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;

    foreach (i; 0..N-1) {
        if (S[i] > S[i-1]) {
            writeln("YES");
            writeln(i+1, " ", i+2);
            return;
        }
    }

    writeln("NO");
}


Pay attention to the non-standard memory limit in this problem.In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.The array $$$a=[a_1, a_2, \ldots, a_n]$$$ ($$$1 \le a_i \le n$$$) is given. Its element $$$a_i$$$ is called special if there exists a pair of indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) such that $$$a_i = a_l + a_{l+1} + \ldots + a_r$$$. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).Print the number of special elements of the given array $$$a$$$.For example, if $$$n=9$$$ and $$$a=[3,1,4,1,5,9,2,6,5]$$$, then the answer is $$$5$$$:  $$$a_3=4$$$ is a special element, since $$$a_3=4=a_1+a_2=3+1$$$;  $$$a_5=5$$$ is a special element, since $$$a_5=5=a_2+a_3=1+4$$$;  $$$a_6=9$$$ is a special element, since $$$a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$$$;  $$$a_8=6$$$ is a special element, since $$$a_8=6=a_2+a_3+a_4=1+4+1$$$;  $$$a_9=5$$$ is a special element, since $$$a_9=5=a_2+a_3=1+4$$$. Please note that some of the elements of the array $$$a$$$ may be equal — if several elements are equal and special, then all of them should be counted in the answer.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given in two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 8000$$$) — the length of the array $$$a$$$. The second line contains integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$8000$$$.

Print $$$t$$$ numbers — the number of special elements for each of the given arrays.

void main() {
	auto t = ri;
	foreach(T; 0..t) {
		auto n = ri;
		auto a = readAs!(int[]);
		auto arr = new int[](n);
		arr[0] = a[0];
		foreach(i; 1..n) arr[i] = arr[i-1] + a[i];
		int[int] ms, me;

		foreach(v; a) me[v]++;
		foreach(i; 1..n) ms[arr[i]]++;
		foreach(i; 0..n) foreach(j; i..n) {
			if(j - i < 2) continue;
			auto s = arr[j] - arr[i];
			debug writefln("%d, %d => %d", j, i, s);
			if(s <= n) ms[s]++;
		}
		long res;
		debug "=====".writeln;
		debug me.writeln;
		debug ms.writeln;
		foreach(i, v; me) {
			if(i in ms) {
				res += v;
			}
		}
		res.writeln;
	}
}

// ===================================

import std.stdio;
import std.string;
import std.functional;
import std.algorithm;
import std.range;
import std.traits;
import std.math;
import std.container;
import std.bigint;
import std.numeric;
import std.conv;
import std.typecons;
import std.uni;
import std.ascii;
import std.bitmanip;
import core.bitop;

T readAs(T)() if (isBasicType!T) {
	return readln.chomp.to!T;
}
T readAs(T)() if (isArray!T) {
	return readln.split.to!T;
}

T[][] readMatrix(T)(uint height, uint width) if (!isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		res[i] = readAs!(T[]);
	}
	return res;
}

T[][] readMatrix(T)(uint height, uint width) if (isSomeChar!T) {
	auto res = new T[][](height, width);
	foreach(i; 0..height) {
		auto s = rs;
		foreach(j; 0..width) res[i][j] = s[j].to!T;
	}
	return res;
}

int ri() {
	return readAs!int;
}

long rl() {
	return readAs!long;
}

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_t; 0..T) {
        auto N = readln.chomp.to!int;
        auto as = readln.split.to!(int[]);
        if (N == 1) {
            writeln(0);
            continue;
        }
        int r;
        foreach (a; as) {
            int s = as[0] + as[1];
            size_t i, j = 2;
            while (i < N-1) {
                if (s == a) {
                    goto ok;
                } else if (s < a && j < N) {
                    s += as[j++];
                } else if (i < j-2) {
                    s -= as[i++];
                } else if (j < N) {
                    s += as[j++];
                } else {
                    break;
                }
            }
            continue;
            ok:
            ++r;
        }
        writeln(r);
    }
}

// Author: Ivan Kazmenko (gassa@mail.ru)
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 marks = new bool [n + 1];
		foreach (i; 0..n)
		{
			int cur = a[i];
			foreach (j; i + 1..n)
			{
				cur += a[j];
				if (cur > n)
				{
					break;
				}
				marks[cur] = true;
			}
		}
		writeln (a.count !(x => marks[x]));
	}
}

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

T readNum(T)(){
  return readStr.to!T;
}

T[] readNums(T)(){
  return readStr.split.to!(T[]);
}

string readStr(){
  return readln.chomp;
}

void main(){
  auto t = readNum!int;

  foreach(i; 0 .. t){
    int ret;
    auto n = readNum!int;
    auto a = readNums!int;

    auto csum = new int[](n+1);
    foreach(j; 1 .. n+1){
      csum[j] = csum[j-1] + a[j-1];
    }

    foreach(j; 0 .. n){
      int l = 0, r = 2;

      while(r <= n){
        int sum = csum[r] - csum[l];
        if(sum < a[j] || l == r-1){
          r++;
        } else if(sum > a[j]){
          l++;
        } else {
          ret++;
          break;
        }
      }
    }

    writeln(ret);
  }
}

import std.stdio;
import std.algorithm;
import std.range;
import std.conv;
import std.string;
import std.array;
import core.stdc.stdlib;
import core.stdc.stdio;
import core.stdc.string;

void main() @nogc {
	// int tt = 1000;
	int tt;
	scanf("%d", &tt);
	foreach (t; 0 .. tt) {
		// int n = 8000;
		int n;
		scanf("%d", &n);
		int[] arr = (cast(int*)malloc(int.sizeof * n))[0 .. n];
		foreach (i; 0 .. arr.length) {
			scanf("%d", &arr[i]);
			// arr[i] = rand() % n + 1;
		}
		bool[] specials = (cast(bool*)malloc(bool.sizeof * (n + 2)))[0 .. n + 2];
		memset(specials.ptr, 0, bool.sizeof * (n + 2));
		foreach (i; 0 .. arr.length) {
			int sum = arr[i];
			foreach (j; i + 1 .. arr.length) {
				sum += arr[j];
				if (sum < n + 2) {
					specials[sum] = true;
				}
				else {
					break;
				}
			}
		}
		int res;
		foreach (i; arr) {
			if (specials[i]) {
				res++;
			}
		}
		printf("%d\n", res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto b = new int[](n+1);
		foreach (i; 0..n)
		{
			b[i+1] += b[i] + a[i];
		}

		auto set = new int[](n+1);
		foreach (i; 0..n)
		{
			++set[a[i]];
		}
		debug writeln(set);

		auto hit = new bool[](n+1);
		foreach (l; 0..n)
		{
			foreach (r; l+2..n+1)
			{
				auto x = b[r] - b[l];
				if (x > n) continue;
				hit[x] = true;
			}
		}

		foreach (i; 0..n+1)
		{
			if (hit[i])
			{
				ans[ti] += set[i];
			}
		}
	}

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

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

T readNum(T)(){
  return readStr.to!T;
}

T[] readNums(T)(){
  return readStr.split.to!(T[]);
}

string readStr(){
  return readln.chomp;
}

void main(){
  auto t = readNum!int;

  foreach(i; 0 .. t){
    int ret;
    auto n = readNum!int;
    auto a = readNums!int;

    auto csum = new int[](n+1);
    foreach(j; 1 .. n+1){
      csum[j] = csum[j-1] + a[j-1];
    }

    foreach(j; 1 .. n){
      int l = 0, r = 2;

      while(r <= n){
        int sum = csum[r] - csum[l];
        if(sum < a[j] || l == r-1){
          r++;
        } else if(sum > a[j]){
          l++;
        } else {
          ret++;
          break;
        }
      }
    }

    writeln(ret);
  }
}


The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!

The first line contains two integers, n and k (1 ≤ k ≤ n ≤ 100) — the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'.

In t lines, print the actions the programmers need to make. In the i-th line print:   "LEFT" (without the quotes), if the i-th action was "move the ladder to the left";  "RIGHT" (without the quotes), if the i-th action was "move the ladder to the right";  "PRINT x" (without the quotes), if the i-th action was to "go up the ladder, paint character x, go down the ladder".  The painting time (variable t) must be minimum possible. If there are multiple optimal painting plans, you can print any of them.

RIGHT
RIGHT
PRINT !
LEFT
PRINT O
LEFT
PRINT G
LEFT
PRINT ?
LEFT
PRINT O
LEFT
PRINT G

NoteNote that the ladder cannot be shifted by less than one meter. The ladder can only stand in front of some square of the poster. For example, you cannot shift a ladder by half a meter and position it between two squares. Then go up and paint the first character and the second character.

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                int k = cin.readInt;
                string s = cin.readString;
                if (k <= n - k) {
                        for (int i = 1; i < k; i++) {
                                writeln("LEFT");
                        }
                        for (int i = 0; i < n; i++) {
                                writeln("PRINT ", s[i]);
                                if (i != n - 1) writeln("RIGHT");
                        }
                } else {
                        for (int i = k; i < n; i++) {
                                writeln("RIGHT");
                        }
                        for (int i = n - 1; i >= 0; i--) {
                                writeln("PRINT ", s[i]);
                                if (i != 0) writeln("LEFT");
                        }
                }
        }
}


Businessman Divan loves chocolate! Today he came to a store to buy some chocolate. Like all businessmen, Divan knows the value of money, so he will not buy too expensive chocolate. At the same time, too cheap chocolate tastes bad, so he will not buy it as well.The store he came to has $$$n$$$ different chocolate bars, and the price of the $$$i$$$-th chocolate bar is $$$a_i$$$ dollars. Divan considers a chocolate bar too expensive if it costs strictly more than $$$r$$$ dollars. Similarly, he considers a bar of chocolate to be too cheap if it costs strictly less than $$$l$$$ dollars. Divan will not buy too cheap or too expensive bars.Divan is not going to spend all his money on chocolate bars, so he will spend at most $$$k$$$ dollars on chocolates.Please determine the maximum number of chocolate bars Divan can buy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The description of each test case consists of two lines. The first line contains integers $$$n$$$, $$$l$$$, $$$r$$$, $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le l \le r \le 10^9$$$, $$$1 \le k \le 10^9$$$) — the lowest acceptable price of a chocolate, the highest acceptable price of a chocolate and Divan's total budget, respectively. The second line contains a sequence $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) integers — the prices of chocolate bars in the store.

For each test case print a single integer — the maximum number of chocolate bars Divan can buy.

NoteIn the first example Divan can buy chocolate bars $$$1$$$ and $$$3$$$ and spend $$$100$$$ dollars on them.In the second example Divan can buy chocolate bars $$$3$$$ and $$$4$$$ and spend $$$7$$$ dollars on them.In the third example Divan can buy chocolate bars $$$3$$$, $$$4$$$, and $$$5$$$ for $$$12$$$ dollars.In the fourth example Divan cannot buy any chocolate bar because each of them is either too cheap or too expensive.In the fifth example Divan cannot buy any chocolate bar because he considers the first bar too cheap, and has no budget for the second or third.In the sixth example Divan can buy all the chocolate bars in the shop.

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

void solve(){
    long n = scan;
    long l = scan;
    long r = scan;
    long k = scan;
    auto arr = scanArray;
    arr.sort;
    long cnt = 0;
    for(int i = 0; i < n; ++i){
        if(arr[i] >= l && arr[i] <= r){
            if(k >= arr[i]){
                ++cnt;
                k -= arr[i];
            }
        }
    }
    writeln(cnt);
}

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

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

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto l = readInt!int;
	auto r = readInt!int;
	auto k = readInt!int;
	auto a = ma(n, readInt!int);
	a = a.filter!(ai => ai >= l && ai <= r).array;
	sort(a);
	debug writeln("after filter ", a);
	int count = 0;
	while (!a.empty && k >= a.front)
	{
		count++;
		k -= a.front;
		a.popFront;
	}
	count.writeln;
}

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

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

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

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

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

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]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

		a.sort;
		foreach (i; 0..n)
		{
			if (a[i] < l || a[i] > r) continue;
			if (k < a[i]) break;
			k -= a[i];
			++ans[ti];
		}
	}

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