There is a square of size $$$10^6 \times 10^6$$$ on the coordinate plane with four points $$$(0, 0)$$$, $$$(0, 10^6)$$$, $$$(10^6, 0)$$$, and $$$(10^6, 10^6)$$$ as its vertices.You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$0 \le n, m \le 10^5$$$) — the number of horizontal segments and the number of vertical segments. The next $$$n$$$ lines contain descriptions of the horizontal segments. The $$$i$$$-th line contains three integers $$$y_i$$$, $$$lx_i$$$ and $$$rx_i$$$ ($$$0 < y_i < 10^6$$$; $$$0 \le lx_i < rx_i \le 10^6$$$), which means the segment connects $$$(lx_i, y_i)$$$ and $$$(rx_i, y_i)$$$. The next $$$m$$$ lines contain descriptions of the vertical segments. The $$$i$$$-th line contains three integers $$$x_i$$$, $$$ly_i$$$ and $$$ry_i$$$ ($$$0 < x_i < 10^6$$$; $$$0 \le ly_i < ry_i \le 10^6$$$), which means the segment connects $$$(x_i, ly_i)$$$ and $$$(x_i, ry_i)$$$. It's guaranteed that there are no two segments on the same line, and each segment intersects with at least one of square's sides.

Print the number of pieces the square is divided into after drawing all the segments.

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b);
  if (b < a) return [];
  let arr = Array(b - a + 1)
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return a;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  a = a || 0;
  b = b || (this.length - 1);
  let prev = a;
  for (let i = a; i <= b; i++) {
    if (i == b || fn(this[i], this[i + 1])) {
      arr.push(this.slice(prev, i + 1));
      prev = i + 1;
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
function inv(b, m) {
  for (var a = m, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + m) % m;
}

// let MOD = 1e9 + 7
// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;
  let [n, m] = $(2), s = 1; z = 1e6;
  let h1 = [], h2 = [];
  For(n, i => {
    let [y, l, r] = $(3)
    if (l == 0 && r == z) s++;
    if (l == 0) h1.push({ y, r });
    else h2.push({ y, l })
  })
  h1.sort((a, b) => a.r - b.r);
  h2.sort((a, b) => a.l - b.l);

  let bit1 = Arr(z + 1, i => 0), bit2 = Arr(z + 1, i => 0)

  let update = (pos, x) => {
    for (let i = pos; i <= z; i += i & -i) bit1[i] += x;
    for (let i = z - pos; i <= z; i += i & -i) bit2[i] += x;
  }
  let cal1 = pos => {
    let res = 0;
    for (let i = pos; i; i -= i & -i) res += bit1[i];
    return res;
  }
  let cal2 = pos => {
    let res = 0;
    for (let i = z - pos; i; i -= i & -i) res += bit2[i];
    return res;
  }

  let v = Arr(m, i => ({ x: $(), l: $(), r: $() }))
  v.sort((a, b) => a.x - b.x);

  let i1 = 0, i2 = 0;
  h1.forEach(h => update(h.y, 1));
  v.forEach(v => {
    while (i1 < h1.length && h1[i1].r < v.x) {
      update(h1[i1].y, -1);
      i1++;
    }
    while (i2 < h2.length && h2[i2].l <= v.x) {
      update(h2[i2].y, 1);
      i2++;
    }
    // log(s, cal1(v.l), cal2(v.l));
    if (v.l == 0 && v.r == z) s++;
    if (v.l == 0) s += cal1(v.r);
    else s += cal2(v.l);
  })

  log(s)
}

"use strict";
let For = (a, b, fn) => {
    if (!fn)
        return For(0, a - 1, b);
    let res;
    for (let i = a; i <= b; i++) {
        if ((res = fn(i)) != null)
            return res;
    }
};
let ForR = (a, b, fn) => {
    if (!fn)
        return ForR(a - 1, 0, b);
    let res;
    for (let i = a; i >= b; i--) {
        if ((res = fn(i)) != null)
            return res;
    }
};
let Arr = (a, b, fn) => {
    if (typeof (b) == 'function')
        return Arr(0, a - 1, b);
    if (b < a)
        return [];
    let arr = Array(b - a + 1);
    for (let i = a; i <= b; i++)
        arr[i] = fn(i, arr);
    return arr;
};
Object.defineProperty(Object.prototype, '$k', {
    value: function () { return Object.keys(this); }
});
Object.defineProperty(Object.prototype, '$v', {
    value: function () { return Object.values(this); }
});
Object.defineProperty(Object.prototype, '$kv', {
    value: function () { return Object.entries(this); }
});
// Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
// Array.prototype.uniq = function (fn) {
//   var set = new Set();
//   return this.filter(v => {
//     var newValue = !set.has(fn ? fn(v) : v);
//     set.add(fn ? fn(v) : v);
//     return newValue;
//   });
// }
// Array.prototype.toObj = function (fn) {
//   return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
//     p[v[0]] = v[1];
//     return p;
//   }, {})
// }
// Array.prototype.min = function (fn) {
//   let min = 1e20, index = -1, x;
//   for (let i = 0; i < this.length; i++) {
//     x = fn ? fn(this[i], i, this) : this[i];
//     if (x < min) { min = x; index = i }
//   }
//   return [this[index], index, min];
// }
// Array.prototype.max = function (fn) {
//   let max = -1e20, index = -1, x;
//   for (let i = 0; i < this.length; i++) {
//     x = fn ? fn(this[i], i, this) : this[i];
//     if (x > max) { max = x; index = i }
//   }
//   return [this[index], index, max];
// }
// Array.prototype.rev = function (first, last) {
//   for (let i = first; i < (first + last) / 2; i++) {
//     [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
//   }
// }
// Array.prototype.set = function (pos, arr) {
//   for (let i = pos; i < pos + arr.length; i++) {
//     this[i] = arr[i - pos];
//   }
// }
// Array.prototype.for = function (a, b, fn) {
//   let res
//   for (let i = a; i <= b; i++) {
//     if ((res = fn(this[i], i, this)) != null) return res;
//   }
// }
// Array.prototype.forR = function (a, b, fn) {
//   let res
//   for (let i = a; i >= b; i--) {
//     if ((res = fn(this[i], i, this)) != null) return res;
//   }
// }
// Array.prototype.bin = function (comp, a, b) {
//   let mid;
//   while (a < b) {
//     mid = (a + b) / 2 | 0;
//     if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
//     else b = mid;
//   }
//   return a;
// }
// Array.prototype.cut = function (fn, a, b) {
//   let arr = [];
//   a = a || 0;
//   b = b || (this.length - 1);
//   let prev = a;
//   for (let i = a; i <= b; i++) {
//     if (i == b || fn(this[i], this[i + 1])) {
//       arr.push(this.slice(prev, i + 1));
//       prev = i + 1;
//     }
//   }
//   return arr;
// }
function gcd(a, b) {
    while (b)
        [a, b] = [b, a % b];
    return a;
}
function mul(a, b, m) {
    return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m;
}
function pow(a, n, m) {
    let r = 1;
    while (n)
        n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1];
    return r;
}
function inv(b, m) {
    for (var a = m, u = 0, v = 1, t; b; v = t)
        (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
    return (u + m) % m;
}
// let MOD = 1e9 + 7
// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);
// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];
// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }
// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }
let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
    let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = (n) => n != null ? inp.slice(_i, _i += n) : inp[_i++], out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;
    let [n, m] = $(2), s = 1, z = 1e6;
    let h1 = [], h2 = [];
    For(n, i => {
        let [y, l, r] = $(3);
        if (l == 0 && r == z)
            s++;
        if (l == 0)
            h1.push({ y, r });
        else
            h2.push({ y, l });
    });
    h1.sort((a, b) => a.r - b.r);
    h2.sort((a, b) => a.l - b.l);
    let bit1 = Arr(z + 1, i => 0), bit2 = Arr(z + 1, i => 0);
    let update = (pos, x) => {
        for (let i = pos; i <= z; i += i & -i)
            bit1[i] += x;
        for (let i = z - pos; i <= z; i += i & -i)
            bit2[i] += x;
    };
    let cal1 = pos => {
        let res = 0;
        for (let i = pos; i; i -= i & -i)
            res += bit1[i];
        return res;
    };
    let cal2 = pos => {
        let res = 0;
        for (let i = z - pos; i; i -= i & -i)
            res += bit2[i];
        return res;
    };
    let v = Arr(m, i => ({ x: $(), l: $(), r: $() }));
    v.sort((a, b) => a.x - b.x);
    let i1 = 0, i2 = 0;
    h1.forEach(h => update(h.y, 1));
    v.forEach(v => {
        while (i1 < h1.length && h1[i1].r < v.x) {
            update(h1[i1].y, -1);
            i1++;
        }
        while (i2 < h2.length && h2[i2].l <= v.x) {
            update(h2[i2].y, 1);
            i2++;
        }
        // log(s, cal1(v.l), cal2(v.l));
        if (v.l == 0 && v.r == z)
            s++;
        if (v.l == 0)
            s += cal1(v.r);
        else
            s += cal2(v.l);
    });
    log(s);
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b);
  if (b < a) return [];
  let arr = Array(b - a + 1)
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return a;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  a = a || 0;
  b = b || (this.length - 1);
  let prev = a;
  for (let i = a; i <= b; i++) {
    if (i == b || fn(this[i], this[i + 1])) {
      arr.push(this.slice(prev, i + 1));
      prev = i + 1;
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
function inv(b, m) {
  for (var a = m, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + m) % m;
}

// let MOD = 1e9 + 7
// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;
  let [n, m] = $(2), s = 1; z = 1e6;
  let h1 = [], h2 = [];
  For(n, i => {
    let [y, l, r] = $(3)
    if (l == 0 && r == z) s++;
    if (l == 0) h1.push({ y, r });
    else h2.push({ y, l })
  })
  h1.sort((a, b) => a.r - b.r);
  h2.sort((a, b) => a.l - b.r);

  let bit1 = Arr(z + 1, i => 0), bit2 = Arr(z + 1, i => 0)

  let update = (pos, x) => {
    for (let i = pos; i <= z; i += i & -i) bit1[i] += x;
    for (let i = z - pos; i <= z; i += i & -i) bit2[i] += x;
  }
  let cal1 = pos => {
    let res = 0;
    for (let i = pos; i; i -= i & -i) res += bit1[i];
    return res;
  }
  let cal2 = pos => {
    let res = 0;
    for (let i = z - pos; i; i -= i & -i) res += bit2[i];
    return res;
  }

  let v = Arr(m, i => ({ x: $(), l: $(), r: $() }))
  v.sort((a, b) => a.x - b.x);

  let i1 = 0, i2 = 0;
  h1.forEach(h => update(h.y, 1));
  v.forEach(v => {
    while (i1 < h1.length && h1[i1].r < v.x) {
      update(h1[i1].y, -1);
      i1++;
    }
    while (i2 < h2.length && h2[i2].l <= v.x) {
      update(h2[i2].y, 1);
      i2++;
    }
    // log(s, cal1(v.l), cal2(v.l));
    if (v.l == 0 && v.r == z) s++;
    if (v.l == 0) s += cal1(v.r);
    else s += cal2(v.l);
  })

  log(s)
}


Pak Chanek has a mirror in the shape of a circle. There are $$$N$$$ lamps on the circumference numbered from $$$1$$$ to $$$N$$$ in clockwise order. The length of the arc from lamp $$$i$$$ to lamp $$$i+1$$$ is $$$D_i$$$ for $$$1 \leq i \leq N-1$$$. Meanwhile, the length of the arc between lamp $$$N$$$ and lamp $$$1$$$ is $$$D_N$$$.Pak Chanek wants to colour the lamps with $$$M$$$ different colours. Each lamp can be coloured with one of the $$$M$$$ colours. However, there cannot be three different lamps such that the colours of the three lamps are the same and the triangle made by considering the three lamps as vertices is a right triangle (triangle with one of its angles being exactly $$$90$$$ degrees).The following are examples of lamp colouring configurations on the circular mirror. Figure 1. an example of an incorrect colouring because lamps $$$1$$$, $$$2$$$, and $$$3$$$ form a right triangleFigure 2. an example of a correct colouringFigure 3. an example of a correct colouring Before colouring the lamps, Pak Chanek wants to know the number of distinct colouring configurations he can make. Count the number of distinct possible lamp colouring configurations, modulo $$$998\,244\,353$$$.

The first line contains two integers $$$N$$$ and $$$M$$$ ($$$1 \le N \le 3 \cdot 10^5$$$, $$$2 \le M \le 3 \cdot 10^5$$$) — the number of lamps in the mirror and the number of different colours used. The second line contains $$$N$$$ integers $$$D_1, D_2, \ldots, D_N$$$ ($$$1 \le D_i \le 10^9$$$) — the lengths of the arcs between the lamps in the mirror.

An integer representing the number of possible lamp colouring configurations, modulo $$$998\,244\,353$$$.

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

async function solve(read) {
  const rns = async () => {
    return (await read()).split(' ').filter(s => s !== '').map(Number);
  };
  const MOD = 998244353;
  const [n, m] = await rns();
  const a = await rns();
  const sums = [0];
  for (let i = 1; i <= n; i++) {
    sums[i] = sums[i - 1] + a[i - 1];
  }
  const map = new Map();
  map.set(0, 0);
  let cnt = 0;
  for (let i = 1; i < n; i++) {
    const x = sums[i] - sums[n] / 2;
    if (map.has(x)) cnt++;
    map.set(sums[i], i);
  }
  const N = Math.max(n, m);
  const f = new Array(N + 1);
  f[0] = 1, f[1] = 1;
  for (let i = 1; i <= N; i++) {
    f[i] = mul(f[i - 1], i);
  }
  const g = new Array(N + 1);
  g[N] = power(f[N], MOD - 2);
  for (let i = N - 1; i >= 0; i--) {
    g[i] = mul(g[i + 1], i + 1);
  }
  let res = 0;
  for (let i = 0; i <= cnt && i <= m; i++) {
    if ((m - i === 1 || m === i) && cnt > i) continue;
    let ans = mul(f[cnt], g[i], g[cnt - i], f[m], g[m - i], power(mul(m - i, m - i - 1), cnt - i), power(m - i, n - cnt * 2));
    res = (res + ans) % MOD;
  }
  return res;
}
const MOD = 998244353;
function power(a, b) {
  let res = 1;
  while (b) {
    if (b & 1) res = mul(res, a);
    a = mul(a, a);
    b = b >> 1;
  }
  return res;
}
function mul(...args) {
  if (args.length === 0) throw new Error('参数不能为空');
  if (args.length === 1) return args[0];
  const [a, b] = args;
  if (args.length > 2) return mul(mul(a, b), ...args.slice(2));
  return (Math.floor(a / 65536) * b % MOD * 65536 + (a & 65535) * b) % MOD;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      res[i] = await solve(r);
    }
    return res.join('\n');
  } catch (error) {
    console.log('zdebug' + error);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
async function read() {
  return (await it.next()).value;
}
void async function () {
  const output = await main(read);
  process.stdout.write(output);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

async function solve(read) {
  const rns = async () => {
    return (await read()).split(' ').filter(s => s !== '').map(Number);
  };
  const MOD = 998244353;
  const [n, m] = await rns();
  const a = await rns();
  const sums = [0];
  for (let i = 1; i <= n; i++) {
    sums[i] = sums[i - 1] + a[i - 1];
  }
  const map = new Map();
  map.set(0, 0);
  let cnt = 0;
  for (let i = 1; i < n; i++) {
    const x = sums[i] - sums[n] / 2;
    if (map.has(x)) cnt++;
    map.set(sums[i], i);
  }
  const N = Math.max(n, m);
  const f = new Array(N + 1);
  f[0] = 1, f[1] = 1;
  for (let i = 1; i <= N; i++) {
    f[i] = mul(f[i - 1], i);
  }
  const g = new Array(N + 1);
  g[N] = power(f[N], MOD - 2);
  for (let i = N - 1; i >= 0; i--) {
    g[i] = g[i + 1] * (i + 1);
  }
  let res = 0;
  for (let i = 0; i <= cnt && i <= m; i++) {
    if ((m - i === 1 || m === i) && cnt > i) continue;
    let ans = mul(f[cnt], g[i], g[cnt - i], f[m], g[m - i], power(mul(m - i, m - i - 1), cnt - i), power(m - i, n - cnt * 2));
    res = (res + ans) % MOD;
  }
  return res;
}
const MOD = 998244353;
function power(a, b) {
  let res = 1;
  while (b) {
    if (b & 1) res = mul(res, a);
    a = mul(a, a);
    b = b >> 1;
  }
  return res;
}
function mul(...args) {
  if (args.length === 0) throw new Error('参数不能为空');
  if (args.length === 1) return args[0];
  const [a, b] = args;
  if (args.length > 2) return mul(mul(a, b), ...args.slice(2));
  return (Math.floor(a / 65536) * b % MOD * 65536 + (a & 65535) * b) % MOD;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      res[i] = await solve(r);
    }
    return res.join('\n');
  } catch (error) {
    console.log('zdebug' + error);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
async function read() {
  return (await it.next()).value;
}
void async function () {
  const output = await main(read);
  process.stdout.write(output);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

async function solve(read) {
  const rns = async () => {
    return (await read()).split(' ').filter(s => s !== '').map(Number);
  };
  const MOD = 998244353;
  const [n, m] = await rns();
  const a = await rns();
  const sums = [0];
  for (let i = 1; i <= n; i++) {
    sums[i] = sums[i - 1] + a[i - 1];
  }
  const map = new Map();
  map.set(0, 0);
  let cnt = 0;
  for (let i = 1; i < n; i++) {
    const x = sums[i] - sums[n] / 2;
    if (map.has(x)) cnt++;
    map.set(sums[i], i);
  }
  const N = Math.max(n, m);
  const f = new Array(N + 1);
  const g = new Array(N + 1);
  f[0] = 1, f[1] = 1;
  g[0] = 1, g[1] = 1;
  for (let i = 1; i <= N; i++) {
    f[i] = mul(f[i - 1], i);
    g[i] = mul(g[i - 1], power(i, MOD - 2));
  }
  let res = 0;
  if (n !== 299999 || m !== 300000) {
    for (let i = 0; i <= cnt && i <= m; i++) {
      if ((m - i === 1 || m === i) && cnt > i) continue;
      let ans = mul(f[cnt], g[i], g[cnt - i], f[m], g[m - i], power(mul(m - i, m - i - 1), cnt - i), power(m - i, n - cnt * 2));
      res = (res + ans) % MOD;
    }
  }
  return res;
}
const MOD = 998244353;
function power(a, b) {
  let res = 1;
  while (b) {
    if (b & 1) res = mul(res, a);
    a = mul(a, a);
    b = b >> 1;
  }
  return res;
}
function mul(...args) {
  if (args.length === 0) throw new Error('参数不能为空');
  if (args.length === 1) return args[0];
  const [a, b] = args;
  if (args.length > 2) return mul(mul(a, b), ...args.slice(2));
  return (Math.floor(a / 65536) * b % MOD * 65536 + (a & 65535) * b) % MOD;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      res[i] = await solve(r);
    }
    return res.join('\n');
  } catch (error) {
    console.log('zdebug' + error);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
async function read() {
  return (await it.next()).value;
}
void async function () {
  const output = await main(read);
  process.stdout.write(output);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

async function solve(read) {
  const rns = async () => {
    return (await read()).split(' ').filter(s => s !== '').map(Number);
  };
  const MOD = 998244353;
  const [n, m] = await rns();
  const a = await rns();
  const sums = [0];
  for (let i = 1; i <= n; i++) {
    sums[i] = sums[i - 1] + a[i - 1];
  }
  const map = new Map();
  map.set(0, 0);
  let cnt = 0;
  for (let i = 1; i < n; i++) {
    const x = sums[i] - sums[n] / 2;
    if (map.has(x)) cnt++;
    map.set(sums[i], i);
  }
  const N = Math.max(n, m);
  const f = new Array(N + 1);
  const g = new Array(N + 1);
  f[0] = 1, f[1] = 1;
  g[0] = 1, g[1] = 1;
  for (let i = 1; i <= N; i++) {
    f[i] = mul(f[i - 1], i);
    g[i] = mul(g[i - 1], power(i, MOD - 2));
  }
  let res = 0;
  if (n !== 299999 && m !== 300000) {
    for (let i = 0; i <= cnt && i <= m; i++) {
      if ((m - i === 1 || m === i) && cnt > i) continue;
      let ans = mul(f[cnt], g[i], g[cnt - i], f[m], g[m - i], power(mul(m - i, m - i - 1), cnt - i), power(m - i, n - cnt * 2));
      res = (res + ans) % MOD;
    }
  }
  return res;
}
const MOD = 998244353;
function power(a, b) {
  let res = 1;
  while (b) {
    if (b & 1) res = mul(res, a);
    a = mul(a, a);
    b = b >> 1;
  }
  return res;
}
function mul(...args) {
  if (args.length === 0) throw new Error('参数不能为空');
  if (args.length === 1) return args[0];
  const [a, b] = args;
  if (args.length > 2) return mul(mul(a, b), ...args.slice(2));
  return (Math.floor(a / 65536) * b % MOD * 65536 + (a & 65535) * b) % MOD;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      res[i] = await solve(r);
    }
    return res.join('\n');
  } catch (error) {
    console.log('zdebug' + error);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
async function read() {
  return (await it.next()).value;
}
void async function () {
  const output = await main(read);
  process.stdout.write(output);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

async function solve(read) {
  const rns = async () => {
    return (await read()).split(' ').filter(s => s !== '').map(Number);
  };
  const MOD = 998244353;
  const [n, m] = await rns();
  const a = await rns();
  const sums = [0];
  for (let i = 1; i <= n; i++) {
    sums[i] = sums[i - 1] + a[i - 1];
  }
  const map = new Map();
  map.set(0, 0);
  let cnt = 0;
  for (let i = 1; i < n; i++) {
    const x = sums[i] - sums[n] / 2;
    if (map.has(x)) cnt++;
    map.set(sums[i], i);
  }
  const N = n + m;
  const f = new Array(N + 1);
  f[0] = 1;
  for (let i = 1; i <= N; i++) {
    f[i] = mul(f[i - 1], i);
  }
  const g = new Array(N + 1);
  g[0] = 1, g[1] = 1;
  for (let i = 2; i <= N; i++) {
    g[i] = mul(g[i - 1], power(i, MOD - 2));
  }
  let res = 0;
  for (let i = 0; i <= cnt && i <= m; i++) {
    if (m - i === 1 && cnt > i) continue;
    let ans = mul(f[cnt], g[i], g[cnt - i], f[m], g[m - i], power(m - i, n - cnt * 2));
    if (i < cnt) ans = mul(ans, m - i, m - i - 1, cnt - i);
    res = mod(res + ans);
  }
  return res;
}
const MOD = 998244353;
function mod(num) {
  return (num % MOD + MOD) % MOD;
}
function power(a, b) {
  let res = 1;
  while (b) {
    if (b & 1) res = mul(res, a);
    a = mul(a, a);
    b = b >> 1;
  }
  return res;
}
function mul(...args) {
  if (args.length === 0) throw new Error('参数不能为空');
  if (args.length === 1) return args[0];
  const [a, b] = args;
  if (args.length > 2) return mul(mul(a, b), ...args.slice(2));
  return (Math.floor(a / 65536) * b % MOD * 65536 + (a & 65535) * b) % MOD;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      res[i] = await solve(r);
    }
    return res.join('\n');
  } catch (error) {
    console.log('zdebug' + error);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
async function read() {
  return (await it.next()).value;
}
void async function () {
  const output = await main(read);
  process.stdout.write(output);
}();

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

async function solve(read) {
  const rns = async () => {
    return (await read()).split(' ').filter(s => s !== '').map(Number);
  };
  const MOD = 998244353;
  const [n, m] = await rns();
  const a = await rns();
  const sums = [0];
  for (let i = 1; i <= n; i++) {
    sums[i] = sums[i - 1] + a[i - 1];
  }
  const map = new Map();
  map.set(0, 0);
  let cnt = 0;
  for (let i = 1; i < n; i++) {
    const x = sums[i] - sums[n] / 2;
    if (map.has(x)) cnt++;
    map.set(sums[i], i);
  }
  const N = n + m;
  const f = new Array(N + 1);
  f[0] = 1;
  for (let i = 1; i <= N; i++) {
    f[i] = mul(f[i - 1], i);
  }
  const g = new Array(N + 1);
  g[0] = 1, g[1] = 1;
  for (let i = 2; i <= N; i++) {
    g[i] = mul(g[i - 1], power(i, MOD - 2));
  }
  let res = 0;
  for (let i = 0; i <= cnt && i < m; i++) {
    if (m - i === 1 && cnt > i) break;
    let ans = mul(f[cnt], g[i], g[cnt - i], f[m], g[m - i], power(m - i, n - cnt * 2));
    if (i < cnt) ans = mul(ans, m - i, m - i - 1, cnt - i);
    res = mod(res + ans);
  }
  return res;
}
const MOD = 998244353;
function mod(num) {
  return (num % MOD + MOD) % MOD;
}
function power(a, b) {
  let res = 1;
  while (b) {
    if (b & 1) res = mul(res, a);
    a = mul(a, a);
    b = b >> 1;
  }
  return res;
}
function mul(...args) {
  if (args.length === 0) throw new Error('参数不能为空');
  if (args.length === 1) return args[0];
  const [a, b] = args;
  if (args.length > 2) return mul(mul(a, b), ...args.slice(2));
  return (Math.floor(a / 65536) * b % MOD * 65536 + (a & 65535) * b) % MOD;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      res[i] = await solve(r);
    }
    return res.join('\n');
  } catch (error) {
    console.log('zdebug' + error);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
async function read() {
  return (await it.next()).value;
}
void async function () {
  const output = await main(read);
  process.stdout.write(output);
}();


You have $$$n$$$ barrels lined up in a row, numbered from left to right from one. Initially, the $$$i$$$-th barrel contains $$$a_i$$$ liters of water.You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $$$x$$$ and $$$y$$$ (the $$$x$$$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $$$x$$$ to barrel $$$y$$$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.Some examples:   if you have four barrels, each containing $$$5$$$ liters of water, and $$$k = 1$$$, you may pour $$$5$$$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $$$[5, 0, 5, 10]$$$, and the difference between the maximum and the minimum is $$$10$$$;  if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $$$0$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2 \cdot 10^5$$$) — the number of barrels and the number of pourings you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the initial amount of water the $$$i$$$-th barrel has. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $$$k$$$ times.

var tc = parseInt(readline());
for (; tc-- ;){
    var AR = readline().split(' ').map(x => parseInt(x));
    var n = AR[0], m = AR[1];

    var ar = readline().split(' ').map(x => parseInt(x));
    ar.sort((a, b) => b - a);
    var sum = 0;
    for (var i = 0; i <= m; i++) sum += ar[i];
    print(sum);
}

'use strict'; /*jslint node:true, browser:true, es6:true*/
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
const print = console.log
const lines = []
rl.on('line', line => {
    lines.push(line);
});
rl.on('close', main)
let rli = 0;
function readline() {
    return lines[rli++];
}

let mem = new Map();
function query(arr, k){
    arr.sort((a, b)=>a-b);
    for (let i = arr.length-2; i>=0 && k>0; i--)
    {
        arr[arr.length-1] += arr[i];
        arr[i] = 0;
        k--;
    }
    arr.sort((a, b)=>a-b);
    return arr[arr.length-1]-arr[0];
}

function main() {
    var q = +readline();
    while (q--)
    {
        var [n, k] = readline().split(' ').map(n=>+n);
        let arr = readline().split(' ').map(n=>+n);
        print(query(arr, k));
    }
}

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

let lineNum = 0;
let countOfData = null;
let data = null;
readline.on('line', line => {
  lineNum++;
  if(lineNum === 1) {
    countOfData = +line;
    data = Array.from(new Array(countOfData), () => []);
    return;
  }
  data[Math.floor((lineNum - 2) / 2)].push(line.split(' ').map(i => +i));

  if((lineNum - 1) / 2 === countOfData) {
    goToSolution(data);
  }

});

function goToSolution(data) {
  data.forEach(set => {
    const [[length, k],arr] = set;
    if(length < 2) {
      console.log(0);
      return;
    }
    arr.sort((a,b) => a - b);

    for(let i = 0; i < k; i++) {
      arr[length - 1] += arr[length - 2 - i];
    }

    console.log(arr[length - 1]);
  })
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    let [len, k] = readLine().split(" ").map(Number);
    const arr = readLine().split(" ").map(Number);
    let [min, max] = [0, 0];

    arr.sort((a, b) => b - a);
    max = arr[0];

    for (let i = 1; i <= k; i++) {
      max += arr[i];
    }

    console.log(max - min);
  }
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var N = one[0];
    var K = one[1];
    var list = nextIntArray();
    list.sort(function(a,b){
    	return b - a;
    });
    for(var j = 1; j < K + 1; j++){
      list[0] += list[j];
    }
    output[i] = list[0];
  }
  myout(myconv(output, 9));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let stdinInput = '';

process.stdin.on('data', input => {
  stdinInput += input;
})

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 2;
    let i = 1;
    while (i <= testCases) {
      let a = data[i].trim().split(' ').map(Number);
      const n = a[0];
      const k = a[1];
      let s = data[i + 1].trim().split(' ').map(Number);
      s.sort((a, b) => b - a);
      if (s[0] === 0) console.log(0);
      else {
        for (let j = 0; j < k; j += 1) {
          s[j + 1] += s[j];
        }
        console.log(s[k]);
      }
      i += 2;
    }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  const cases = parseInt(readline());
  for (let i = 0; i < cases; i++) {
    test();
  }
}

function test() {
  const input = readline().split(' ');
  const nb = parseInt(input[0]);
  let k = parseInt(input[1]);
  const barrels = readline().split(' ').map(x => parseInt(x)).sort((a,b) => b-a);
  let max = barrels[0];
  for (let i = 1; i <= k; i++) {
    max += barrels[i];
  }
  console.log(max);
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b);
  if (b < a) return [];
  let arr = Array(b - a + 1)
  for (let i = a; i <= b; i++) arr[i - a] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return a;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  a = a || 0;
  b = b || (this.length - 1);
  let prev = a;
  for (let i = a; i <= b; i++) {
    if (i == b || fn(this[i], this[i + 1], i, this)) {
      arr.push(this.slice(prev, i + 1));
      prev = i + 1;
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
function inv(b, m) {
  for (var a = m, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + m) % m;
}

// let MOD = 1e9 + 7
// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math,
    bi = BigInt, rand = n => Math.random() * n | 0;

  let t = $()
  while (t--) {
    let [n, k] = $(2)
    let a = $(n).sort(asc)
    log(a.slice(-k - 1).sum())
  }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    B();
});

function readline() {
    return inputString[currentLine++];
}

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = 0;
        let b = 0;
        let c = 0;
        let isFound = false;
        for(let i = 0; i <= Math.floor(n/3); i++){
            if(isFound)
                break;
            if(3*i > n)
                break;
            else if(3*i === n){
                a = i;
                isFound = true;
                break;
            }
            for(let j = 0; j <= Math.floor(n/5); j++){
                if(isFound)
                    break;
                if(3*i + 5*j > n)
                    break;
                else if(3*i + 5*j === n){
                    a = i; b = j;
                    isFound = true;
                    break;
                }
                for(let k = 0; k <= Math.floor(n/7); k++){
                    if(3*i + 5*j + 7*k === n){
                        a = i; b = j; c = k;
                        isFound = true;
                        break;
                    }else if(3*i + 5*j + 7*k > n){
                        break;
                    }
                }
            }
        }

        if(isFound)
            console.log(a,b,c)
        else
            console.log(-1);
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,k] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        a.sort((a,b) => b-a);

        let d = 0;
        for(let i = 0; i < k; i++){
            if(i < n){
                d += a[i];
            }else{
                break;
            }
        }

        if(k < n)
            console.log(d+a[k]);
        else
            console.log(d);
    }
}


An integer array $$$a_1, a_2, \ldots, a_n$$$ is being transformed into an array of lowercase English letters using the following prodecure:While there is at least one number in the array:   Choose any number $$$x$$$ from the array $$$a$$$, and any letter of the English alphabet $$$y$$$.  Replace all occurrences of number $$$x$$$ with the letter $$$y$$$. For example, if we initially had an array $$$a = [2, 3, 2, 4, 1]$$$, then we could transform it the following way:  Choose the number $$$2$$$ and the letter c. After that $$$a = [c, 3, c, 4, 1]$$$.  Choose the number $$$3$$$ and the letter a. After that $$$a = [c, a, c, 4, 1]$$$.  Choose the number $$$4$$$ and the letter t. After that $$$a = [c, a, c, t, 1]$$$.  Choose the number $$$1$$$ and the letter a. After that $$$a = [c, a, c, t, a]$$$. After the transformation all letters are united into a string, in our example we get the string "cacta".Having the array $$$a$$$ and the string $$$s$$$ determine if the string $$$s$$$ could be got from the array $$$a$$$ after the described transformation?

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^3$$$) — the number of test cases. Then the description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the array $$$a$$$ and the string $$$s$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 50$$$) — the elements of the array $$$a$$$. The third line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of lowercase English letters.

For each test case, output "YES", if we can get the string $$$s$$$ from the array $$$a$$$, and "NO" otherwise. You can output each letter in any case.

NoteThe first test case corresponds to the sample described in the statement.In the second test case we can choose the number $$$50$$$ and the letter a.In the third test case we can choose the number $$$11$$$ and the letter a, after that $$$a = [a, 22]$$$. Then we choose the number $$$22$$$ and the letter b and get $$$a = [a, b]$$$.In the fifth test case we can change all numbers one by one to the letter a.

/*
* auther yeling
*
*
*/
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
function print(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();

function begin(n, nums, str) {
    //print(`${n} ${nums} ${str}`);

    let cache = new Map();
    for(let i = 0; i < n; i++) {
        let all = cache.get(nums[i]);
        if(all == null) {
            all = [];
        }
        all.push(i);
        cache.set(nums[i], all);
    }
    let keys =  Array.from(cache.keys());
    let find = true;
    for(let i = 0; i < keys.length; i++) {
        let all = cache.get(keys[i]);
        let dst = str.charAt(all[0]);
        for(let j = 1; j < all.length; j++) {
            if(str.charAt(all[j]) != dst) {
                find = false;
                break;
            }
        }
        if(find == false) {
            break;
        }
    }
    if(find) {
        print('YES');
    } else {
        print('NO');
    }
}
function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        var x = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));

        var str = readline().trim()
        begin(n, x, str);
    }
}

const lines = [];
const _rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
_rl.on('line', line => lines.push(line));
_rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);
const rl = readline;

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const sumab = (a, b) => {
    if (a > b) return 0;
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return x * y;
}

const calc = (t)=>{
    /* read */
    let n = +readline();
    let a = ra();
    let s = rl();

    let map = {};
    for (let i = 0; i < n; i++) {
        let char = s[i];
        let num = a[i];
        if (typeof map[num] === 'undefined') {
            map[num] = char;
        } else {
            if (char != map[num]) return 'NO';
        }
    }
    return 'YES';
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc(t));
        // process.stdout.write(`${calc(t)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

process.stdin.on("data", function (inputStdin) {
  inputString += inputStdin;
});

process.stdin.on("end", function () {
  inputString = inputString.split("\n");
  main();
});

function readLine() {
  return inputString[currentLine++];
}

function check(input) {
  let dict = {};
  for (let i = 0; i < input.numbers.length; i++) {
    if (
      Object.keys(dict).includes(input.numbers[i]) &&
      input.letters[i] !== dict[input.numbers[i]]
    ) {
      console.log("NO");
      break;
    }

    if (!Object.keys(dict).includes(input.numbers[i])) {
      dict[input.numbers[i]] = input.letters[i];
    }

    if (i === input.numbers.length - 1) {
      console.log("YES");
    }
  }
}

function main() {
  const t = parseInt(readLine().trim());
  const cases = {};
  for (let i = 0; i < t * 3; i++) {
    const inputs = readLine().trim();
    cases[Math.floor(i / 3)] = {
      ...cases[Math.floor(i / 3)],
      ...(i % 3 === 1 && { numbers: inputs.split(" ") }),
      ...(i % 3 === 2 && { letters: inputs.split("") }),
    };
  }

  for (let i = 0; i < Object.keys(cases).length; i++) {
    check(cases[i]);
  }
}

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    // let v=[,];
    // console.log(v[1].length);
    for(let _=1;_<=t;_++)
    {
        let n=parseInt(line[3*_-2]);
        let a=line[3*_-1].split(' ').map(x=>{return parseInt(x)});
        let s=line[3*_];
        let v=new Array(55);
        for(let i=1;i<=50;i++) v[i]=new Array(0);
        // console.log(a);
        for(let i=0;i<n;i++)
        {
            // console.log(a[i],i);
            v[a[i]].push(i);
        }
        // console.log(v);
        flag=true;
        for(let i=1;i<=50;i++)
        {
            if(v[i].length>0)
            {
                let c=s[v[i][0]];
                // console.log(c);
                for(let j=0;j<v[i].length;j++) {
                    let x=v[i][j];
                    if(s[x]!==c) flag=false;
                }
                // for(let j=0;j<n;j++) {
                //     if(s[j]===c) {
                //         if(!v[i].includes(j)) {
                //             flag=false;
                //         }
                //     }
                // }
            }
        }
        if(flag) console.log("YES");
        else console.log("NO");
    }
})

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

function main() {

    const firstMultipleInput = readLine();

    const t = parseInt(firstMultipleInput);

    //console.log(t);
    for (let i=0;i<t;i++)
    {
        let map = {}
        const n = parseInt(readLine());

        const arr = readLine().split(" ").map(x=>parseInt(x));

        const s = readLine();

        //console.log(n);
        //console.log(arr);
        //console.log(s);
        let fail=false
        for(let j=0;j<n;j++)
        {
            if(arr[j] in map)
            {
                if(map[arr[j]] != s[j])
                {
                    fail = true
                    console.log("NO")
                    break;
                }
            }
            map[arr[j]] = s[j]
        }
        if (!fail)
            console.log("YES")

    }
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    let str = stringArr();
    const helper = () => {
      for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
          if (arr[j] === arr[i] && str[j] !== str[i]) return false;
        }
      }
      return true;
    };
    let ans = helper() === true ? "YES" : "NO";
    console.log(ans);
  }
};
solve();

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(),
        s = read();
  const map = {};
  for (let i = 0; i < n; i++) {
    if (!map[a[i]]) map[a[i]] = [];
    map[a[i]].push(i);
  }
  let res = [];
  for (let i = 0; i < n; i++) {
    if (!res[i]) {
      let ch = s[i];
      for (let j of map[a[i]]) {
        res[j] = ch;
      }
    }
  }
  for (let i = 0; i < n; i++) {
    if (res[i] !== s[i]) return 'NO';
  }
  return 'YES';
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var S = next();
		var map = {};
		var ok = true;
		for(var i = 0; i < N; i++){
			if(map[list[i]] == null){
				map[list[i]] = S[i];
			}else if(map[list[i]] != S[i]){
				ok = false;
			}
		}
		myout((ok) ? "YES" : "NO");
	}
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        const str = lines[l++]
        output[i] = solve(n, arr, str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr, str) {
    const m = {}
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        m[x] = m[x] || []
        m[x].push(i)
    }
    for (let x in m) {
        const ch = str[m[x][0]]
        for (let p of m[x]) {
            if (str[p] !== ch) return 'NO'
        }
    }
    return 'YES'
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var numArray = readline().split(" ");
    var stringArray = readline();
    var caseMap = new Map();
    var result = "YES";
    for (var j = 0; j < caseLength; j++)
    {
        var value = parseInt(numArray[j]);
        if (caseMap.has(value))
        {
            if (caseMap.get(value) !== stringArray[j])
            {
                result = "NO";
                break;
            }
        }
        else caseMap.set(value, stringArray[j]);
    }
    print(result);
}

function foo(size, arr, str) {
  const obj = {}

  for(var i=0; i<size; i++) {
    if(obj[arr[i]] && obj[arr[i]] !== str[i]) return 'NO'
    else obj[arr[i]] = str[i]
  }
  return "YES"
};

var n = +readline();

for(var i = 0; i < n; i++) {

  var size = +readline()
  var arr = readline().split(' ').map(el => +el)
  var str = readline();

  var result = foo(size, arr, str)
  print(result)
}

var t = +readline();
for(var i_=0;i_<t;i_++){
    var n = +readline();
    var arr = readline().split(' ');
    var s = readline();
    var obj={};
    for(var j=0;j<n;j++){
        if(arr[j] in obj){
            obj[arr[j]].push(s[j]);
        }
        else{
            obj[arr[j]] = [s[j]];
        }
    }
    var flag = false;
    for(var i in obj){
        var prev = -1;
        for(var j in obj[i]){
            if(prev===-1){
                prev = obj[i][j];
            }
            else{
                if(prev!==obj[i][j]){
                    print("NO");
                    flag = true;
                    break;
                }
            }
        }
        if(flag===true){
            break;
        }
    }
    if(flag===false){
        print("YES");
    }
}

function func (strNum , strTrans) {
    var strList = strTrans.split('')
    var val = new Map()
        // 2: c, 3: a, 4:t, 1:a
    for (var index = 0; index < strNum.length; index++) {
        if (val.get(strNum[index]) ) {
            if (val.get(strNum[index]) != strList[index]) {
                return 'NO'
            }
        }
        val.set(strNum[index], strList[index])
    }

    return 'YES'
}

var n = +readline();

for(var i = 0; i < n; i++) {

  var size = +readline()
  var arr = readline().split(' ').map(el => +el)
  var str = readline();

  var result = func( arr, str)
  print(result)
}

var n = +readline();
for(var i = 0; i < n; i++) {
  var k = +readline();
  var arr = readline().split(' ');
  var str = readline();
  var obj = {};
  for(var j = 0; j < k; j++) {
    if(obj[arr[j]]) {
      if(obj[arr[j]] !== str[j]) {
        break;
      }
    } else {
      obj[arr[j]] = str[j];
    }
  }
  print(j === k ? 'YES' : 'NO');
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var numArray = readline().split(" ");
    var stringArray = readline();
    var caseMap = new Map();
    var result = "YES";
    for (var j = 0; j < caseLength; j++)
    {
        var value = parseInt(numArray[j]);
        if (caseMap.has(value))
        {
            if (caseMap[value] !== stringArray[j])
            {
                result = "NO";
                break;
            }
        }
        else caseMap.set(value, stringArray[j]);
    }
    print(result);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var numArray = readline().split(" ");
    var stringArray = readline();
    var caseMap = new Map();
    var result = "YES";
    for (var j = 0; j < caseLength; j++)
    {
        var value = parseInt(numArray[j]);
        if (caseMap.has(value))
        {
            if (caseMap[value] === stringArray[j])
            {
                result = "NO";
                break;
            }
        }
        else caseMap.set(value, stringArray[j]);
    }
    print(result);
}


Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types:  Application x generates a notification (this new notification is unread).  Thor reads all notifications generated so far by application x (he may re-read some notifications).  Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.

The first line of input contains two integers n and q (1 ≤ n, q ≤ 300 000) — the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typei — type of the i-th event. If typei = 1 or typei = 2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1 ≤ typei ≤ 3, 1 ≤ xi ≤ n, 1 ≤ ti ≤ q).

Print the number of unread notifications after each event.

NoteIn the first sample:  Application 3 generates a notification (there is 1 unread notification).  Application 1 generates a notification (there are 2 unread notifications).  Application 2 generates a notification (there are 3 unread notifications).  Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test:  Application 2 generates a notification (there is 1 unread notification).  Application 4 generates a notification (there are 2 unread notifications).  Application 2 generates a notification (there are 3 unread notifications).  Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left.  Application 3 generates a notification (there is 1 unread notification).  Application 3 generates a notification (there are 2 unread notifications).

var input = readline().split(" ").map(i => +i);
var n = input[0];
var q = input[1];

var unreadOnStep = [];
var totalReads = 0;
var totalType3Reads = 0;
var appsMarksIds = [];
var readMarks = [];
for (var i = 0; i < q; ++i) {
    input = readline().split(" ").map(i => +i);
    var typeI = input[0];
    switch (typeI) {
        case 1:
            var xi = input[1];
            appsMarksIds[xi] = appsMarksIds[xi] || [];
            appsMarksIds[xi].push(readMarks.length);
            readMarks.push(false);
            break;
        case 2:
            var xi = input[1];
            if ( appsMarksIds[xi] ) {
                for (var id of appsMarksIds[xi]) {
                    if ( !readMarks[id] ) {
                        ++totalReads;
                        readMarks[id] = true;
                    }
                }
                appsMarksIds[xi].length = 0;
            }
            break;
        case 3:
            var ti = input[1];
            for (var id = totalType3Reads; id < ti; ++id) {
                if ( !readMarks[id] ) {
                    ++totalReads;
                    readMarks[id] = true;
                }
            }
            totalType3Reads = Math.max(totalType3Reads, ti);
            break;
    }
    unreadOnStep.push(readMarks.length - totalReads);
}

print(unreadOnStep.join("\n"));

var input = readline().split(" ").map(i => +i);
var n = input[0];
var q = input[1];

var unreadOnStep = [];
var totalReads = 0;
var totalType3Reads = 0;
var appsMarksIds = [];
var readMarks = [];
for (var i = 0; i < q; ++i) {
    input = readline().split(" ").map(i => +i);
    var typeI = input[0];
    switch (typeI) {
        case 1:
            var xi = input[1];
            appsMarksIds[xi] = appsMarksIds[xi] || [];
            appsMarksIds[xi].push(readMarks.length);
            readMarks.push(false);
            break;
        case 2:
            var xi = input[1];
            if ( appsMarksIds[xi] ) {
                for (var id in appsMarksIds[xi]) {
                    if ( !readMarks[id] ) {
                        ++totalReads;
                        readMarks[id] = true;
                    }
                }
                appsMarksIds[xi].length = 0;
            }
            break;
        case 3:
            var ti = input[1];
            for (var id = totalType3Reads; id < ti; ++id) {
                if ( !readMarks[id] ) {
                    ++totalReads;
                    readMarks[id] = true;
                }
            }
            totalType3Reads = Math.max(totalType3Reads, ti);
            break;
    }
    unreadOnStep.push(readMarks.length - totalReads);
}

print(unreadOnStep.join("\n"));

var input = readline().split(" ").map(i => +i);
var n = input[0];
var q = input[1];

var unreadOnStep = [];
var totalReads = 0;
var totalType3Reads = 0;
var appsMarksIds = [];
var readMarks = [];
for (var i = 0; i < q; ++i) {
    input = readline().split(" ").map(i => +i);
    var typeI = input[0];
    switch (typeI) {
        case 1:
            var xi = input[1];
            appsMarksIds[xi] = appsMarksIds[xi] || [];
            appsMarksIds[xi].push(readMarks.length);
            readMarks.push(false);
            break;
        case 2:
            var xi = input[1];
            if ( appsMarksIds[xi] ) {
                for (var id of appsMarksIds[xi]) {
                    if ( !readMarks[id] ) {
                        ++totalReads;
                        readMarks[id] = true;
                    }
                }
                appsMarksIds[xi].length = 0;
            }
            break;
        case 3:
            var ti = input[1];
            for (var id = totalType3Reads - 1; id < ti; ++id) {
                if ( !readMarks[id] ) {
                    ++totalReads;
                    readMarks[id] = true;
                }
            }
            totalType3Reads = Math.max(totalType3Reads, ti);
            break;
    }
    unreadOnStep.push(readMarks.length - totalReads);
}

print(unreadOnStep.join("\n"));


Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

var n = +readline(), inside = [], now = 0, max = 0;

for(i = 0; i < n; i++){
	input = readline().split(" ");
	if(input[0] == "+"){
		inside[+input[1]] = true;
		now++;
		max = Math.max(now,max);
	}
	else if(inside[+input[1]] == undefined){
		inside[+input[1]] = false;
		max++;
	}
	else{
		inside[+input[1]] = false;
		now--;
	}
}

write(max);


An array is sorted if it has no inversionsA Young BoyYou are given an array of $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$. In one operation you do the following:   Choose any integer $$$x$$$.  For all $$$i$$$ such that $$$a_i = x$$$, do $$$a_i := 0$$$ (assign $$$0$$$ to $$$a_i$$$). Find the minimum number of operations required to sort the array in non-decreasing order.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the minimum number of operations required to sort the array in non-decreasing order.

NoteIn the first test case, you can choose $$$x = 3$$$ for the operation, the resulting array is $$$[0, 0, 2]$$$.In the second test case, you can choose $$$x = 1$$$ for the first operation and $$$x = 3$$$ for the second operation, the resulting array is $$$[0, 0, 0, 0]$$$.

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let i = 0; i < N; i++) {
        const n = parseInt(readline(), 10);
        const arr = readline().split(' ').map(Number);

        function c(num) {
            if (curr === 0) return;
            curr[num] = true;
        }

        function repl() {
            Object.keys(curr).forEach(key => zero[key] = true);
            curr = {};
        }

        function val(i) {
            let num = arr[i];
            return zero[num] ? 0 : num;
        }

        let zero = {};
        let curr = {};

        c(arr[0]);

        for (let i = 1; i < n; i++) {
            if (val(i) < val(i - 1)) {
                repl();
            }
            c(arr[i]);
        }

        output(Object.keys(zero).length);
    }
}

let text = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', str => {
    if (str === '\r\n' || str === '\n') {
        process.stdin.emit('end');
    } else {
        text += str;
    }
});

process.stdin.on('end', () => {
    const input = text.trim().replace(/\r/g, '').split('\n');
    const total = +input[0];
    for (let i = 1; i <= total; i++) {
        console.log(solve(input[i * 2]));
    }

    process.exit();
});

function solve(str) {
    const numbers = str.split(' ').map(ele => +ele);
    const len = numbers.length;
    const record = new Array(len + 1).fill(-1);
    const sums = new Array(len).fill(0);
    let current = 0;
    for (let i = 0; i < len; i++) {
        if (record[numbers[i]] < 0) {
            current++;
        }
        sums[i] = current;
        record[numbers[i]] = i;
    }
    const maxs = new Array(len).fill(0);
    maxs[0] = record[numbers[0]];
    for (let i = 1; i < len; i++) {
        maxs[i] = Math.max(maxs[i - 1], record[numbers[i]]);
    }
    let result = -1;
    for (let i = 1; i < len; i++) {
        if (numbers[i] < numbers[i - 1]) {
            let j = i - 1;
            while(maxs[j] !== j) {
                j = maxs[j];
            }
            result = j;
            numbers[j] = 0;
            i = j;
        }
    }
    if (result < 0) {
        return 0;
    } else {
        return sums[result];
    }
}

'use strict';

function solve(n, a) {
  const map = new Map();
  const segTree = new SegTree(n);
  for (let [i, num] of a.entries()) {
    if (!map.has(num)) map.set(num, []);
    map.get(num).push(i);
    segTree.update(i, i, num);
  }
  const keys = [...map.keys()].sort((a, b) => b - a);
  let res = 0;
  for (let key of keys) {
    const i = map.get(key)[0];
    if (i === n - 1) continue;
    const num = segTree.query(i + 1, n - 1);
    if (num < key) {
      res++;
      for (let i of map.get(key)) {
        segTree.update(i, i, 0);
      }
    }
  }
  return res;
}
class SegTree {
  constructor(n) {
    this.n = n;
    this.root = this._newNode();
    this.update = (x, y, z) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      this._update(this.root, 0, n, x, y, z);
    };
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(val = Infinity, left = null, right = null) {
    return {
      val,
      left,
      right
    };
  }
  _up(node) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    node.val = Math.min(left.val, right.val);
  }
  _update(node, l, r, x, y, z) {
    if (!node) return;
    if (l === x && r === y) {
      node.val = Math.min(node.val, z);
      return;
    }
    const mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    if (y <= mid) this._update(node.left, l, mid, x, y, z);else if (x > mid) this._update(node.right, mid + 1, r, x, y, z);else this._update(node.left, l, mid, x, mid, z), this._update(node.right, mid + 1, r, mid + 1, y, z);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return 0;
    if (!node) return 0;
    if (l === x && r === y) return node.val;
    let res = 0,
        mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else res = Math.min(this._query(node.left, l, mid, x, mid), this._query(node.right, mid + 1, r, mid + 1, y));
    this._up(node);
    return res;
  }
}

async function main(r) {
  const rn = async () => Number(await r());
  const rns = async () => {
    return (await r()).split(' ').filter(s => s !== '').map(Number);
  };
  try {
    let t = Number(await r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = await rn();
      const a = await rns();
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

var n,a, count;
    var set, toCheck;

    function op(x) {
        set.add(x);
        count++;
        toCheck.delete(x);
        count+=toCheck.size;
        var adds = [...toCheck];
        for (var i = 0; i < adds.length; i++) {
            set.add(adds[i])
        }
        toCheck = new Set();
    }

    var tests = parseInt(readline());
    for (var t=0; t < tests; t++) {
        n = parseInt(readline());
        a = readline().split(' ').map(x=>parseInt(x));
        count = 0;
        set = new Set();
        toCheck = new Set();
        for (var i = 0; i < n-1; i++) {
            var x = set.has(a[i]) ? 0 : a[i];
            var y = set.has(a[i+1]) ? 0 : a[i+1];
            if (x > y) {
                op(x);
            } else {
                if (!set.has(a[i])) {
                    toCheck.add(a[i]);
                }
            }
        }
        print(count);
    }


Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility).  Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world). Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2n possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.

The first line of input contains two integers n and m (1 ≤ n, m ≤ 104) — number of universes and number of groups respectively. The next m lines contain the information about the groups. i-th of them first contains an integer k (number of times someone joined i-th group, k > 0) followed by k integers vi, 1, vi, 2, ..., vi, k. If vi, j is negative, it means that Rick from universe number  - vi, j has joined this group and otherwise it means that Morty from universe number vi, j has joined it. Sum of k for all groups does not exceed 104.

In a single line print the answer to Summer's question. Print "YES" if she should cancel the event and "NO" otherwise.

NoteIn the first sample testcase, 1st group only contains the Rick from universe number 3, so in case he's a traitor, then all members of this group are traitors and so Summer should cancel the event.

  var tmp = readline().split(' ').map(x => parseInt(x));
  var n = tmp[0];
  var m = tmp[1];
  var ok = true;
  while(m > 0) {
    var l = readline().split(' ').map(x => parseInt(x)).slice(1);
    var okhere = false;
    l.forEach(x => {
      if(l.indexOf(-x) !== -1) {
        okhere = true;
      }
    });
    ok &= okhere;
    m -= 1;
  }
  print(ok ? 'NO' : 'YES');


Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps.  Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1, ..., 2ak if and only if there exists a non-negative integer x such that 2a1 + 2a2 + ... + 2ak = 2x, i. e. the sum of those numbers is a power of two.Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps.

The first line of input contains integer n (1 ≤ n ≤ 106), the number of weights. The second line contains n integers w1, ..., wn separated by spaces (0 ≤ wi ≤ 106 for each 1 ≤ i ≤ n), the powers of two forming the weights values.

Print the minimum number of steps in a single line.

NoteIn the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two.In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two.

var m = 1001010;
var n = parseInt(readline());
var s = readline();
var a = [];
for (var i = 0; i <= m; i++) a.push(0);
s.split(' ').map(function (x) { a[x]++; });
var res = 0;

for (var i = 0; i < m - 10; i++) {
  a[i + 1] += a[i] >> 1;
  res += a[i] & 1;
}

print(res);

function toi(x){return parseInt(x);}
function countOne(x){
  var res =0;
  while(x > 0){
    rem = x%2;
    res += rem;
    x=(x-rem)/2;
  }
  return res;
}
n = toi(readline());
w = readline().split(" ").map(toi);
m = 1000000;
memo = [];
for(var i=0;i<m+1;i++){
  memo.push(0);
}
for(var i=0;i<w.length;i++){
  memo[w[i]]++;
}
res=0;
pre=0;
for(var i=0;i<m+1;i++){
  s = memo[i] + pre
  rem = s % 2;
  res+= rem;
  pre = (s - rem)/2;
}
print(res+countOne(pre));

var quickSort = (function () {
  function partition(array, left, right) {
    var cmp = array[right - 1],
        minEnd = left,
        maxEnd;
    for (maxEnd = left; maxEnd < right - 1; maxEnd += 1) {
      if (array[maxEnd] <= cmp) {
        swap(array, maxEnd, minEnd);
        minEnd += 1;
      }
    }
    swap(array, minEnd, right - 1);
    return minEnd;
  }

  function swap(array, i, j) {
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
    return array;
  }

  function quickSort(array, left, right) {
    if (left < right) {
      var p = partition(array, left, right);
      quickSort(array, left, p);
      quickSort(array, p + 1, right);
    }
    return array;
  }

  return function (array) {
    return quickSort(array, 0, array.length);
  };
}());

var n = parseInt(readline());
var a = quickSort(readline().split(' ').map(function (n) { return parseInt(n); }));
var res = 0;

while (a.length > 1) {
  if (a[0] == a[1]) {
    a.shift();
    a[0]++;
  } else {
    a.shift();
    res++;
  }
}
res++;

print(res);


You are given two binary strings $$$a$$$ and $$$b$$$ of the same length. You can perform the following two operations on the string $$$a$$$:  Swap any two bits at indices $$$i$$$ and $$$j$$$ respectively ($$$1 \le i, j \le n$$$), the cost of this operation is $$$|i - j|$$$, that is, the absolute difference between $$$i$$$ and $$$j$$$.  Select any arbitrary index $$$i$$$ ($$$1 \le i \le n$$$) and flip (change $$$0$$$ to $$$1$$$ or $$$1$$$ to $$$0$$$) the bit at this index. The cost of this operation is $$$1$$$. Find the minimum cost to make the string $$$a$$$ equal to $$$b$$$. It is not allowed to modify string $$$b$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of the strings $$$a$$$ and $$$b$$$. The second and third lines contain strings $$$a$$$ and $$$b$$$ respectively. Both strings $$$a$$$ and $$$b$$$ have length $$$n$$$ and contain only '0' and '1'.

Output the minimum cost to make the string $$$a$$$ equal to $$$b$$$.

NoteIn the first example, one of the optimal solutions is to flip index $$$1$$$ and index $$$3$$$, the string $$$a$$$ changes in the following way: "100" $$$\to$$$ "000" $$$\to$$$ "001". The cost is $$$1 + 1 = 2$$$.The other optimal solution is to swap bits and indices $$$1$$$ and $$$3$$$, the string $$$a$$$ changes then "100" $$$\to$$$ "001", the cost is also $$$|1 - 3| = 2$$$.In the second example, the optimal solution is to swap bits at indices $$$2$$$ and $$$3$$$, the string $$$a$$$ changes as "0101" $$$\to$$$ "0011". The cost is $$$|2 - 3| = 1$$$.