void main() {
	auto N = ri;
	int[][] tree = new int[][](N+3, 0);
	//foreach(i; 2..N+2) tree[i] = [];
	foreach(i; 2..N+1) {
		auto p = ri;
		tree[p] ~= i;
	}
	ulong k;
	int[][] que;
	que = [[],[]];
	que[0] ~= 1;
	bool flag = true;
	while(que[k%2] != []) {
		auto p = que[k%2].front;
		que[k%2].popFront;
		ulong cnt;
		bool ok = true;
		foreach(i; tree[p]) {
			que[(k+1)%2] ~= i;
			debug writefln("%s %s %s", tree[i], [], tree[i] == []);
			if(tree[i] == []) cnt++;
			else ok = false;
		}
		if((!ok && cnt == 0) || cnt != 0 && cnt < 3) flag = false;
		k++;
	}
	writeln(flag ? "Yes" : "No");
}

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

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

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto G = new int[][](N);
    foreach (i; 0..N-1) {
        auto v = readln.chomp.to!int;
        G[v-1] ~= i+1;
    }

    auto is_leaf = new bool[](N);
    foreach (i; 0..N) is_leaf[i] = G[i].length == 0;

    auto ok = new bool[](N);
    foreach (i; 0..N) {
        if (is_leaf[i]) {
            ok[i] = true;
            continue;
        }
        int cnt = 0;
        foreach (m; G[i]) {
            cnt += is_leaf[m];
        }
        ok[i] = cnt >= 3;
    }

    writeln(ok.all ? "Yes" : "No");
}

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

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

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) sc.read!true;

    int n;
    sc.read(n);
    int[][] g = new int[][](n);
    foreach (i; 1..n) {
        int p;
        sc.read(p); p--;
        g[p] ~= i;
    }

    bool ans = true;
    int dfs(int p) {
        if (g[p].length == 0) return 1;
        int u = 0;
        foreach (d; g[p]) {
            u += dfs(d);
        }
        if (u < 3) ans = false;
        return 0;
    }
    dfs(0);
    if (ans) writeln("Yes");
    else writeln("No");
    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

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

    private T* _data;
    private uint len, cap;

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

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

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

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

    void clear() {
        len = 0;
    }

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

/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

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

}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

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

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

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

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

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

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

bool solve (int [] p)
{
	auto n = p.length;
	auto d = new int [n];
	foreach (i; 1..n)
	{
		d[p[i]] += 1;
	}
	auto isLeaf = new bool [n];
	auto leafSons = new int [n];
	foreach (i; 1..n)
	{
		isLeaf[i] = (d[i] == 0);
		leafSons[p[i]] += isLeaf[i];
	}
	foreach (i; 0..n)
	{
		if (!isLeaf[i])
		{
			if (leafSons[i] < 3)
			{
				return false;
			}
		}
	}
	return true;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new int [n];
		foreach (i; 1..n)
		{
			readf (" %s", &p[i]);
		}
		p[] -= 1;
		writeln (solve (p) ? "Yes" : "No");
	}
}

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

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

    auto adj = new int[][](n, 0);

    foreach (i ; 1 .. n) {
        int pi;
        scan(pi);
        adj[pi-1] ~= i;
    }

    bool ans = true;

    void dfs(int v, int p) {
        if (adj[v].empty) return;

        int lc;

        foreach (u ; adj[v]) {
            if (u == p) continue;
            if (adj[u].empty) {
                lc++;
            }
            else {
                dfs(u, v);
            }
        }

        if (lc < 3) ans = false;

        return;
    }

    dfs(0,0);

    writeln(ans ? "Yes" : "No");
}

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

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

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

  int n; rd(n);
  auto par=new int[](n);
  par[0]=-1;
  foreach(int i; 1..n){
    int p; rd(p);
    par[i]=(p-1);
  }

  auto leaf=new bool[](n);
  foreach(i; 0..n){
    auto c=count(par, i);
    if(c==0) leaf[i]=true;
  }
  foreach(i; 0..n)if(leaf[i]==false){
    int c=0;
    foreach(j; 0..n){
      if(par[j]==i && leaf[j]) c++;
    }
    if(c<3){writeln("No"); return;}
  }
  writeln("Yes");
}

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

void main() {
	auto N = ri;
	int[] arr;
	foreach(i; 0..N-1) arr ~= ri;
	bool[ulong] m;
	arr.enumerate.filter!(i => i.value == 1).map!(i => i.index).array.each!(i => m[i] = true);
	arr.enumerate.filter!(i => i.value != 1).each!(i => m[i.value-1] = false);
	if(m.values.count!(i => i) == 3) writeln("Yes");
	else writeln("No");
}

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

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

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}

void main() {
	auto N = ri;
	int[][] tree = new int[][](N+3, 0);
	//foreach(i; 2..N+2) tree[i] = [];
	foreach(i; 2..N+1) {
		auto p = ri;
		tree[p] ~= i;
	}
	ulong k;
	int[][] que;
	que = [[],[]];
	que[0] ~= 1;
	bool flag = true;
	while(que[k%2] != []) {
		auto p = que[k%2].front;
		que[k%2].popFront;
		ulong cnt;
		foreach(i; tree[p]) {
			que[(k+1)%2] ~= i;
			debug writefln("%s %s %s", tree[i], [], tree[i] == []);
			if(tree[i] == []) cnt++;
		}
		if(cnt != 0 && cnt < 3) flag = false;
		k++;
	}
	writeln(flag ? "Yes" : "No");
}

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

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

double rd() {
	return readAs!double;
}

string rs() {
	return readln.chomp;
}


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

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

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

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

enum INF = 10^^9;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const A = readInt();
      const B = readInt();
      const S = readToken();

      auto lcp = new int[][](N + 1, N + 1);
      foreach_reverse (i; 0 .. N) foreach_reverse (j; 0 .. N) {
        lcp[i][j] = (S[i] == S[j]) ? (1 + lcp[i + 1][j + 1]) : 0;
      }
      foreach (i; 0 .. N + 1) {
        foreach (j; 0 .. N) {
          chmax(lcp[i][j + 1], lcp[i][j]);
        }
      }

      auto dp = new int[N + 1];
      dp[] = INF;
      dp[0] = 0;
      foreach (i; 0 .. N) {
        chmin(dp[i + 1], dp[i] + A);
        foreach (j; i + 1 .. N + 1) {
          // lcp[i][k] >= j - i, 0 <= k <= i - (j - i)
          if (0 <= i - (j - i) && lcp[i][i - (j - i)] >= j - i) {
            chmin(dp[j], dp[i] + B);
          }
        }
      }
      writeln(dp[N]);
    }
  } catch (EOFException e) {
  }
}

int[] make_z(in char[] s) {
  import std.algorithm : max;
  import std.conv : to;

  int n = s.length.to!(int);
  auto z = new int[](n);
  for (int i = 1, p = 0; i < n; i++) {
    if (i + z[i - p] < p + z[p]) {
      z[i] = z[i - p];
    } else {
      auto j = max(0, p + z[p] - i);
      while (i + j < n && s[j] == s[i + j]) {
        j++;
      }
      z[i] = j;
      p = i;
    }
  }
  z[0] = n;
  return z;
}

void chmin(ref int l, int r) {
  if (l > r) {
    l = r;
  }
}

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

  int n, a, b;
  rd(n, a, b);
  auto s = readln.chomp.to!(char[]);

  auto z = new int[][](n, n);
  foreach (i; 0 .. n) {
    z[i][i .. $] = make_z(s[i .. $]);
  }
  auto dp = new int[](n + 1);
  fill(dp, 5000 * 5000);
  dp[0] = 0;
  foreach (i; 0 .. n) {
    chmin(dp[i + 1], dp[i] + a);
    foreach (j; 0 .. i) {
      if (z[j][i] > 0) {
        chmin(dp[i + min(z[j][i], i - j)], dp[i] + b);
      }
    }
  }
  writeln(dp[n]);
}

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


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.typecons;

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

    while (t--) {
        int n, p, k;
        readf("%s %s %s", &n, &p, &k);
        readln;

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

        arr.sort();

        auto cost = new int[] (n+1);
        cost[0] = 0;
        foreach (i, e; arr.enumerate(1)) {
            if (i < k) { cost[i.to!int] = cost[i.to!int - 1] + e; }
            else { cost[i.to!int] = cost[i.to!int - k] + e; }
        }

        int ans = 0;
        foreach (i, e; cost) {
            if (e <= p) { ans = i.to!int; }
        }

        ans.writeln;
    }
}

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

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  immutable t = r.next!uint;
  auto res = uninitializedArray!(int[]) (t);
  foreach (tid; 0 .. t) {
    immutable n = r.next!uint;
    auto p = r.next!uint;
    immutable k = r.next!uint;
    auto a = r.nextA!uint (n);
    sort (a);
    /*
    auto s = new long[n+1];
    s[0] = 0;
    foreach (i; 1 .. n + 1) s[i] = s[i-1] + a[i-1];
    */
    auto b = new long[n+1];
    b[0] = 0;
    foreach (i; 1 .. n + 1) {
      immutable val = a[i-1];
      b[i] = b[i-1] + val;
      int j = (i - (k - 1));
      if (j >= 1) {
        b[i] = min (b[i], b[j-1] + val);
      }
    }
    int ans;
    foreach_reverse (i; 1 .. n + 1) {
      if (b[i] <= p) {
        ans = i;
        break;
      }
    }
    res[tid] = ans;
  }
  writefln ("%(%s\n%)", res);
}

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 rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	foreach(_; 0 .. rint){
		int n = rint;
		long p = rlong;
		int k = rint;
		long[] as = rlong(n);
		as.sort();
		log("---");
		log("n:", n, "p:", p, "k:", k, "as:", as);

		int ans = 0;
		int tmp1 = 0;
		foreach(r; 0 .. k){
			int tmp2 = tmp1;
			for(int m = 0; r + k * m <= n; m ++){
				log("r:", r, "m:", m, "x:", r + k * m, "tmp1:", tmp1, "tmp2:", tmp2, "f:", tmp2 <= p);
				if(tmp2 <= p) ans.chmax(r + k * m);
				else break;
				if(r + k * m + k - 1 < n) tmp2 += as[r + k * m + k - 1];
				else break;
			}
			tmp1 += as[r];
		}
		ans.writeln;
	}
}


import std.bigint,std.container,std.array,std.algorithm,std.conv,std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.typecons,std.regex,
std.random,std.uni,std.traits,std.variant;
import core.stdc.stdio:freopen;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
immutable int mod=1000000007;
@property pure nothrow T lcm (T)(auto ref T a,auto ref T b)
{
	return a/gcd(a,b)*b;
}
pure nothrow @property X binpow(X,Y)(X base,Y exp)
if(is(typeof(exp&1)))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow @property auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
if(is(typeof(exp&1)))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@property void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
@property void putarr(X)(X a,in int n,in int m)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
@property bool getarr(X)(X a,in int n){bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0) {return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
struct pair(X,Y)
{
	X first;
	Y second;
	alias first fi;
	alias second se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
	}
	this(this){fi=fi;se=se;}
	this(A,B)(auto ref pair!(A,B) p)
	{
		fi=p.fi;
		se=p.se;
	}
	int opCmp(in pair!(X,Y) s_) const pure nothrow @safe
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(in X x_,in Y y_) pure nothrow @safe
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_;}
X cub(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_*a_;}
nothrow @nogc @system void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow @nogc @system void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
auto arread(T)(){return readln.split.map!(to!(T)).array;}
nothrow @property pure size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (!(a[l]<g))?l:r;
}
pure @property nothrow size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(g<a[m])r=m;
		else l=m;
	}
	return (g<a[l])?l:r;
}
pure @property nothrow size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (g==a[l])?l:a.length;
}
pure @property nothrow bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	return binf(a,g)!=a.length;
}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n,k;
	while(input(&n,&k))
	{
		readln;
		auto t=arread!int;
		int r;
		foreach(i;t)if(i<0)r++;
		debug writeln(r);
		if(r>k){writeln(-1);return;}
		int ans;
		int[] pos;
		auto q=rbt!(true,int);
		foreach(i,p;t)
		{
			if(p<0)
			{
				k--;
				if(pos.length>0 && i-pos[$-1]>1){ q.insert(i-pos[$-1]-1);ans+=2;}
				else if(pos.length==0) ans+=2;
				pos~=i;
			}
		}
		while(!q.empty && k>=q.front)
		{
			k-=q.front;
			q.removeFront;
			ans-=2;
		}
		if(pos.length>0 && k>=n-pos[$-1]-1)ans--;
		writeln(ans);
	}
	debug readln;
}

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

__gshared:

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

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

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

int n, k;
bool[200_000] _winter;

void main() {
    while (read(&n, &k)) {
        auto winter = _winter[0 .. n];
        int winterLength = 0;
        bool cur = false;
        int result = 0;
        foreach (ref x; winter) {
            int y;
            read(&y);
            x = y < 0;
            if (x) {
                if (!cur) {
                    result++;
                    cur = true;
                }
                winterLength++;
            } else if (cur) {
                result++;
                cur = false;
            }
        }
        if (winterLength > k)
            writeln("-1");
        else {
            debug writeln("pre: ", result);

            int check(uint[ ] intervals, int cap) {
                intervals.sort();
                debug writeln(intervals);
                int result2 = result;
                debug writeln(cap);
                while (!intervals.empty && cap >= intervals[0]) {
                    cap -= intervals[0];
                    result2 -= 2;
                    intervals.popFront();
                }
                debug writeln("< ", result2);
                assert(result2 >= 0);
                return result2;
            }

            auto intervals = group(winter).filter!`!a[0]`.map!`a[1]`.array();
            int result2 = int.max;
            if (!intervals.empty) {
                if (!winter[0])
                    intervals.popFront();
                int cap = k - winterLength;
                if (!winter[$ - 1] && !intervals.empty) {
                    if (cap >= intervals[$ - 1])
                        result2 = check(intervals[0 .. $ - 1].dup, cap - intervals[$ - 1]) - 1;
                    result2 = min(result2, check(intervals[0 .. $ - 1], cap));
                } else
                    result2 = check(intervals, cap);
            } else
                result2 = 1;
            writeln(result2 >= 0 && result2 != int.max? result2 : -1);
            debug writeln();
        }
    }
}

import std.bigint,std.container,std.array,std.algorithm,std.conv,std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.typecons,std.regex,
std.random,std.uni,std.traits,std.variant;
import core.stdc.stdio : freopen;
import core.stdc.stdlib : system;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
immutable int mod=1000000007;
@property pure nothrow T lcm (T)(auto ref T a,auto ref T b)
{
	return a/gcd(a,b)*b;
}
pure nothrow @property X binpow(X,Y)(X base,Y exp)
if(is(typeof(exp&1)))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow @property auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
if(is(typeof(exp&1)))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@property void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
@property void putarr(X)(X a,in int n,in int m)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
@property bool getarr(X)(X a,in int n){bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0) {return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
struct pair(X,Y)
{
	X first;
	Y second;
	alias first fi;
	alias second se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
	}
	this(this){fi=fi;se=se;}
	this(A,B)(auto ref pair!(A,B) p) if(is(A:X) && is(B:Y))
	{
		fi=p.fi;
		se=p.se;
	}
	int opCmp(A,B)(in pair!(A,B) s_) const pure nothrow @safe if(is(typeof(s_.fi<fi)==bool) && is(typeof(s_.se<se)==bool))
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(in X x_,in Y y_) pure nothrow @safe
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_;}
X cub(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_*a_;}
nothrow @nogc @system void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow @nogc @system void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
auto arread(T)(){return readln.split.map!(to!(T)).array;}
nothrow @property pure size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (!(a[l]<g))?l:r;
}
pure @property nothrow size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(g<a[m])r=m;
		else l=m;
	}
	return (g<a[l])?l:r;
}
pure @property nothrow size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (g==a[l])?l:a.length;
}
pure @property nothrow bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	return binf(a,g)!=a.length;
}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n,k;
	while(input(&n,&k))
	{
		readln;
		auto t=arread!int;
		auto r=t.count!"a<0";
		debug writeln(r);
		if(r>k){writeln(-1);return;}
		int ans;
		int[] pos;
		auto q=rbt!(true,int);
		foreach(i,p;t)
		{
			if(p<0)
			{
				k--;
				if(pos.length>0 && i-pos[$-1]>1){ q.insert(i-pos[$-1]-1);ans+=2;}
				else if(pos.length==0) ans+=2;
				pos~=i;
			}
		}
		while(!q.empty && k>=q.front)
		{
			k-=q.front;
			q.removeFront;
			ans-=2;
		}
		if(pos.length>0 && k>=n-pos[$-1]-1)ans--;
		writeln(ans);
	}
	debug system("pause");
}

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

__gshared:

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

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

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

int n, k;
bool[200_000] _winter;

void main() {
    while (read(&n, &k)) {
        auto winter = _winter[0 .. n];
        int winterLength = 0;
        bool cur = false;
        int result = 0;
        foreach (ref x; winter) {
            int y;
            read(&y);
            x = y < 0;
            if (x) {
                if (!cur) {
                    result++;
                    cur = true;
                }
                winterLength++;
            } else if (cur) {
                result++;
                cur = false;
            }
        }
        if (winterLength > k)
            writeln("-1");
        else {
            debug writeln("pre: ", result);

            int check(uint[ ] intervals, int cap) {
                intervals.sort();
                debug writeln(intervals);
                int result2 = result;
                debug writeln(cap);
                while (!intervals.empty && cap >= intervals[0]) {
                    cap -= intervals[0];
                    result2 -= 2;
                    intervals.popFront();
                }
                debug writeln("< ", result2);
                assert(result2 >= 0);
                return result2;
            }

            auto intervals = group(winter).filter!`!a[0]`.map!`a[1]`.array();
            int result2 = int.max;
            if (!intervals.empty) {
                if (!winter[0])
                    intervals.popFront();
                int cap = k - winterLength;
                if (!winter[$ - 1] && !intervals.empty) {
                    if (cap >= intervals[$ - 1])
                        result2 = check(intervals[0 .. $ - 1].dup, cap - intervals[$ - 1]) - 1;
                    result2 = min(result2, check(intervals[0 .. $ - 1], cap));
                } else
                    result2 = check(intervals, cap);
            }
            writeln(result2 >= 0 && result2 != int.max? result2 : -1);
        }
    }
}

import std.bigint,std.container,std.array,std.algorithm,std.conv,std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.typecons,std.regex,
std.random,std.uni,std.traits,std.variant;
import core.stdc.stdio:freopen;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
immutable int mod=1000000007;
@property pure nothrow T lcm (T)(auto ref T a,auto ref T b)
{
	return a/gcd(a,b)*b;
}
pure nothrow @property X binpow(X,Y)(X base,Y exp)
if(is(typeof(exp&1)))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow @property auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
if(is(typeof(exp&1)))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@property void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
@property void putarr(X)(X a,in int n,in int m)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
@property bool getarr(X)(X a,in int n){bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0) {return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
struct pair(X,Y)
{
	X first;
	Y second;
	alias first fi;
	alias second se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
	}
	this(this){fi=fi;se=se;}
	this(A,B)(auto ref pair!(A,B) p)
	{
		fi=p.fi;
		se=p.se;
	}
	int opCmp(in pair!(X,Y) s_) const pure nothrow @safe
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(in X x_,in Y y_) pure nothrow @safe
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_;}
X cub(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_*a_;}
nothrow @nogc @system void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow @nogc @system void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
auto arread(T)(){return readln.split.map!(to!(T)).array;}
nothrow @property pure size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (!(a[l]<g))?l:r;
}
pure @property nothrow size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(g<a[m])r=m;
		else l=m;
	}
	return (g<a[l])?l:r;
}
pure @property nothrow size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (g==a[l])?l:a.length;
}
pure @property nothrow bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	return binf(a,g)!=a.length;
}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n,k;
	while(input(&n,&k))
	{
		readln;
		auto t=arread!int;
		auto r=fold!"a+(b<0)"(t);
		if(r>k){writeln(-1);return;}
		int ans;
		int[] pos;
		auto q=rbt!(true,int);
		foreach(i,p;t)
		{
			if(p<0)
			{
				k--;
				if(pos.length>0 && i-pos[$-1]>1){ q.insert(i-pos[$-1]-1);ans+=2;}
				else if(pos.length==0) ans+=2;
				pos~=i;
			}
		}
		while(!q.empty && k>=q.front)
		{
			k-=q.front;
			q.removeFront;
			ans-=2;
		}
		if(pos[$-1]<n-1 && k>=n-pos[$-1]-1)ans--;
		writeln(ans);
	}
	debug readln;
}

import std.bigint,std.container,std.array,std.algorithm,std.conv,std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.typecons,std.regex,
std.random,std.uni,std.traits,std.variant;
import core.stdc.stdio:freopen;
import std.stdio;
//import core.stdc.stdio;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias BoyerMooreFinder strfind;
immutable int mod=1000000007;
@property pure nothrow T lcm (T)(auto ref T a,auto ref T b)
{
	return a/gcd(a,b)*b;
}
pure nothrow @property X binpow(X,Y)(X base,Y exp)
if(is(typeof(exp&1)))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow @property auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
if(is(typeof(exp&1)))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@property void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
@property void putarr(X)(X a,in int n,in int m)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
@property bool getarr(X)(X a,in int n){bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0) {return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
struct pair(X,Y)
{
	X first;
	Y second;
	alias first fi;
	alias second se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
	}
	this(this){fi=fi;se=se;}
	this(A,B)(auto ref pair!(A,B) p)
	{
		fi=p.fi;
		se=p.se;
	}
	int opCmp(in pair!(X,Y) s_) const pure nothrow @safe
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(in X x_,in Y y_) pure nothrow @safe
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_;}
X cub(X)(in X a_) pure nothrow @property @safe @nogc {return a_*a_*a_;}
nothrow @nogc @system void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow @nogc @system void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
auto arread(T)(){return readln.split.map!(to!(T)).array;}
nothrow @property pure size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (!(a[l]<g))?l:r;
}
pure @property nothrow size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(g<a[m])r=m;
		else l=m;
	}
	return (g<a[l])?l:r;
}
pure @property nothrow size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	size_t l=0,r=a.length;
	while(r-l>1)
	{
		auto m=(l+r)>>1;
		if(!(a[m]<g))r=m;
		else l=m;
	}
	return (g==a[l])?l:a.length;
}
pure @property nothrow bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
{
	return binf(a,g)!=a.length;
}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin cumulativeFold schwartzSort multiSort partialSort heapify join filter
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	int n,k;
	while(input(&n,&k))
	{
		readln;
		auto t=arread!int;
		int r;
		foreach(i;t)if(i<0)r++;
		debug writeln(r);
		if(r>k){writeln(-1);return;}
		int ans;
		int[] pos;
		auto q=rbt!(true,int);
		foreach(i,p;t)
		{
			if(p<0)
			{
				k--;
				if(pos.length>0 && i-pos[$-1]>1){ q.insert(i-pos[$-1]-1);ans+=2;}
				else if(pos.length==0) ans+=2;
				pos~=i;
			}
		}
		while(!q.empty && k>=q.front)
		{
			k-=q.front;
			q.removeFront;
			ans-=2;
		}
		if(pos[$-1]<n-1 && k>=n-pos[$-1]-1)ans--;
		writeln(ans);
	}
	debug readln;
}


import std.stdio;
import std.string;
import core.stdc.stdio;
import std.math;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int p, q;
	int c = 0;
	foreach (int i; 0..n)
	{
		scanf("%d %d", &p, &q);
		if (q - p >= 2) c++;
	}
	printf("%d", c);
	return 0;
}

import std.stdio;

void main() {
  int n; readf(" %s", &n);
  int ans = 0;
  for (int i = 0; i < n; i++) {
    int p, q; readf(" %s %s", &p, &q);
    if (p + 2 <= q) {
      ans++;
    }
  }
  writeln(ans);
}


import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex;
import std.bigint;
import std.traits;

void main()
{
	auto n = readln().chomp().to!int();
	auto enemy = new long[][](n, 2);
	long score, kenemy;

	foreach (ref e; enemy) {
		e = readln().split().map!(to!long)().array();
	}
	enemy.sort!("a[1] < b[1]");

	auto t = readln().chomp().to!int();
	auto mag = readln().split().map!(to!long)().array();
	mag ~= 1e18.to!long();
	auto m = 1;
	int cur;

	foreach (ref e; enemy) {
		while (e[0]) {
			if (kenemy + e[0] <= mag[cur]) {
				score += e[0] * e[1] * m;
				kenemy += e[0];
				e[0] = 0;
			} else {
				score += (mag[cur] - kenemy) * e[1] * m;
				e[0] -= mag[cur] - kenemy;
				kenemy += mag[cur] - kenemy;
				cur++;
				m++;
			}
		}
	}

	score.writeln();
}

import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex;
import std.bigint;
import std.traits;

void main()
{
	auto n = readln().chomp().to!int();
	auto enemy = new int[][](n, 2);
	long score, kenemy;

	foreach (ref e; enemy) {
		e = readln().split().map!(to!int)().array();
	}
	enemy.sort!("a[1] < b[1]");

	auto t = readln().chomp().to!int();
	auto mag = readln().split().map!(to!long)().array();
	mag ~= 1e18.to!long();
	auto m = 1;
	int cur;

	foreach (ref e; enemy) {
		while (e[0]) {
			if (kenemy + e[0] <= mag[cur]) {
				score += e[0] * e[1] * m;
				kenemy += e[0];
				e[0] = 0;
			} else {
				score += (mag[cur] - kenemy) * e[1] * m;
				e[0] -= mag[cur] - kenemy;
				kenemy += mag[cur] - kenemy;
				cur++;
				m++;
			}
		}
	}

	score.writeln();
}

import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex;
import std.bigint;
import std.traits;

void main()
{
	auto n = readln().chomp().to!int();
	auto enemy = new int[][](n, 2);
	long score, kenemy;

	foreach (ref e; enemy) {
		e = readln().split().map!(to!int)().array();
	}
	auto t = readln().chomp().to!int();
	auto mag = readln().split().map!(to!long)().array();
	mag ~= 1e18.to!long();
	auto m = 1;
	int cur;

	foreach (ref e; enemy) {
		while (e[0]) {
			if (kenemy + e[0] <= mag[cur]) {
				score += e[0] * e[1] * m;
				kenemy += e[0];
				e[0] = 0;
			} else {
				score += (mag[cur] - kenemy) * e[1] * m;
				e[0] -= mag[cur] - kenemy;
				kenemy += mag[cur] - kenemy;
				cur++;
				m++;
			}
		}
	}

	score.writeln();
}


import std.algorithm,std.numeric,std.stdio;
void main(){
	readln;long m,d,w;
	while(readf!(" %s %s %s")(m,d,w)>0){
		auto e=d-1,s=w/gcd(e,w),a=min(d,m),p=a/s;
		writeln(e?(a*2-p*s-s)*p/2:0);
}}

import std.algorithm, std.numeric, std.stdio;
void main () {
	readln;
	long m, d, w;
	while (readf !(" %s %s %s") (m, d, w) > 0) {
		auto e = d - 1, s = w / gcd (e, w), a = min (d, m), p = a / s;
		writeln (e ? (a * 2 - (p + 1) * s) * p / 2 : 0);
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		long m, d, w;
		readf !(" %s %s %s") (m, d, w);
		auto rem = (m * d) % w;
		auto dist = d - 1;
		if (dist == 0)
		{
			writeln (0);
			continue;
		}
		auto g = gcd (dist, w);
		auto len = dist / g * w;
		auto step = len / dist;
		long res = 0;
		long first = min (d, m) - step;
		long next = min (d, m) - step * 2;
		debug {writeln (first, " ", next);}
		if (first <= 0)
		{
			res = 0;
		}
		else if (next <= 0)
		{
			res = first;
		}
		else
		{
			long num = first / (first - next);
			long last = first - step * num;
			res = (num + 1) * (first + last) / 2;
		}
		writeln (res);
	}
}

import std.algorithm,std.numeric,std.stdio;
void main(){
	readln;long m,d,w;
	while(readf!(" %s %s %s")(m,d,w)>0){
		auto e=d-1,s=w/gcd(e,w),a=min(d,m),p=a/s;
		writeln(e?(a*2-p*s-p)*p/2:0);
}}


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 = 998244353;
//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 main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto s = RD!int;
		while (s >= 10)
		{
			auto r = s % 10;
			ans[ti] += s - r;
			s /= 10;
			s += r;
		}
		ans[ti] += s;
	}

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

import std.stdio;

void main()
{
    int t;
    readf!"%d\n"(t);

    foreach (i; 0..t) {
        ulong n;
        readf!"%d\n"(n);
        ulong s = 0;

        while (n > 0) {
            if (n < 10) {
                s += n;
                break;
            } else {
                auto a = n - n % 10;
                s += a;
                n = a / 10 + n % 10;
            }
        }

        writeln(s);
    }
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
import std.algorithm.mutation;
import std.container.array;

string[] tokens;

string readToken()
{
    while (tokens.empty)
    {
        tokens = readln.split;
    }
    auto token = tokens.front;
    tokens.popFront;
    return token;
}

int readInt()
{
    return readToken.to!int;
}

void main()
{
    int T = readInt;
    while (T--)
    {
        int n = readInt;
        int res = 0;
        while (n >= 10)
        {
            res += n - n % 10;
            n = n % 10 + n / 10;
        }
        writeln(res + n);
    }
}

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

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

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

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

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

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

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

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

    }
}

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

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

void main()
{
  auto t = next!int;
  foreach(tc; 0 .. t)
    {
      auto s = next!long;
      auto res = long(0);
      while(s >= 10)
        {
          res += (s / 10) * 10;
          s += (s / 10) - (s / 10) * 10;
        }
      res += s;
      writeln(res);
    }
}


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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new char[][](t);
	foreach (ti; 0..t)
	{
		auto s = RD!string;
		auto x = RD!int;
		auto n = s.length;

		ans[ti].length = s.length;
		ans[ti][] = '1';
		foreach (i; 0..s.length)
		{
			if (s[i] == '0')
			{
				if (i >= x)
				{
					ans[ti][i-x] = '0';
				}
				if (i < n-x)
				{
					ans[ti][i+x] = '0';
				}
			}
		}

		foreach (i; 0..s.length)
		{
			if (s[i] == '1')
			{
				bool ok;
				if (i >= x)
				{
					ok |= ans[ti][i-x] == '1';
				}
				if (i < n-x)
				{
					ok |= ans[ti][i+x] == '1';
				}
				if (!ok)
				{
					ans[ti].length = 0;
					break;
				}
			}
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln(-1);
		else
			writeln(e);
	}
	stdout.flush;
	debug readln;
}

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

void main ()
{
	foreach (test; 0..readln.strip.to !(int))
	{
		auto s = readln.strip;
		auto x = readln.strip.to !(int);
		auto n = s.length.to !(int);
		auto w = new char [n];
		w[] = '1';
		foreach (i; 0..n)
		{
			if (s[i] == '0')
			{
				if (i - x >= 0)
				{
					w[i - x] = '0';
				}
				if (i + x < n)
				{
					w[i + x] = '0';
				}
			}
		}
		bool ok = true;
		foreach (i; 0..n)
		{
			if (s[i] == '1')
			{
				if (!(i - x >= 0 && w[i - x] == '1') &&
				    !(i + x < n && w[i + x] == '1'))
				{
					ok = false;
				}
			}
		}
		writeln (ok ? w : "-1");
	}
}


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, k;
    readf("%s %s", &n, &k);
    readln;

    auto arr = [0] ~ readln.chomp.split.map!(to!int).array;

    debug { arr.writeln; }

    arr.sort();

    auto dp = new int[][] (n+1, k+1);
    foreach (ref rw; dp) rw.fill(0);

    foreach (i; 1 .. n+1) {
        int mnval = arr[i] - 5;
        auto bigger = arr[1 .. $].assumeSorted.upperBound(mnval - 1);

        int prev = n - (bigger.length.to!int);

        foreach (j; 1 .. k+1) {
            dp[i][j] = max(dp[i-1][j], dp[prev][j-1] + i - prev);
        }
    }

    debug { dp.each!writeln; }

    dp[n][k].writeln;
}

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, k;
    readf("%s %s", &n, &k);
    readln;

    auto arr = [0] ~ readln.chomp.split.map!(to!int).array;

    debug { arr.writeln; }

    arr.sort();

    auto dp = new int[][] (n+1, k+1);
    foreach (ref rw; dp) rw.fill(0);

    int prev = 0;
    foreach (i; 1 .. n+1) {
        int mnval = arr[i] - 5;
        while (arr[prev+1] < mnval) { prev += 1; }

        foreach (j; 1 .. k+1) {
            dp[i][j] = max(dp[i-1][j], dp[prev][j-1] + i - prev);
        }
    }

    debug { dp.each!writeln; }

    dp[n][k].writeln;
}


import std.stdio;
import std.algorithm;

void main() {
  int t;
  readf(" %s", &t);
  while(t-- > 0) {
    int n, x, a, b;
    readf(" %s %s %s %s", &n, &x, &a, &b);
    if(a > b) swap(a, b);
    int d = min(x, a - 1);
    a -= d;
    x -= d;
    d = min(n - b, x);
    b += d;
    x -= d;
    writef("%s\n", b - a);
  }
}

import std.stdio;
import std.math;
int main()
{
	int a=0;
	readf(" %d", &a);
	for (int i=0; i<a; i++)
	{
		int b=0;
		int c=0;
		int d=0;
		int e=0;
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		readf(" %d", &e);
		if (abs(d-e)+c>=b)
		{
			writeln(b-1);
		}
		else
		{
			writeln(abs(d-e)+c);
		}
	}
	return 0;
}

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998244353;
//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 main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto x = RD!int;
		auto a = RD!int-1;
		auto b = RD!int-1;
		auto aa = min(a, b);
		auto bb = max(a, b);
		auto cnt1 = min(aa, x);
		x -= cnt1;
		aa -= cnt1;
		auto cnt2 = min(n-bb-1, x);
		bb += cnt2;
		ans[i] = bb - aa;
	}

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

import std.stdio;
import std.math;
int main()
{
	int a=0;
	readf(" %d", &a);
	for (int i=0; i<a; i++)
	{
		int b=0;
		int c=0;
		int d=0;
		int e=0;
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		readf(" %d", &e);
		if (abs(d-e)+c>=b)
		{
			writeln(b-2);
		}
		else
		{
			writeln(abs(d-e)+c);
		}
	}
	return 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()
{
    auto r = () => readln.chomp.to!(dchar[]);
    auto s = r();
    auto t = r();

    debug { writeln(s, ' ', t); }

    int n = s.length.to!int;
    auto ans = new dchar[] (n);
    auto sl = DList!dchar(s.sort().array[0 .. (n+1) / 2]);
    auto tl = DList!dchar(t.sort().array[(n+1) / 2 .. $]);

    debug { sl.each!write; writeln; tl.each!write; writeln; }

    int lft = 0, rt = n-1;
    foreach (i; 0 .. n) {
        if (i % 2 == 0) {
            if (i == n-1 || sl.front < tl.back) {
                ans[lft] = sl.front;
                sl.removeFront();
                lft += 1;
            } else {
                ans[rt] = sl.back;
                sl.removeBack();
                rt -= 1;
            }
        } else {
            if (i == n-1 || sl.front < tl.back) {
                ans[lft] = tl.back;
                tl.removeBack();
                lft += 1;
            } else {
                ans[rt] = tl.front;
                tl.removeFront();
                rt -= 1;
            }
        }
    }

    ans.writeln;
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const S = readToken();
      const T = readToken();
      const N = cast(int)(S.length);

      auto as = new int[N];
      auto bs = new int[N];
      foreach (i; 0 .. N) {
        as[i] = S[i] - 'a';
        bs[i] = T[i] - 'a';
      }
      as.sort;
      bs.sort;
      int al = 0, ar = (N + 1) / 2;
      int bl = N - N / 2, br = N;

      auto cs = new int[N];
      int cl = 0, cr = N;
      for (; ; ) {
        // min
        if (al == ar) {
          break;
        }
        if (bl == br || as[al] < bs[br - 1]) {
          cs[cl++] = as[al++];
        } else {
          cs[--cr] = as[--ar];
        }
        // max
        if (bl == br) {
          break;
        }
        if (al == ar || bs[br - 1] > as[al]) {
          cs[cl++] = bs[--br];
        } else {
          cs[--cr] = bs[bl++];
        }
      }

      auto ans = new char[N];
      foreach (i; 0 .. N) {
        ans[i] = cast(char)('a' + cs[i]);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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()
{
    auto r = () => readln.chomp.to!(dchar[]);
    auto s = r();
    auto t = r();

    debug { writeln(s, ' ', t); }

    int n = s.length.to!int;
    auto ans = new dchar[] (n);
    auto sl = DList!dchar(s.sort().array[0 .. (n+1) / 2]);
    auto tl = DList!dchar(t.sort().array[(n+1)/2 .. $]);

    debug { writeln(sl.back, ' ', tl.front); }

    int lft = 0, rt = n-1;
    foreach (i; 0 .. n) {
        if (i % 2 == 0) {
            if (i == n-1 || sl.front < tl.back) {
                ans[lft] = sl.front;
                sl.removeFront();
                lft += 1;
            } else {
                ans[rt] = sl.back;
                sl.removeBack();
                rt -= 1;
            }
        } else {
            if (i == n-1 || sl.front < tl.back) {
                ans[lft] = tl.back;
                tl.removeBack();
                lft += 1;
            } else {
                ans[rt] = tl.front;
                tl.removeFront();
                rt -= 1;
            }
        }
    }

    ans.writeln;
}

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()
{
    auto r = () => readln.chomp.to!(dchar[]);
    auto s = r();
    auto t = r();

    debug { writeln(s, ' ', t); }

    int n = s.length.to!int;
    auto ans = new dchar[] (n);
    auto sl = DList!dchar(s.sort().array[0 .. (n+1) / 2]);
    auto tl = DList!dchar(t.sort().array[(n+1)/2 .. $]);

    debug { writeln(sl.back, ' ', tl.front); }

    int lft = 0, rt = n-1;
    foreach (i; 0 .. n) {
        if (i % 2 == 0) {
            if (i == n-1 || sl.front <= tl.back) {
                ans[lft] = sl.front;
                sl.removeFront();
                lft += 1;
            } else {
                ans[rt] = sl.back;
                sl.removeBack();
                rt -= 1;
            }
        } else {
            if (i == n-1 || sl.front <= tl.back) {
                ans[lft] = tl.back;
                tl.removeBack();
                lft += 1;
            } else {
                ans[rt] = tl.front;
                tl.removeFront();
                rt -= 1;
            }
        }
    }

    ans.writeln;
}

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;
immutable int MX = 5000;

void main()
{
    auto r = () => readln.chomp.to!(dchar[]);
    auto s = r().sort();
    auto t = r().sort();

    debug { writeln(s, ' ', t); }

    string ans;
    int sidx = 0, tidx = t.length.to!int - 1;
    foreach (i; 0 .. s.length) {
        if (i % 2 == 0) {
            ans ~= s[sidx];
            sidx += 1;
        } else {
            ans ~= t[tidx];
            tidx -= 1;
        }
    }

    ans.writeln;
}


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;
bool DEBUG = 0; void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void main(string[] args){ if(args.canFind("-debug")) DEBUG = 1;
if(args.canFind("-gen")) gen; else if(args.canFind("-jury")) jury; else solve; }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); }
void print(T, A ...)(T t, A a){ std.stdio.write(t, " "), print(a); }
string unsplit(T)(T xs, string d=" "){ return xs.array.to!(string[]).join(d); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T mini(T)(ref T x, T y){ if(x > y) x = y; return x; } T maxi(T)(ref T x, T y){ if(x < y) x = y; return x; }
T mid(T)(T l, T r, bool delegate(T) f){ T m=(l+r)/2; (f(m)?l:r)=m; return f(l)?f(r-1)?r:mid(l,r,f):l; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void gen(){ // テストケース
	int t = uniform(1, 5);
	t.print;
	foreach(_; 0 .. t){
		int n = uniform(1, 5), m = uniform(1, 5);
		print(n, m);
		foreach(j; 0 .. m){
			int[] as;
			foreach(i; 0 .. n) if(uniform(0, 2) == 0) as ~= i;
			if(as.length == 0) as ~= uniform(0, n);
			as.randomShuffle;
			print(as.length, as.map!(a => a + 1).unsplit);
		}
	}
}
void jury(){ // 愚直解
	int q = scan!int;
	int[] ns, ms;
	int[][][] ar = new int[][][](q);
	foreach(t; 0 .. q){
		int n = scan!int, m = scan!int;
		ns ~= n, ms ~= m;
		foreach(j; 0 .. m){
			int k = scan!int;
			int[] as = scan!int(k).map!(x => x - 1).array;
			ar[t] ~= as;
		}
	}
	foreach(t; 0 .. q){
		string yesno = scan;
		if(yesno == "NO") "NO".print;
		else{
			int[] ans = scan!int(ms[t]).map!(a => a - 1).array;
			int[] cnt = new int[](ns[t]);
			foreach(j, an; ans){
				if( ! ar[t][j].canFind(an)) print("not available", j + 1);
				cnt[an] += 1;
			}
			foreach(i; 0 .. ns[t]) if(cnt[i] > (ms[t] + 1) / 2) print("too much", i + 1);
			"YES".print;
			ans.map!(a => a + 1).unsplit.print;
		}
	}
}
void solve(){ // 提出解
	A: foreach(_; 0 .. scan!int){
		int n = scan!int, m = scan!int;
		int ceilm2 = (m + 1) / 2;
		int[][] ass;
		int[][] lones = new int[][](n);
		int[][] others = new int[][](n);
		foreach(j; 0 .. m){
			int k = scan!int;
			int[] as = scan!int(k).map!(x => x - 1).array;
			if(as.length == 1) lones[as[0]] ~= j;
			else foreach(a; as) others[a] ~= j;
			ass ~= as;
		}
		log("ass:", ass);
		log("lones:", lones);
		log("others:", others);

		foreach(i; 0 .. n){
			if(lones[i].length > ceilm2){
				"NO".print;
				continue A;
			}
		}
		int[][] us = new int[][](n);
		int[] ans = new int[](m);
		ans.fill(-1);

		int foundi = -1;
		B: foreach(i; 0 .. n){
			if(lones[i].length + others[i].length >= ceilm2){
				// found
				foundi = i;
				foreach(j; lones[i]) us[i] ~= j, ans[j] = i;
				foreach(j; others[i]){
					if(us[i].length == ceilm2) break;
					us[i] ~= j, ans[j] = i;
				}
				log("i:", i, "found", "us:", us, "ans:", ans);
				break B;
			}
		}
		foreach(j; 0 .. m){
			if(ans[j] >= 0) continue;
			if(ass[j][0] == foundi) ans[j] = ass[j][1];
			else ans[j] = ass[j][0];
		}

		"YES".print;
		ans.map!(a => a + 1).array.unsplit.print;

	}
}
/*
一人での出現回数がceil(m/2)を超えている人がいる場合
	→NO
複数名での出現を含めてならceil(m/2)を超えている人がいる場合
	→その人にぴったりceil(m/2)回を取らせればあとはてきとうでよい
	　そのために、一人での出現回はその人にとらせ、
	　あとはceil(m/2)になるまでとらせる。その人はもう終わり。
出現回数ceil(m/2)を超えている人がいない場合
	→絶対安全なのでてきとうに取ればよい
*/

import std.stdio;
import std.container;
import std.algorithm;

/*
a[i]-a[i-1] = c (mod m)
a[1] = s mod m
m > a[i] for i=1,...,n

arbitrary s
m | a[1]-s
m | a[i]-(a[i-1]+c) = a[i]-a[i-1]-c

1 positive, 1 negative at MAX
a = -b => mod is a-(-b).

if only positive or only negative, m can be arbitrary large
if >1 pos or >1 neg, impossible.
*/

void main() {
    int t; readf(" %d",&t);
    while (t--) {
        int n,m; readf(" %d %d",&n,&m);
        int[][] a = new int[][](m+1);
        int[] id = new int[m+1];
        foreach (int i, ref e; id) {e=i;}
        //writeln("id=",id);
        foreach (i; 1..m+1) {
            int k_i; readf(" %d",&k_i);
            foreach(j; 0..k_i) {
                int x; readf(" %d",&x);
                a[i] ~= x;
            }
            sort((a[i])[0..$]);
        }
        auto cmp = delegate bool(int i, int j) {
            if (a[i].length != a[j].length) return a[i].length < a[j].length;
            return a[i]<a[j];
        };
        sort!(cmp)(id[1..$]);
        //writeln(id);

        int[] cnt = new int[n+1];
        bool feasible = true;
        int[] sol = new int[m+1];
        foreach (i; id[1..$]) {
            bool flag = false;
            int[] b = a[i];
            foreach (e; b) {
                if (cnt[e]<(m+1)/2) {
                    flag = true;
                    sol[i] = e;
                    ++cnt[e];
                    break;
                }
            }
            if (!flag) {
                feasible = false;
                break;
            }
        }
        if (feasible) {
            writeln("YES");
            foreach (e; sol[1..$]) {
                write(e," ");
            }
            writeln();
        }
        else 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;
bool DEBUG = 0; void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void main(string[] args){ if(args.canFind("-debug")) DEBUG = 1;
if(args.canFind("-gen")) gen; else if(args.canFind("-jury")) jury; else solve; }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); }
void print(T, A ...)(T t, A a){ std.stdio.write(t, " "), print(a); }
string unsplit(T)(T xs, string d=" "){ return xs.array.to!(string[]).join(d); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T mini(T)(ref T x, T y){ if(x > y) x = y; return x; } T maxi(T)(ref T x, T y){ if(x < y) x = y; return x; }
T mid(T)(T l, T r, bool delegate(T) f){ T m=(l+r)/2; (f(m)?l:r)=m; return f(l)?f(r-1)?r:mid(l,r,f):l; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
void gen(){ // テストケース
}
void jury(){ // 愚直解
}
void solve(){ // 提出解
	A: foreach(_; 0 .. scan!int){
		int n = scan!int, m = scan!int;
		int ceilm2 = (m + 1) / 2;
		int[][] ass;
		int[][] lones = new int[][](n);
		int[][] others = new int[][](n);
		foreach(j; 0 .. m){
			int k = scan!int;
			int[] as = scan!int(k).map!(x => x - 1).array;
			if(as.length == 1) lones[as[0]] ~= j;
			else foreach(a; as) others[a] ~= j;
			ass ~= as;
		}
		log("ass:", ass);
		log("lones:", lones);
		log("others:", others);

		foreach(i; 0 .. n){
			if(lones[i].length > ceilm2){
				"NO".print;
				continue A;
			}
		}
		int[][] us = new int[][](n);
		int[] ans = new int[](m);
		ans.fill(-1);

		B: foreach(i; 0 .. n){
			if(lones[i].length + others[i].length >= ceilm2){
				// found
				foreach(j; lones[i]) us[i] ~= j, ans[j] = i;
				foreach(j; others[i]){
					if(us[i].length == ceilm2) break;
					us[i] ~= j, ans[j] = i;
				}
				foreach(j; 0 .. m){
					if(ans[j] >= 0) continue;
					if(ass[j][0] == i) ans[j] = ass[j][1];
					else ans[j] = ass[j][0];
				}
				log("i:", i, "found", "us:", us, "ans:", ans);
				break B;
			}
		}

		"YES".print;
		ans.map!(a => a + 1).array.unsplit.print;

	}
}
/*
一人での出現回数がceil(m/2)を超えている人がいる場合
	→NO
複数名での出現を含めてならceil(m/2)を超えている人がいる場合
	→その人にぴったりceil(m/2)回を取らせればあとはてきとうでよい
	　そのために、一人での出現回はその人にとらせ、
	　あとはceil(m/2)になるまでとらせる。その人はもう終わり。
出現回数ceil(m/2)を超えている人がいない場合
	→絶対安全なのでてきとうに取ればよい
*/


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

string FMT_F = "%.10f";

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

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

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

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

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

		int mode;
		foreach (i; 0..n)
		{
			if (a[i] == i)
			{
				if (mode == 1)
					mode = 2;
			}
			else
			{
				if (mode == 0)
					mode = 1;
				else if (mode == 2)
					mode = 3;
			}
		}

		if (mode == 0) continue;
		else if (mode == 1 || mode == 2)
			ans[ti] = 1;
		else
			ans[ti] = 2;
	}

	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto p0 = enumerate (p);
		auto p1 = p0.find !(q{a[0] != a[1]});
		auto p2 = p1.find !(q{a[0] == a[1]});
		auto p3 = p2.find !(q{a[0] != a[1]});
		writeln (p1.empty ? 0 : p3.empty ? 1 : 2);
	}
}

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 p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto s = n.iota.map !(i => i == p[i]).sum;
		writeln (s == n ? 0 : s == 0 ? 1 : 2);
	}
}

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 p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto p0 = enumerate (p);
		writeln (p0);
		auto p1 = p0.find !(q{a[0] != a[1]});
		auto p2 = p1.find !(q{a[0] == a[1]});
		auto p3 = p2.find !(q{a[0] != a[1]});
		writeln (p1.empty ? 0 : p3.empty ? 1 : 2);
	}
}


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, m;
    readf("%s %s", &n, &m);
    readln;

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

    Tuple!(int, int, int)[] s;

    foreach (i; 0 .. m) {
        int le, r;
        readf("%s %s", &le, &r);
        readln;

        --le, --r;
        s ~= tuple(le, r, i+1);
    }

    s.sort();

    auto rbt = make!(RedBlackTree!(int, "a < b", true));
    foreach (e; arr) { rbt.insert(e); }

    debug { rbt.writeln; }

    int mx = 0;
    int[] ans;
    auto curseg = make!(RedBlackTree!int);
    auto ends = new Tuple!(int, int)[][] (n);
    int sidx = 0;
    foreach (i; 0 .. n) {
        while (sidx < m && s[sidx][0] == i) {
            foreach (j; s[sidx][0] .. s[sidx][1] + 1) {
                rbt.removeKey(arr[j]);
                arr[j] -= 1;
                rbt.insert(arr[j]);

                curseg.insert(s[sidx][2]);
            }

            ends[s[sidx][1]] ~= tuple(s[sidx][0], s[sidx][2]);
            sidx += 1;
        }

        if (rbt.back - arr[i] > mx) {
            ans = [];
            foreach (e; curseg) { ans ~= e; }
            mx = rbt.back - arr[i];
        }

        foreach (t; ends[i]) {
            int end = t[0], segid = t[1];
            foreach (j; end .. i+1) {
                rbt.removeKey(arr[j]);
                arr[j] += 1;
                rbt.insert(arr[j]);

                curseg.removeKey(segid);
            }
        }
    }

    mx.writeln;
    ans.length.writeln;
    ans.writefln!"%(%s %)";
}

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 s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = readln.split.map!(to!long).array;
    auto LR = new Tuple!(int, int, int)[](M);
    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        LR[i] = tuple(s[0]-1, s[1]-1, i);
    }
    LR.sort();

    auto pq = new BinaryHeap!(Array!(Tuple!(int, int, int)), "a[1] > b[1]")();
    auto st = new LazySegmentTree!(long, long, min, (a,b)=>a+b, (a,b)=>a+b, (a,b)=>a, 1L<<59, 0L)(N+1);
    st.table[] = 0L;

    foreach (i; 0..N) st.update(i, i, A[i]);
    foreach (i; 0..M) st.update(LR[i][0], LR[i][1], -1);

    int p = 0;
    long maxv = 0;
    long maxi = 0;

    foreach (i; 0..N) {
        while (p < M && LR[p][0] == i) {
            st.update(LR[p][0], LR[p][1], 1);
            pq.insert(LR[p]);
            ++p;
        }
        while (!pq.empty && pq.front[1] < i) {
            st.update(pq.front[0], pq.front[1], -1);
            pq.removeFront;
        }

        long tmp = st.query(i, i) - st.query(0, N-1);
        if (tmp >= maxv)  {
            maxv = tmp;
            maxi = i;
        }
    }

    Tuple!(int, int, int)[] seg;
    foreach (i; 0..M) {
        if (LR[i][1] < maxi || LR[i][0] > maxi) {
            seg ~= LR[i];
        }
    }

    maxv.writeln;
    seg.sort!"a[2] < b[2]";
    seg.length.writeln;
    foreach (sg; seg) {
        write(sg[2]+1, " ");
    }
    writeln;
}

class LazySegmentTree(T, L, alias opTT, alias opTL, alias opLL, alias opPrd, T eT, L eL) {
    T[] table;
    L[] lazy_;
    int n;
    int size;

    this(int n) {
        this.n = n;
        size = 1;
        while (size <= n) size <<= 1;
        size <<= 1;
        table = new T[](size);
        lazy_ = new L[](size);
        table[] = eT;
        lazy_[] = eL;
    }

    void push(int i, int a, int b) {
        if (lazy_[i] == eL) return;
        table[i] = opTL(table[i], opPrd(lazy_[i], b - a + 1));
        if (i * 2 + 1 < size) {
            lazy_[i*2] = opLL(lazy_[i*2], lazy_[i]);
            lazy_[i*2+1] = opLL(lazy_[i*2+1], lazy_[i]);
        }
        lazy_[i] = eL;
    }

    T query(int l, int r) {
        if (l > r) return eT;
        return query(l, r, 1, 0, n-1);
    }

    T query(int l, int r, int i, int a, int b) {
        if (b < l || r < a) return eT;
        push(i, a, b);
        if (l <= a && b <= r) {
            return table[i];
        } else {
            return opTT(query(l, r, i*2, a, (a+b)/2), query(l, r, i*2+1, (a+b)/2+1, b));
        }
    }

    void update(int l, int r, L val) {
        if (l > r) return;
        update(l, r, 1, 0, n-1, val);
    }

    void update(int l, int r, int i, int a, int b, L val) {
        if (b < l || r < a) {
            push(i, a, b);
        } else if (l <= a && b <= r) {
            lazy_[i] = opLL(lazy_[i], val);
            push(i, a, b);
        } else {
            push(i, a, b);
            update(l, r, i*2, a, (a+b)/2, val);
            update(l, r, i*2+1, (a+b)/2+1, b, val);
            table[i] = opTT(table[i*2], table[i*2+1]);
        }
    }
}


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

int sign (int x) {
  if (!x) return 0;
  if (x > 0) return 1;
  return -1;
}

long test () {
  auto s = readln.splitter.map!(to!int);
  immutable n = s.front;
  s.popFront;
  immutable x = s.front;
  auto t = readln[0 .. n];
  auto a = new int[n+1];
  foreach (i; 0 .. n) {
    a[i+1] = a[i] + (t[i] == '1' ? -1 : 1);
  }
  debug stderr.writeln (a);
  immutable m = a.back;
  if (m == 0) {
    return (minElement (a) <= x && x <= maxElement (a)) ? -1 : 0;
  }
  long r = 0;
  foreach (i; 0 .. n) {
    int delta = x - a[i];
    if (m > 0) {
      if (delta >= 0 && !(delta % m)) ++r;
    } else {
      if (delta <= 0 && !((-delta) % (-m))) ++r;
    }
  }
  return r;
}

void main() {
  auto nt = readln.strip.to!int;
  foreach (tid; 0 .. nt) {
    writeln (test ());
  }
}

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

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

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

        auto s = readln.chomp;

        auto tot = s.count!(v => v == '0').to!int - s.count!(v => v == '1').to!int;

        if (tot == 0) {
            int cur = 0, mx = 0, mn = 0;
            foreach (e; s) {
                if (e == '0') { cur += 1; }
                else { cur -= 1; }

                mx = max(mx, cur);
                mn = min(mn, cur);
            }

            writeln(mn <= x && x <= mx ? -1 : 0);
            continue;
        }

        int ans = 0, cur = 0;
        foreach (e; s) {
            if ((x-cur) % tot == 0 && (x-cur) / tot >= 0) { ans += 1; }

            if (e == '0') { cur += 1; }
            else { cur -= 1; }
        }

        ans.writeln;
    }
}


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

void main() {
    auto N = readln.chomp.to!int;
    auto A = new int[](N);
    auto B = new int[](N);
    auto AB = new Tuple!(int, int)[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        AB[i] = tuple(s[0], s[1]);
    }
    AB.sort();
    foreach (i; 0..N) {
        A[i] = AB[i][0];
        B[i] = AB[i][1];
    }

    auto dp = new int[](N);
    foreach (i; 0..N) {
        auto lb = A.assumeSorted.lowerBound(A[i] - B[i]).length;
        if (lb > 0) dp[i] += dp[lb-1];
        dp[i] += 1;
    }

    writeln(N - dp.reduce!max);
}

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;
	while (readf (" %s", &n) > 0)
	{
		alias Point = Tuple !(int, q{a}, int, q{b});
		auto p = new Point [n];
		foreach (ref q; p)
		{
			readf (" %s %s", &q.a, &q.b);
		}
		sort (p);
		p = Point (int.min / 2, 0) ~ p;

		int res = n - 1;
		auto f = new int [n + 1];
		f[0] = 1;
		foreach (i, ref q; p)
		{
			int lo = 0;
			int hi = i - 1;
			while (lo < hi)
			{
				int me = (lo + hi + 1) >> 1;
				if (p[me].a + q.b >= q.a)
				{
					hi = me - 1;
				}
				else
				{
					lo = me;
				}
			}
			debug {writeln (p[i].a, ": ", p[lo].a);}
			f[i] = f[lo] + (i - lo - 1);
			res = min (res, f[i] + (n - i));
		}
		debug {writeln (f);}
		writeln (res);
	}
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = new int[](N);
    auto B = new int[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        A[i] = s[0];
        B[i] = s[1];
    }

    auto dp = new int[](N);
    foreach (i; 0..N) {
        auto lb = A.assumeSorted.lowerBound(A[i] - B[i]).length;
        if (lb > 0) dp[i] += dp[lb-1];
        dp[i] += 1;
    }

    writeln(N - dp.reduce!max);
}


import std.stdio;
import std.string;
import std.conv;
import std.regex;
import std.file;
void main()
{

    string[] inp=split(strip(readln()));
    int n=to!int(inp[0]);
    int p=to!int(inp[1]);
    int q=to!int(inp[2]);
    string s = strip(readln());
    //writeln(n);
    for(int i = 0;i <= n;i++)
    {
        for(int j = 0;j <= n ;j++)
        {
            if(i * p + j * q == n)
            {
                writeln(i + j);
                for(int k = 0;k < i;k++){
                    writeln(s[k*p .. (k+1)*p]);
                }
                string res=s[i*p..$];
                for(int k = 0;k < j;k++){
                    writeln(res[k*q .. (k+1)*q]);
                }
                return;

            }
        }
    }
    writeln("-1");

}

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

void main ()
{
	int n, p, q;
	string buf;
	while ((buf = readln).formattedRead (" %s %s %s", &n, &p, &q) > 0)
	{
		string s = readln.strip;
		string [] res;
		while (true)
		{
			if (s.length % q == 0)
			{
				res ~= s.chunks (q).map !(text).array;
				s = "";
				break;
			}
			if (s.length < p)
			{
				break;
			}
			res ~= s[0..p];
			s = s[p..$];
		}
		if (s.empty)
		{
			writefln ("%s\n%-(%s\n%)", res.length, res);
		}
		else
		{
			writeln (-1);
		}
	}
}

module main;

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

int main()
{
    int n, p, q;

    readf(" %d %d %d", &n, &p, &q);
    readln();

    auto s = readln().strip();

    if (n % p == 0) {
        writeln(n / p);

        for (int i = 0; i < n; i += p)
            writeln(s[i..i + p]);
    } else if (n % q == 0) {
        writeln(n / q);

        for (int i = 0; i < n; i += q)
            writeln(s[i..i + q]);
    } else {
        auto temp = n;
        int count;

        while (temp % q != 0 && temp > 0)
            temp -= p, count++;

        if (temp < 0)
            writeln(-1);
        else {
            writeln(count + temp / q);

            for (int i = 0; i < temp; i += q)
                writeln(s[i..i + q]);

            for (int i = temp; i < n; i += p)
                writeln(s[i..i + p]);
        }
    }

	return 0;
}

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

void main ()
{
	int n, p, q;
	string buf;
	while ((buf = readln).formattedRead (" %s %s %s", &n, &p, &q) > 0)
	{
		string s = readln.strip;
		string [] res;
		while (s.length >= p)
		{
			if (s.length % q == 0)
			{
				res ~= s.chunks (q).map !(text).array;
				s = "";
				break;
			}
			res ~= s[0..p];
			s = s[p..$];
		}
		if (s.empty)
		{
			writefln ("%s\n%-(%s\n%)", res.length, res);
		}
		else
		{
			writeln (-1);
		}
	}
}

module main;

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

int main()
{
    int n, p, q;

    readf(" %d %d %d", &n, &p, &q);
    readln();

    auto s = readln().strip();

    if (n % p == 0) {
        writeln(n / p);

        for (int i = 0; i < n; i += p)
            writeln(s[i..i + p]);
    } else if (n % q == 0) {
        writeln(n / q);

        for (int i = 0; i < n; i += q)
            writeln(s[i..i + q]);
    } else {
        auto temp = n;

        while (temp % q != 0 && temp > 0)
            temp -= p;

        if (temp < 0)
            writeln(-1);
        else {
            for (int i = 0; i < temp; i += q)
                writeln(s[i..i + q]);

            for (int i = temp; i < n; i += p)
                writeln(s[i..i + p]);
        }
    }

	return 0;
}


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

void main ()
{
	auto n = readln.strip.to !(int);
	auto a = n.iota.map !(_ => readln.split.map !(to !(real)))
		.map !(c => atan2 (c[1], c[0]))
		.enumerate.map !(reverse).array;
	sort (a);
	a ~= a[0];
	a[n][0] += 2 * PI;
	auto b = n.iota.map !(i => tuple (a[i + 1][0] - a[i][0],
		a[i][1], a[i + 1][1])).array;
	sort (b);
	writeln (b[0][1] + 1, ' ', b[0][2] + 1);
}

import std.algorithm, std.math, std.range, std.stdio, std.typecons;

void main ()
{
    int n;
    while (readf (" %s", &n) > 0)
    {
        alias Vector = Tuple !(real, q{alpha}, int, q{num});
        auto a = new Vector [n];
        foreach (i, ref c; a)
        {
            real x, y;
            readf (" %s %s", &x, &y);
            c.alpha = atan2 (y, x);
            c.num = i + 1;
        }
        a.schwartzSort !(q{a.alpha});
        a ~= Vector (a[0].alpha + 2 * PI, a[0].num);
        auto p = n.iota.minPos !((i, j) =>
            a[i + 1].alpha - a[i].alpha <
            a[j + 1].alpha - a[j].alpha).front;
        writeln (a[p].num, ' ', a[p + 1].num);
    }
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Vector = Tuple !(real, q{x}, real, q{y},
		    real, q{alpha}, int, q{num});
		auto a = new Vector [n];
		foreach (i, ref c; a)
		{
			readf (" %s %s", &c.x, &c.y);
			c.alpha = atan2 (c.y, c.x);
			c.num = i + 1;
		}
		a.schwartzSort !(q{a.alpha});
		a ~= Vector (a[0].x, a[0].y, a[0].alpha + 2 * PI, a[0].num);
		auto p = n.iota.minPos !((i, j) =>
		    a[i + 1].alpha - a[i].alpha <
		    a[j + 1].alpha - a[j].alpha).front;
		writeln (a[p].num, ' ', a[p + 1].num);
	}
}