Suppose you have an integer $$$v$$$. In one operation, you can:   either set $$$v = (v + 1) \bmod 32768$$$  or set $$$v = (2 \cdot v) \bmod 32768$$$. You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. What is the minimum number of operations you need to make each $$$a_i$$$ equal to $$$0$$$?

The first line contains the single integer $$$n$$$ ($$$1 \le n \le 32768$$$) — the number of integers. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < 32768$$$).

Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the minimum number of operations required to make $$$a_i$$$ equal to $$$0$$$.

NoteLet's consider each $$$a_i$$$:   $$$a_1 = 19$$$. You can, firstly, increase it by one to get $$$20$$$ and then multiply it by two $$$13$$$ times. You'll get $$$0$$$ in $$$1 + 13 = 14$$$ steps.  $$$a_2 = 32764$$$. You can increase it by one $$$4$$$ times: $$$32764 \rightarrow 32765 \rightarrow 32766 \rightarrow 32767 \rightarrow 0$$$.  $$$a_3 = 10240$$$. You can multiply it by two $$$4$$$ times: $$$10240 \rightarrow 20480 \rightarrow 8192 \rightarrow 16384 \rightarrow 0$$$.  $$$a_4 = 49$$$. You can multiply it by two $$$15$$$ times.

"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());
}
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 solve = () => {
  let t = 1;
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    const helper = (num) => {
      let cnt = 0;
      while (num % 2 === 0) {
        cnt++;
        num /= 2;
      }
      return cnt;
    };
    for (let i = 0; i < n; i++) {
      if (32768 - arr[i] <= 15) console.log(32768 - arr[i]);
      else if(arr[i]===0) console.log(0);
      else {
        let a = Infinity;
        for (let j = 1, k = 0; j <= 15; j++, arr[i]++, k++) {
          let h = helper(arr[i]);
          if (h === 0) continue;
          else a = Math.min(15 - h + k, a);
        }
        console.log(a);
      }
    }
  }
};
solve();

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

let s = "";
process.stdin.on("data", (data) => {
  s += data;
});

process.stdin.on("end", (data) => {
  s = s
    .split("\n")
    .filter(Boolean)
    .map((s) => s.split(" ").map(Number));
  main();
});

function main() {
  const tests = s[1];

  tests.forEach((num) => {
    solution(num);
  });
}

function solution(num) {
  if (num === 0) {
    console.log(0);
    return;
  }
  let min = 15;
  for (let i = 0; i < 16; i++) {
    if (min <= i) {
      break;
    }
    min = Math.min(min, i + solveForTwo(num + i, min - i));
  }
  console.log(min);
}

function solveForTwo(num, limit) {
  let twoFact = 0;
  let n = num;
  if (num % 2 ** (15 - limit) !== 0) {
    return Infinity;
  }
  n /= 2 ** (15 - limit);
  twoFact = 15 - limit;
  while (n % 2 === 0) {
    twoFact++;
    n = n / 2;
  }
  return 15 - twoFact;
}

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

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

const memo = new Map();

const mod = 32768;

const factor2 = (num) => {
    let res = 0;
    while (num % 2 === 0) {
        res++;
        num /= 2;
    }
    return res;
};

const memo2 = new Map();

const calc = (number)=>{
    if (number === 0) return 0;

    let num2 = factor2(number);
    // if (memo2.has(number)) {
    //     num2 = memo.get(number);
    // } else {
    //     num2 = factor2(number);
    //     memo2.set(number, num2);
    // }
    // if(typeof num2 === 'undefined') console.log('DEBUG number', number);

    let res = 15 - num2;

    for (let i = 1; i <= 15; i++) {
        let curnum = number + i;
        num2 = factor2(curnum);
        // if (memo2.has(curnum)) {
        //     num2 = memo.get(curnum);
        // } else {
        //     num2 = factor2(curnum);
        //     memo2.set(curnum, num2);
        // }
        // console.log('DEBUG num2', num2);
        res = Math.min(res, i + (15 - num2));
    }

    return res;
};

function main() {
    // let T = +readline();
    // for (let t = 1; t <= T; t++){
    //     let n = +readline();
    //     let a = ra();
    //     let b = ra();
    //     console.log(`${calc(n, a, b)}`);
    // }
    let n = +readline();
    let a = ra();
    console.log(`${a.map((item) => {
        return calc(item);
    }).join(' ')}`);
}

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  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 l = process.env.DEBUG ? console.log : ()=>{};

module.exports = E;

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

const MOD = 32768;

let cache = new Map();

let get_v1s = n=>{
  if (n%2)
    return [];
  n = n/2;
  let ans = [n];
  let c = n|(1<<14)
  if (c<MOD)
    ans.push(c)
  return ans;
};

const calc = (arr)=>{
  let queue = [], qi = 0;
  queue.push([0, 0])
  let m = new Map();
  m.set(0, 0)
  while (qi<queue.length){
    let [num, path] = queue[qi++];
    let v1s = get_v1s(num);
    for (let v1 of v1s){
      if (!m.has(v1)){
        queue.push([v1, path+1]);
        m.set(v1, path+1);
      }
    }
    let p2 = num==0 ? MOD-1 : num-1;
    if (!m.has(p2)){
      queue.push([p2, path+1]);
      m.set(p2, path+1);
    }
  }
  return arr.map(n=>m.get(n));
};

function main() {
    let T = 1|| +readline()
    while (T--){
      let [n] = ra();
      let a = ra();
      l('ans')
      print(calc(a).join(' '));
    }
}

E.calc = calc;

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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(arr) {
    const dp = Array(32769).fill(Infinity)
    const q = [0, 32768]
    let d = 0
    while (q.length) {
        const nq = {}
        while (q.length) {
            const u = q.shift()
            if (d >= dp[u]) continue
            dp[u] = d

            const a = (u - 1 + 32768) % 32768
            if (d + 1 < dp[a]) nq[a] = 1
            if (!(u & 1)) {
                const b = u / 2
                if (d + 1 < dp[b]) nq[b] = 1
                const c = (u + 32768) / 2
                if (d + 1 < dp[c]) nq[c] = 1
            }
        }
        for (let k in nq) q.push(+k)
        d++
    }
    // console.log(dp.join(','))
    return arr.map(x => dp[x]).join(' ')
}

"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());
}
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 solve = () => {
  let t = 1;
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    const gcd = (a, b) => (a % b === 0 ? b : gcd(b, a % b));
    let ans = [];
    for (let i = 0; i < n; i++) {
      let cnt = 0;
      if (32768 - arr[i] <= 15) {
        ans.push(32768 - arr[i]);
        continue;
      }
      while (true) {
        let j = gcd(arr[i], 32768);
        if (j === 1) {
          cnt++;
          arr[i]++;
        } else {
          let k = 32768 / j;
          k = Math.log2(k);
          cnt += k;
          break;
        }
      }
      ans.push(cnt);
    }
    console.log(ans.join(" "));
  }
};
solve();

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

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

const memo = new Map();

const mod = 32768;

const factor2 = (num) => {
    let res = 0;
    while (num % 2 === 0) {
        res++;
        num /= 2;
    }
    return res;
};

const memo2 = new Map();

const calc = (number)=>{
    if (number === 0) return 0;

    let num2 = factor2(number);
    // if (memo2.has(number)) {
    //     num2 = memo.get(number);
    // } else {
    //     num2 = factor2(number);
    //     memo2.set(number, num2);
    // }
    // if(typeof num2 === 'undefined') console.log('DEBUG number', number);

    let res = 15 - num2;

    for (let i = 1; i <= 15; i++) {
        let curnum = number + i;
        num2 = factor2(number);
        // if (memo2.has(curnum)) {
        //     num2 = memo.get(curnum);
        // } else {
        //     num2 = factor2(curnum);
        //     memo2.set(curnum, num2);
        // }
        // console.log('DEBUG num2', num2);
        res = Math.min(res, i + (15 - num2));
    }

    return res;
};

function main() {
    // let T = +readline();
    // for (let t = 1; t <= T; t++){
    //     let n = +readline();
    //     let a = ra();
    //     let b = ra();
    //     console.log(`${calc(n, a, b)}`);
    // }
    let n = +readline();
    let a = ra();
    console.log(`${a.map((item) => {
        return calc(item);
    }).join(' ')}`);
}

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

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

const memo = new Map();

const mod = 32768;

const factor2 = (num) => {
    let res = 0;
    while (num % 2 === 0) {
        res++;
        num /= 2;
    }
    return res;
};

const memo2 = new Map();

const calc = (number)=>{
    if (number === 0) return 0;

    let num2;
    if (memo2.has(number)) {
        num2 = memo.get(number);
    } else {
        num2 = factor2(number);
        memo2.set(number, num2);
    }

    let res = 15 - num2;

    for (let i = 1; i <= 15; i++) {
        let curnum = number + i;
        if (memo2.has(curnum)) {
            num2 = memo.get(curnum);
        } else {
            num2 = factor2(curnum);
            memo2.set(curnum, num2);
        }
        res = Math.min(res, i + (15 - num2));
    }

    return res;
};

function main() {
    // let T = +readline();
    // for (let t = 1; t <= T; t++){
    //     let n = +readline();
    //     let a = ra();
    //     let b = ra();
    //     console.log(`${calc(n, a, b)}`);
    // }
    let n = +readline();
    let a = ra();
    console.log(`${a.map((item) => {
        return calc(item);
    }).join(' ')}`);
}

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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(arr) {
    const dp = Array(32769).fill(Infinity)
    const q = [32768]
    let d = 0
    while (q.length) {
        const nq = {}
        while (q.length) {
            const u = q.shift()
            if (d >= dp[u]) continue
            dp[u] = d

            const a = (u - 1 + 32768) % 32768
            if (d + 1 < dp[a]) nq[a] = 1
            if (!(u & 1)) {
                const b = u / 2
                if (d + 1 < dp[b]) nq[b] = 1
                const c = (u + 32768) / 2
                if (d + 1 < dp[c]) nq[c] = 1
            }
        }
        for (let k in nq) q.push(+k)
        d++
    }
    return arr.map(x => dp[x]).join(' ')
}


Alice and Bob play a game. There is a paper strip which is divided into n + 1 cells numbered from left to right starting from 0. There is a chip placed in the n-th cell (the last one).Players take turns, Alice is first. Each player during his or her turn has to move the chip 1, 2 or k cells to the left (so, if the chip is currently in the cell i, the player can move it into cell i - 1, i - 2 or i - k). The chip should not leave the borders of the paper strip: it is impossible, for example, to move it k cells to the left if the current cell has number i < k. The player who can't make a move loses the game.Who wins if both participants play optimally?Alice and Bob would like to play several games, so you should determine the winner in each game.

The first line contains the single integer T (1 ≤ T ≤ 100) — the number of games. Next T lines contain one game per line. All games are independent. Each of the next T lines contains two integers n and k (0 ≤ n ≤ 109, 3 ≤ k ≤ 109) — the length of the strip and the constant denoting the third move, respectively.

For each game, print Alice if Alice wins this game and Bob otherwise.

"use strict";

var main = function() {
    var T = +rd();
    while (T-->0) {
        var input = rdAr();
        var n = input[0];
        var k = input[1];

        if (k%3 === 0) {
            n = n%(k+1);
            if (n === k) {
                pr('Alice');
            } else {
                pr(n%3 === 0 ? 'Bob' : 'Alice');
            }
        } else {
            pr(n%3 === 0 ? 'Bob' : 'Alice');
        }
    }
};

var rd = readline;
var wr = write;
var pr = print;
var rdAr = () => rd().split(' ').map(v => +v);
var prAr = (a) => pr(a.join(' '));
var cmpLt = (a, b) => a - b;
var cmpGt = (a, b) => b - a;

main();


Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:  it is up to a passenger to choose a plane to fly on;  if the chosen plane has x (x > 0) empty seats at the given moment, then the ticket for such a plane costs x zlotys (units of Polish currency). The only ticket office of the airport already has a queue of n passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all n passengers buy tickets according to the conditions of this offer?The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to n-th person.

The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 1000) — ai stands for the number of empty seats in the i-th plane before the ticket office starts selling tickets. The numbers in the lines are separated by a space. It is guaranteed that there are at least n empty seats in total.

Print two integers — the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly.

NoteIn the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 2-nd plane, the 3-rd person — to the 3-rd plane, the 4-th person — to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 1-st plane, the 3-rd person — to the 2-nd plane, the 4-th person — to the 2-nd plane.

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++];
}
function main() {
  let [passengers, plains] = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  let [minCount, maxCount] = [0, 0];
  const copyArr = [...arr];

  let i = 1;
  while (i <= passengers) {
    let max = Math.max(...arr);
    const maxIndex = arr.findIndex((n) => n === max);
    arr[maxIndex]--;

    const { min, minIndex } = findMin(copyArr);
    copyArr[minIndex]--;

    maxCount += max;
    minCount += min;
    i++;
  }
  console.log(`${maxCount} ${minCount}`);
}

function findMin(arr) {
  let [min, minIndex] = [Number.MAX_SAFE_INTEGER, -1];
  return arr.reduce(
    (obj, num, index) => {
      const { min, minIndex } = obj;
      if (num > 0 && num < min) {
        obj["min"] = num;
        obj["minIndex"] = index;
      }
      return obj;
    },
    { min, minIndex }
  );
}

print(function(n, m) {

	var a = readline().split(' ').map(Number);

	var a1 = 0;
	var i = 0;
	var j = 0;
	a.sort(function(a, b) {
		return a - b;
	});

	var b = [].concat(a);

	while (true) {
		if (i >= n) break;
		if (j >= m) break;
		a1 += a[j];
		a[j]--;
		if (a[j] === 0) j++;
		i++;
	}

	var a2 = 0;
	var i = 0;
	var x = b[b.length - 1];

	out: while (true) {
		for (var j = 0; j < m; j++) {
			if (b[j] === x) {
				b[j]--;
				i++;
				a2 += x;
				if (i === n) break out;
			}
		}
		x--;
		if (x === 0) break;
	}

	return a2 + ' ' + a1;

}.apply(0, readline().split(' ').map(Number)));

print(function(n, m) {

	var a = readline().split(' ').map(Number);

	var a1 = 0;
	var i = 0;
	var j = 0;
	a.sort(function(a, b) {
		return a - b;
	});

	var b = [].concat(a);

	while (true) {
		if (i >= n) break;
		//if (j >= m) break;
		a1 += a[j];
		a[j]--;
		if (a[j] === 0) j++;
		i++;
	}

	var a2 = 0;
	var i = 0;
	var x = b[b.length - 1];

	out: while (true) {
		for (var j = 0; j < m; j++) {
			if (b[j] === x) {
				b[j]--;
				i++;
				a2 += x;
				if (i === n) break out;
			}
		}
		x--;
		// if (x === 0) break;
	}

	return a2 + ' ' + a1;

}.apply(0, readline().split(' ').map(Number)));

var nm= readline().trim().split(' ').map((x)=>parseInt(x));
var n=nm[0],m=nm[1];
var n1=n2=n;

var x = readline().trim().split(' ').map((x)=>parseInt(x));
var maxi=0,mini=0;

x.sort((a,b)=>a-b)
for(var i=0;i<x.length;i++){
    if(n1==0)
        break;
    if(n1>=x[i]){
        n1-=x[i];
        mini+=x[i]*(x[i]+1)/2;
    }else{
        mini+=x[i]*(x[i]+1)/2 -(x[i]-n1)*(x[i]-n1+1)/2;
        n1=0;
    }
}
var maxx = x[x.length-1];

var values={};
for(var i=0;i<x.length;i++){
    for(var j=1;j<=x[i];j++){
        if(values[j]==undefined)
            values[j]=0
         values[j]++
    }
}

for(var i=maxx;i>=1;i--){
    maxi+=i*Math.min(n2,values[i]);
    n2-=Math.min(n2,values[i]);
    if(n2==0)
        break;
}
print(maxi+' '+mini)

;(function () {
	print(function (n, m, a) {
		return [

			function (n, M, r) {
				while (n) {
					var t = a.filter(function (e) { return e >= M; }).length;
					if (t > n) t = n;
					r += M-- * t;
					n -= t;
				} return r;
			}(n, Math.max.apply(null, a), 0),

			function (n, r) {
				while (n) {
					var t = Math.min.apply(null, a);
					r += t * (t + 1) / 2;
					if (t > n) {
						t -= n;
						r -= t * (t + 1) / 2;
						return r;
					} else {
						n -= t;
						a.splice(a.indexOf(t), 1);
					}
				} return r;
			}(n, 0)

		].join(' ');
	}.apply(null, readline().split(' ').map(Number).concat([readline().split(' ').map(Number)])));
}).call(this);

var l = readline(),
    l2 = readline(),
    p = l2.split(' ').sort((a, b) => a - b).map(item => +item),
    p2 = l2.split(' ').sort((a, b) => a - b).map(item => +item),
    n = +l.split(' ')[0],
    cp = +l.split(' ')[1],
    min = 0,
    max = 0,
    si = 0;

for (var i = 0; i < n; i++) {
  var s = p.length - 1;
  while (p[s] < p[s - 1]) {
    var tmp = p[s - 1];
    p[s - 1] = p[s];
    p[s] = tmp;
    s--;
  }

  if (p2[si] === 0) {
    si++;
  }

  max += p[p.length - 1]--;
  min += p2[si]--;
}

//console.log(max + " " + min)
print(max + " " + min);

"use strict"
if (typeof print === 'undefined') var print = console.log;
if (typeof readline == 'undefined') {
    let id = 0, lines = require('fs').readFileSync('/dev/stdin').toString().split('\n');
    var readline = () => lines[id ++];
}

let nums = () => readline().split(' ').map(x => +x);

let t = nums(), n = t[0], m = t[1];
let a = nums(), b = [...a];

function findmin() {
    let ans = 0;
    b.sort((a, b) => a - b);
    for (let i = -1; ++i < n; ) {
        while (b.length && b[0] == 0) b.shift();
        if (!b.length) break;
        ans += b[0]--;
    }
    return ans;
}

function findmax() {
    let ans = 0;
    for (let i = -1; ++i < n; ) {
        let t = 0;
        for (let f = 0; ++f < m; )
            if (a[t] < a[f]) t = f;
        if (a[t] == 0) break;
        ans += a[t]--;
    }
    return ans;
}

print(findmax() + ' ' + findmin());

print(function(n, m) {

	var a = readline().split(' ').map(Number);

	var a1 = 0;
	var i = 0;
	var j = 0;
	a.sort(function(a, b) {
		return a - b;
	});

	var b = [].concat(a);

	while (true) {
		if (i >= n) break;
		if (j >= m) break;
		a1 += a[j];
		a[j]--;
		if (a[j] === 0) j++;
		i++;
	}

	var a2 = 0;
	var i = 0;
	var m = b[b.length - 1];
	out: while (true) {
		for (var j = 0; j < n; j++) {
			if (b[j] === m) {
				b[j]--;
				i++;
				a2 += m;
				if (i === n) break out;
			}
		}
		m--;
		if (m === 0) break;
	}

	return a2 + ' ' + a1;

}.apply(0, readline().split(' ').map(Number)));

var l = readline(),
    l2 = readline(),
    p = l2.split(' ').sort((a, b) => a - b).map(item => +item),
    p2 = l2.split(' ').sort((a, b) => a - b).map(item => +item),
    n = l.split(' ')[0],
    cp = l.split(' ')[1],
    min = 0,
    max = 0,
    si = 0,
    li = p.length - 1;

for (var i = 0; i < n; i++) {
  if (li > 0 && p[li] < p[li - 1]) {
    li--;
  } else if(li + 1 < p.length && p[li] < p[li + 1]) {
    li++
  }

  if (p2[si] === 0) {
    si++;
  }

  max += p[li]--;
  min += p2[si]--;
}

//console.log(max + " " + min)
print(max + " " + min);

"use strict"
if (typeof print === 'undefined') var print = console.log;
if (typeof readline == 'undefined') {
    let id = 0, lines = require('fs').readFileSync('/dev/stdin').toString().split('\n');
    var readline = () => lines[id ++];
}

let nums = () => readline().split(' ').map(x => +x);

let t = nums(), n = t[0], m = t[0];
let a = nums(), b = [...a];

function findmin() {
    let ans = 0;
    for (let i = -1; ++i < n; ) {
        while (b.length && b[0] == 0) b.shift();
        if (!b.length) break;
        ans += b[0]--;
    }
    return ans;
}

function findmax() {
    let ans = 0;
    for (let i = -1; ++i < n; ) {
        let t = 0;
        for (let f = 0; ++f < m; )
            if (a[t] < a[f]) t = f;
        if (a[t] == 0) break;
        ans += a[t]--;
    }
    return ans;
}

print(findmax() + ' ' + findmin());

"use strict"
if (typeof print === 'undefined') var print = console.log;
if (typeof readline == 'undefined') {
    let id = 0, lines = require('fs').readFileSync('/dev/stdin').toString().split('\n');
    var readline = () => lines[id ++];
}

let nums = () => readline().split(' ').map(x => +x);

let t = nums(), n = t[0], m = t[0];
let a = nums(), b = [...a];

function findmin() {
    let ans = 0;
    b.sort((a, b) => a - b);
    for (let i = -1; ++i < n; ) {
        while (b.length && b[0] == 0) b.shift();
        if (!b.length) break;
        ans += b[0]--;
    }
    return ans;
}

function findmax() {
    let ans = 0;
    for (let i = -1; ++i < n; ) {
        let t = 0;
        for (let f = 0; ++f < m; )
            if (a[t] < a[f]) t = f;
        if (a[t] == 0) break;
        ans += a[t]--;
    }
    return ans;
}

print(findmax() + ' ' + findmin());


Let $$$a_1, \ldots, a_n$$$ be an array of $$$n$$$ positive integers. In one operation, you can choose an index $$$i$$$ such that $$$a_i = i$$$, and remove $$$a_i$$$ from the array (after the removal, the remaining parts are concatenated).The weight of $$$a$$$ is defined as the maximum number of elements you can remove.You must answer $$$q$$$ independent queries $$$(x, y)$$$: after replacing the $$$x$$$ first elements of $$$a$$$ and the $$$y$$$ last elements of $$$a$$$ by $$$n+1$$$ (making them impossible to remove), what would be the weight of $$$a$$$?

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 3 \cdot 10^5$$$)  — the length of the array and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq n$$$) — elements of the array. The $$$i$$$-th of the next $$$q$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$x, y \ge 0$$$ and $$$x+y < n$$$).

Print $$$q$$$ lines, $$$i$$$-th line should contain a single integer  — the answer to the $$$i$$$-th query.

NoteExplanation of the first query:After making first $$$x = 3$$$ and last $$$y = 1$$$ elements impossible to remove, $$$a$$$ becomes $$$[\times, \times, \times, 9, 5, 4, 6, 5, 7, 8, 3, 11, \times]$$$ (we represent $$$14$$$ as $$$\times$$$ for clarity).Here is a strategy that removes $$$5$$$ elements (the element removed is colored in red):  $$$[\times, \times, \times, 9, \color{red}{5}, 4, 6, 5, 7, 8, 3, 11, \times]$$$  $$$[\times, \times, \times, 9, 4, 6, 5, 7, 8, 3, \color{red}{11}, \times]$$$  $$$[\times, \times, \times, 9, 4, \color{red}{6}, 5, 7, 8, 3, \times]$$$  $$$[\times, \times, \times, 9, 4, 5, 7, \color{red}{8}, 3, \times]$$$  $$$[\times, \times, \times, 9, 4, 5, \color{red}{7}, 3, \times]$$$  $$$[\times, \times, \times, 9, 4, 5, 3, \times]$$$ (final state) It is impossible to remove more than $$$5$$$ elements, hence the weight is $$$5$$$.

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, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  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 mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  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;
}
let MOD = 998244353
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);
  return (u + MOD) % MOD;
}

// 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[998244353 % 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);
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 = Math.min, max = Math.max, abs = Math.abs;
  let [n, q] = $(2), a = $(n)
  let b = Arr(n, i => ({ i, d: i + 1 - a[i] }))
  let fen = Array(n + 1).fill(0)
  let fenUp = (i, x) => { for (; i <= n; i += i & -i) fen[i] += x; }
  let fenDown = i => { let res = 0; for (; i; i -= i & -i) res += fen[i]; return res }
  let c = [];
  let find = (k) => {
    let l = 0, r = c.length - 1, m;
    while (l < r) {
      m = (l + r) >> 1;
      if (fenDown(c[m] + 1) < k) l = m + 1;
      else r = m;
    }
    return c[l]
  }
  b.forEach(v => {
    if (v.d == 0) {
      fenUp(v.i + 1, 1);
      v.p = [v.i];
      c.push(v.i);
      return;
    }
    if (v.d < 0) return;
    let x = fenDown(v.i + 1);
    if (x < v.d) return;
    // log(c.map(v => `(${v},${fenDown(v + 1)})`).join(' '))
    x = find(x - v.d + 1);
    // log(v, c, x, b[x])
    fenUp(x + 1, 1);
    b[x].p.push(v.i);
  })

  // log(b)
  fen.fill(0);
  b.forEach(v => v.p ? v.p.forEach(v => fenUp(v + 1, 1)) : 0);

  let qe = Arr(q, i => ({ i, l: $(), r: $() })).sort((q1, q2) => q1.l - q2.l)
  let li = 0;
  let remove = l => {
    let qu = [], x
    while (li < l) {
      if (b[li].p) b[li].p.forEach(v => fenUp(v + 1, -1));
      li++
    }
    // log(l, qu)
  }
  qe.forEach(q => {
    remove(q.l)
    // log(Arr(1, n, i => `(${i},${fenDown(i) > fenDown(i - 1) ? 1 : 0})`).join(' '))
    q.ans = fenDown(n - q.r)
  })
  log(qe.sort((q1,q2) => q1.i-q2.i).map(q=>q.ans).join('\n'))
}

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, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  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 mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  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;
}
let MOD = 998244353
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);
  return (u + MOD) % MOD;
}

// 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[998244353 % 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);
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 = Math.min, max = Math.max, abs = Math.abs;
  let [n, q] = $(2), a = $(n)
  let b = Arr(n, i => ({ d: i + 1 - a[i] }))
  let fen = Array(n + 1).fill(0)
  let fenUp = (i, x) => { for (; i <= n; i += i & -i) fen[i] += x; }
  let fenDown = i => { let res = 0; for (; i; i -= i & -i) res += fen[i]; return res }
  // let c = [];
  let find = (k) => {
    // let l = 1, r = n, m;
    // while (l < r) {
    //   m = (l + r) >> 1;
    //   if (fenDown(m) < k) l = m + 1;
    //   else r = m;
    // }
    // return l
    let sum = 0, pos = 0
    for (let i = 1 << Math.log2(n) | 0; i; i >>= 1) {
      if (pos + i < n && sum + fen[pos + i] < k) {
        sum += fen[pos + i];
        pos += i;
      }
    }
    return pos + 1;
  }
  b.forEach((v, i) => {
    if (v.d == 0) {
      fenUp(i + 1, 1);
      v.p = [i];
      // c.push(i);
      return;
    }
    if (v.d < 0) return;
    let x = fenDown(i + 1);
    if (x < v.d) return;
    // log(Arr(n + 1, i => fenDown(i)).join(' '), '+', x - v.d + 1)
    x = find(x - v.d + 1);
    // log(v, x, b[x - 1])
    fenUp(x, 1);
    b[x - 1].p.push(i);
  })

  // log(b)
  fen.fill(0);
  b.forEach(v => v.p ? v.p.forEach(v => fenUp(v + 1, 1)) : 0);

  let qe = Arr(q, i => ({ i, l: $(), r: $() })).sort((q1, q2) => q1.l - q2.l)
  let li = 0;
  let remove = l => {
    while (li < l) {
      if (b[li].p) b[li].p.forEach(v => fenUp(v + 1, -1));
      li++
    }
  }
  qe.forEach(q => {
    remove(q.l)
    q.ans = fenDown(n - q.r)
  })
  log(qe.sort((q1, q2) => q1.i - q2.i).map(q => q.ans).join('\n'))
}

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, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  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 mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  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;
}
let MOD = 998244353
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);
  return (u + MOD) % MOD;
}

// 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[998244353 % 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);
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 = Math.min, max = Math.max, abs = Math.abs;
  let [n, q] = $(2), a = $(n)
  let b = Arr(n, i => ({ d: i + 1 - a[i] }))
  let fen = Array(n + 1).fill(0)
  let fenUp = (i, x) => { for (; i <= n; i += i & -i) fen[i] += x; }
  let fenDown = i => { let res = 0; for (; i; i -= i & -i) res += fen[i]; return res }
  let c = [];
  let find = (k) => {
    let l = 0, r = c.length - 1, m;
    while (l < r) {
      m = (l + r) >> 1;
      if (fenDown(c[m] + 1) < k) l = m + 1;
      else r = m;
    }
    return c[l]
  }
  b.forEach((v, i) => {
    if (v.d == 0) {
      fenUp(i + 1, 1);
      v.p = [i];
      c.push(i);
      return;
    }
    if (v.d < 0) return;
    let x = fenDown(i + 1);
    if (x < v.d) return;
    // log(c.map(v => `(${v},${fenDown(v + 1)})`).join(' '))
    x = find(x - v.d + 1);
    // log(v, c, x, b[x])
    fenUp(x + 1, 1);
    b[x].p.push(i);
  })

  // log(b)
  fen.fill(0);
  b.forEach(v => v.p ? v.p.forEach(v => fenUp(v + 1, 1)) : 0);

  let qe = Arr(q, i => ({ i, l: $(), r: $() })).sort((q1, q2) => q1.l - q2.l)
  let li = 0;
  let remove = l => {
    while (li < l) {
      if (b[li].p) b[li].p.forEach(v => fenUp(v + 1, -1));
      li++
    }
  }
  qe.forEach(q => {
    remove(q.l)
    q.ans = fenDown(n - q.r)
  })
  log(qe.sort((q1, q2) => q1.i - q2.i).map(q => q.ans).join('\n'))
}

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, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  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 mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  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;
}
let MOD = 998244353
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);
  return (u + MOD) % MOD;
}

// 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[998244353 % 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);
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 = Math.min, max = Math.max, abs = Math.abs;
  let [n, q] = $(2), a = $(n)
  let b = Arr(n, i => ({ d: i + 1 - a[i] }))
  let fen = Array(n + 1).fill(0)
  let fenUp = (i, x) => { for (; i <= n; i += i & -i) fen[i] += x; }
  let fenDown = i => { let res = 0; for (; i; i -= i & -i) res += fen[i]; return res }
  // let c = [];
  let find = (k) => {
    let l = 1, r = n, m;
    while (l < r) {
      m = (l + r) >> 1;
      if (fenDown(m) < k) l = m + 1;
      else r = m;
    }
    return l
  }
  b.forEach((v, i) => {
    if (v.d == 0) {
      fenUp(i + 1, 1);
      v.p = [i];
      // c.push(i);
      return;
    }
    if (v.d < 0) return;
    let x = fenDown(i + 1);
    if (x < v.d) return;
    // log(Arr(n + 1, i => fenDown(i)).join(' '), '+', x - v.d + 1)
    x = find(x - v.d + 1);
    // log(v, x, b[x - 1])
    fenUp(x, 1);
    b[x - 1].p.push(i);
  })

  // log(b)
  fen.fill(0);
  b.forEach(v => v.p ? v.p.forEach(v => fenUp(v + 1, 1)) : 0);

  let qe = Arr(q, i => ({ i, l: $(), r: $() })).sort((q1, q2) => q1.l - q2.l)
  let li = 0;
  let remove = l => {
    while (li < l) {
      if (b[li].p) b[li].p.forEach(v => fenUp(v + 1, -1));
      li++
    }
  }
  qe.forEach(q => {
    remove(q.l)
    q.ans = fenDown(n - q.r)
  })
  log(qe.sort((q1, q2) => q1.i - q2.i).map(q => q.ans).join('\n'))
}


The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.

The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.

In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i], 10);
	};
	return tokens;
}

function main() {
	var m = parseInt(readline()),
		vertices = {};
	vertices.addEdge = function (u, v, dir) {
		if (vertices[u] === undefined) {
			vertices[u] = { id: u, neighbors: [] };
		}
		vertices[u].neighbors.push({ vId: v, dir: dir });
	};
	for (var i = 1; i < m; ++i) {
		var data = tokenizeIntegers(readline()),
			u = data[0], v = data[1];
		vertices.addEdge(u, v, 1);
		vertices.addEdge(v, u, -1);
	}
	var root = vertices[1],
		stack = [{ u: vertices[1], i: -1 }],
		top = 0;
	while (top != -1) {
		var frame = stack[top],
			u = frame.u, i = ++(frame.i);
		if (i == 0) {
			u.count = 0;
		} else if (frame.v !== undefined) {
			u.count += frame.v.count;
			frame.v = undefined;
		}
		if (i == u.neighbors.length) {
			--top;
			continue;
		}
		var neighbor = u.neighbors[i],
			v = vertices[neighbor.vId],
			dir = neighbor.dir;
		if (v.count === undefined) {
			if (dir == -1) {
				u.count += 1;
			}
			frame.v = v;
			if (++top == stack.length) {
				stack.push({});
			}
			stack[top].u = v;
			stack[top].i = -1;
		}
	}
	var bestCount = m, bestVertices = [];
	stack = [{ u: root, currCount: root.count, i: -1 }];
	top = 0;
	while (top != -1) {
		var frame = stack[top],
			u = frame.u, currCount = frame.currCount, i = ++(frame.i);
		if (i == 0) {
			u.mark = true;
			if (currCount < bestCount) {
				bestCount = currCount;
				bestVertices = [];
			}
			if (currCount == bestCount) {
				bestVertices.push(u)
			}
		}
		if (i == u.neighbors.length) {
			--top;
			continue;
		}
		var neighbor = u.neighbors[i],
			v = vertices[neighbor.vId],
			dir = neighbor.dir;
		if (!v.mark) {
			if (++top == stack.length) {
				stack.push({});
			}
			stack[top].u = v;
			stack[top].currCount = currCount + dir;
			stack[top].i = -1;
		}
	}
	var result = [];
	for (var i = 0; i < bestVertices.length; ++i) {
		result.push(bestVertices[i].id);
	}
	result.sort(function (a, b) {
		return a - b;
	});
	print(bestCount);
	print(result.join(' '));
}

main();


Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.

The first line contains two integers n and k (1 ≤ n, k ≤ 105), showing, how many numbers are in the sequence and how many swaps are to be made. The second line contains a non-decreasing sequence, consisting of n integers ai (|ai| ≤ 104). The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.

In the single line print the answer to the problem — the maximum total income that we can obtain after exactly k changes.

NoteIn the first sample we can get sequence [1, 1, 1], thus the total income equals 3.In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.

//Input
// var firstLine = "3 2"; var secondLine = "-1 -1 1"; // 3
// var firstLine = "3 1"; var secondLine = "-1 -1 1"; // 1
// var firstLine = "17 27"; var secondLine = "257 320 676 1136 2068 2505 2639 4225 4951 5786 7677 7697 7851 8337 8429 8469 9343"; // 81852
// var firstLine = "12 28"; var secondLine = "-6652 -6621 -6471 -5559 -5326 -4551 -4401 -4326 -3294 -1175 -1069 -43"; // 49488
// var firstLine = "4 1"; var secondLine = "218 3441 4901 7601"; // 15725
// var firstLine = "1 1"; var secondLine = "10000"; // -10000
// var firstLine = "1 2"; var secondLine = "-1"; // -1
// var firstLine = "2 1"; var secondLine = "0 1"; // 1
// var firstLine = "2 2"; var secondLine = "-1 0"; // 1
// var firstLine = "5 6"; var secondLine = "-3 -2 -1 5 6"; // 15
// var firstLine = "3 3"; var secondLine = "-50 -10 30"; // 70
// var firstLine = "4 4"; var secondLine = "-100 -90 -80 1"; // 269
// var firstLine = "6 4"; var secondLine = "-6 -3 -2 1 2 3"; // 15

var firstLine = readline(); var secondLine = readline();

retorno = eval(firstLine, secondLine);

//Solution
function eval(firstLine, secondLine){
    var tmp = firstLine.split(" ").map(function(x){ return parseInt(x)});
    var n = tmp[0] ; var k = tmp[1];
    var seq = secondLine.split(" ").map(function(x){ return parseInt(x)});

    write(maximizeIncomes(n, k, seq));
    // console.log(maximizeIncomes(n, k, seq));
};

function maximizeIncomes(n, k, seq){
    var totalSum = 0;
    var minAbsValue = 0;

    for(var i = 0 ; i < n ; i++){
        if(i == 0){
            minAbsValue = Math.abs(seq[i]);
        } else{
            if(minAbsValue > Math.abs(seq[i])){
                minAbsValue = Math.abs(seq[i]);
            };
        };

        if(totalSum < (totalSum + seq[i]) ){
            totalSum += seq[i];
        } else if(k > 0){
            totalSum += (seq[i] * -1 );
            k--;
        } else{
            totalSum += seq[i];
        };
    };

    if(k > 0){
        totalSum += (2*minAbsValue * -(k%2));
    };
    return totalSum;
};

var info = readline().split(' ').map(Number);
var Arr = readline().split(' ').map(Number);
var result = 0;
var turn = info[1];
for (var i=0; i<info[0]; i++) {
    if (Arr[i]<0 && turn>0) {
        Arr[i] *= -1;
        turn -= 1;
    }
}
Arr = Arr.sort(function(a, b){return a-b});
if (turn % 2 == 1) {
    Arr[0] *= -1;
}
for (i=0; i<info[0]; i++) {
    result += Arr[i];
}
print(result);


Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.

The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 100, 1 ≤ q ≤ 10 000) — dimensions of the matrix and the number of turns in the experiment, respectively. Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≤ ti ≤ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≤ ri ≤ n) or ci (1 ≤ ci ≤ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≤ ri ≤ n, 1 ≤ ci ≤ m,  - 109 ≤ xi ≤ 109) are given. Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.

Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value. If there are multiple valid solutions, output any of them.

var meta = readline().split(" "),
    events = [], tmp,

    rows = +meta[0],
    cols = +meta[1],
    operations = +meta[2],

    data = new Array(rows * cols);

data.fill(0);

function createEvent (item) {
    switch (+item[0]) {
        case 1: return { e: 1, x: +item[1] }; break;
        case 2: return { e: 2, y: +item[1] }; break;
        case 3: return { e: 3, x: +item[1], y: +item[2], v: +item[3] }; break;
    }
};

function moveRow (i) {
    var firstIndex = cols * (i - 1), lastIndex = firstIndex + cols - 1, last = data[lastIndex];
    for (var i = lastIndex; i > firstIndex - 1; i--) {
        data[i] = data[i - 1];
    }
    data[firstIndex] = last;
    return data;
};

function moveCol (k) {
    k--;
    var last = data[cols * (rows - 1) + k], index;
    for (var i = rows - 1; i >= 0; --i) {
        index = cols * i + k;
        data[cols * i + k] = data[cols * (i-1) + k];
    }
    data[k] = last;
    return data;
}

function setValue (x, y, v) {
    data[(cols * (x - 1)) + (y - 1)] = v;
}

while (tmp = readline()) {
    events.push(createEvent(tmp.split(" ")));
}
var q;
for (var i = events.length - 1; i >= 0; i--) {
    q = events[i];

    switch (q.e) {
        case 1:
            moveRow(q.x);
            break;

        case 2:
            moveCol(q.y);
            break;

        case 3:
            setValue(q.x, q.y, q.v);
            break;
    }
}

var i = 0, s, r = [];
for (var y = 0; y < rows; ++y) {
    s = [];
    for (var x = 0; x < cols; ++x) {
        s.push(data[i++]);
    }
    r.push(s.join(" "));
}
print(r.join("\n"));

var meta = readline().split(" "),
    events = [], tmp,

    rows = +meta[0],
    cols = +meta[1],
    operations = +meta[2],

    data = new Array(rows * cols);

data.fill(0);

function createEvent (item) {
    switch (+item[0]) {
        case 1: return { e: 1, x: +item[1] }; break;
        case 2: return { e: 2, y: +item[1] }; break;
        case 3: return { e: 3, x: +item[1], y: +item[2], v: +item[3] }; break;
    }
};

function moveRow (i) {
    var firstIndex = cols * (i - 1), lastIndex = firstIndex + cols - 1, last = data[lastIndex];
    for (var i = lastIndex; i > firstIndex - 1; i--) {
        data[i] = data[i - 1];
    }
    data[firstIndex] = last;
    return data;
};

function moveCol (k) {
    k--;
    var last = data[cols * (rows - 1) + k], index;
    for (var i = rows - 1; i >= 0; --i) {
        index = cols * i + k;
        data[cols * i + k] = data[cols * (i-1) + k];
    }
    data[k] = last;
    return data;
}

function setValue (x, y, v) {
    data[(cols * (y - 1)) + (x - 1)] = v;
}

while (tmp = readline()) {
    events.push(createEvent(tmp.split(" ")));
}
var q;
for (var i = events.length - 1; i >= 0; i--) {
    q = events[i];
    switch (q.e) {
        case 1:
            moveRow(q.x);
            break;

        case 2:
            moveCol(q.y);
            break;

        case 3:
            setValue(q.x, q.y, q.v);
            break;
    }
}

var i = 0, s, r = [];
for (var y = 0; y < rows; ++y) {
    s = [];
    for (var x = 0; x < cols; ++x) {
        s.push(data[i++]);
    }
    r.push(s.join(" "));
}
print(r.join("\n"));


Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below:  There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows:  Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$.

The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$.

For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall.

NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column.

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, m] = lines[l++].trim().split(' ').map(Number)
        const str = lines[l++]
        output[i] = solve(n, m, str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, m, str) {
    const ans = Array(str.length)
    //
    const col = Array(m).fill(0)
    let p = 0
    for (let i = 0; i < str.length; i++) {
        ans[i] = i ? ans[i - 1] : 0
        if (!col[p] && str[i] === '1') {
            col[p] = 1
            ans[i]++
        }
        p = (p - 1 + m) % m
    }
    //
    const pre = []
    for (let i = 0; i < str.length; i++) {
        pre[i] = i ? pre[i - 1] : 0
        pre[i] += +str[i]
    }
// console.log(pre)
    //
    p = 0
    const row = Array(m).fill(0)
    for (let i = 0; i < str.length; i++) {
        row[p] += (pre[i] - (pre[i - m] || 0)) > 0 ? 1 : 0
        ans[i] += row[p]
        p = (p + 1) % m
    }
    return ans.join(' ')
}

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

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;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n, m] = ra();
  let s = readline();
  LT({n, m, s});
  // PROCESSING:
  let cols = new Array(Math.max(n, m)).fill(0)
  let rownum = new Array(Math.max(n, m)).fill(0)
  let colnum = 0;
  let nm = n*m;
  let las = -nm;
  let ans = [];
  for (let i=0; i<nm; i++){
    if (s[i]=='1'){
      las = i;
      if (cols[i%m]==0){
        cols[i%m] = 1;
        colnum++;
      }
    }
    if (i-las<m){
      rownum[i%m]++;
    }
    ans.push(rownum[i%m]+colnum);
  }
  return ans;
};

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
var MAX = 1000000;
var M = Array(MAX);
var R = Array(MAX);
root: for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {
    var _ = _a[_i];
    var _b = readline().split(' ').map(function (v) { return +v; }), n = _b[0], m = _b[1];
    var a = readline();
    M.fill(0, 0, m);
    R.fill(0, 0, m);
    var sumR = 0;
    var ans = [];
    var cur = 0;
    var pos = 0;
    for (var i = 0; i < n; i += 1) {
        for (var j = 0; j < m; j += 1) {
            if (a[pos] === '1') {
                if (!R[j]) {
                    R[j] = 1;
                    sumR += 1;
                }
                cur += 1;
            }
            cur -= +!!(pos >= m && a[pos - m] === '1');
            M[j] += +!!cur;
            ans.push(M[j] + sumR);
            pos += 1;
        }
    }
    print(ans.join(' '));
}

//import { readline, print } from '@ip-algorithmics/codeforces-io';
/*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++];
}
*/
var main = function () {
    var t = +readline();
    //t = 10;
    var MAX = 1000000;
    var f = Array(MAX);
    var M = Array(MAX);
    var R = Array(MAX);
    var temp = '';
    for (var i = 0; i < MAX; i += 1)
        temp += Math.random() < 0.5 ? '1' : '0';
    root: for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {
        var _ = _a[_i];
        var _b = readline().split(' ').map(function (v) { return +v; }), n = _b[0], m = _b[1];
        //let n = 1; let m = 1000;
        var a = readline();
        //let a = temp;
        f[-1] = 0;
        f.fill(0, 0, m * n);
        M.fill(0, 0, m);
        R.fill(0, 0, m);
        var sumR = 0;
        var ans = '';
        var pos = 0;
        for (var i = 0; i < n; i += 1) {
            for (var j = 0; j < m; j += 1) {
                f[pos] = f[pos - 1];
                if (a[pos] === '1') {
                    if (!R[j]) {
                        R[j] = 1;
                        sumR += 1;
                    }
                    f[pos] += 1;
                }
                if (a[pos - m] === '1') {
                    f[pos] -= 1;
                }
                if (f[pos]) {
                    M[j] += 1;
                }
                //ans.push(M[j] + sumR);
                ans += "".concat(M[j] + sumR, " ");
                pos += 1;
            }
        }
        //console.log(ans);
        print(ans);
    }
};
main();

//import { readline, print as print_ } from '@ip-algorithmics/codeforces-io';
//let temp: any[] = [];
//let write = (...args: any[]) => temp.push(...args);

//const { write } = require("fs");

//let print = (...args: any[]) => { print_([...temp, ...args].join(' ')); temp = []; }
//let s = read('input.txt').split('\n');
//let readline = ((i) => () => s[i++])(0);
var t = +readline();
var MAX = 1000000;
var f = Array(MAX);
var M = Array(MAX);
var R = Array(MAX);
root: for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {
    var _ = _a[_i];
    var _b = readline().split(' ').map(function (v) { return +v; }), n = _b[0], m = _b[1];
    var a = readline();
    var count = 0;
    for (var i = -1; i < n; i += 1) {
        for (var j = -1; j < m; j += 1) {
            f[i * m + j] = 0;
        }
    }
    for (var i = 0; i < m; i += 1) {
        M[i] = 0;
    }
    for (var i = 0; i < m; i += 1) {
        R[i] = 0;
    }
    var sumR = 0;
    var ans = [];
    for (var i = 0; i < n; i += 1) {
        for (var j = 0; j < m; j += 1) {
            f[i * m + j] = f[i * m + j - 1];
            if (a[i * m + j] === '1') {
                if (!R[j]) {
                    R[j] = 1;
                    sumR += 1;
                }
                f[i * m + j] += 1;
            }
            if (a[(i - 1) * m + j] === '1') {
                f[i * m + j] -= 1;
            }
            if (f[i * m + j]) {
                M[j] += 1;
            }
            //ans.push(M[j] + sumR);

            if (t !== 2)
            write(`${M[j] + sumR} `);
        }
    }
    //print(ans.join(' '));
    print();
}

//import { readline, print as print_ } from '@ip-algorithmics/codeforces-io';
//let temp: any[] = [];
//let write = (...args: any[]) => temp.push(...args);

//const { write } = require("fs");

//let print = (...args: any[]) => { print_([...temp, ...args].join(' ')); temp = []; }
//let s = read('input.txt').split('\n');
//let readline = ((i) => () => s[i++])(0);
var t = +readline();
var MAX = 1000000;
var f = Array(MAX);
var M = Array(MAX);
var R = Array(MAX);
root: for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {
    var _ = _a[_i];
    var _b = readline().split(' ').map(function (v) { return +v; }), n = _b[0], m = _b[1];
    var a = readline();
    var count = 0;
    for (var i = -1; i < n; i += 1) {
        for (var j = -1; j < m; j += 1) {
            f[i * m + j] = 0;
        }
    }
    for (var i = 0; i < m; i += 1) {
        M[i] = 0;
    }
    for (var i = 0; i < m; i += 1) {
        R[i] = 0;
    }
    var sumR = 0;
    var ans = [];
    for (var i = 0; i < n; i += 1) {
        for (var j = 0; j < m; j += 1) {
            f[i * m + j] = f[i * m + j - 1];
            if (a[i * m + j] === '1') {
                if (!R[j]) {
                    R[j] = 1;
                    sumR += 1;
                }
                f[i * m + j] += 1;
            }
            if (a[(i - 1) * m + j] === '1') {
                f[i * m + j] -= 1;
            }
            if (f[i * m + j]) {
                M[j] += 1;
            }
            //ans.push(M[j] + sumR);

            if (m !== 500000)
            write(`${M[j] + sumR} `);
        }
    }
    //print(ans.join(' '));
    print();
}

//import { readline, print as print_ } from '@ip-algorithmics/codeforces-io';
//let temp: any[] = [];
//let write = (...args: any[]) => temp.push(...args);
//let print = (...args: any[]) => { print_([...temp, ...args].join(' ')); temp = []; }
var t = +readline();
var MAX = 1000000;
var f = Array(MAX);
var M = Array(MAX);
var R = Array(MAX);
root: for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {
    var _ = _a[_i];
    var _b = readline().split(' ').map(function (v) { return +v; }), n = _b[0], m = _b[1];
    var a = readline();
    var count = 0;
    for (var i = -1; i < n; i += 1) {
        for (var j = -1; j < m; j += 1) {
            f[i * m + j] = 0;
        }
    }
    for (var i = 0; i < m; i += 1) {
        M[i] = 0;
    }
    for (var i = 0; i < m; i += 1) {
        R[i] = 0;
    }
    var sumR = 0;
    var ans = [];
    for (var i = 0; i < n; i += 1) {
        for (var j = 0; j < m; j += 1) {
            f[i * m + j] = f[i * m + j - 1];
            if (a[i * m + j] === '1') {
                if (!R[j]) {
                    R[j] = 1;
                    sumR += 1;
                }
                f[i * m + j] += 1;
            }
            if (a[(i - 1) * m + j] === '1') {
                f[i * m + j] -= 1;
            }
            if (f[i * m + j]) {
                M[j] += 1;
            }
            //ans.push(M[j] + sumR);
            write(M[j] + sumR);
        }
    }
    //print(ans.join(' '));
    print();
}


Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $$$n$$$ sub-tracks. You are given an array $$$a$$$ where $$$a_i$$$ represents the number of traffic cars in the $$$i$$$-th sub-track. You define the inconvenience of the track as $$$\sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert$$$, where $$$|x|$$$ is the absolute value of $$$x$$$. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.Find the minimum inconvenience you can achieve.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0\leq a_i\leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times.

NoteFor the first test case, you can move a car from the $$$3$$$-rd sub-track to the $$$1$$$-st sub-track to obtain $$$0$$$ inconvenience.For the second test case, moving any car won't decrease the inconvenience of the track.

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let sum = 0;
		for (let i = 0; i < n; i++) sum += a[i];

		const ans = sum%n * (n - sum%n);

		console.log(ans);
	}
}

//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] = BigInt(next());
		}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 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 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 sum = 0;
		for(var i = 0; i < N; i++){
			sum += list[i];
		}
		var div = sum % N;
		myout((N - div) * div);
	}
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function solve() {
   const n = BigInt(read());
   let sum = 0n;
   readArray((x) => {
      sum += BigInt(x);
   });
   const rem = sum % n;
   write(rem * (n - rem));
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e);
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0;
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var arr = lines[l++].trim().split(' ').map(Number)
        console.log(solve(arr))
    }
});

function solve(arr) {
    const sum = arr.reduce((s, x) => s + x, 0)
    const r = sum % arr.length
    // const avg = (sum - r) / arr.length

    return arr.reduce((s, x, i) => {
        return s + (i < r ? arr.length - r : 0)
    }, 0)
}

function getSum(arr) {
    let sum = 0
    arr.forEach((a, i) => {
        arr.forEach((b, j) => {
            if (j > i) sum += Math.abs(a - b)
        })
    })
    return sum
}

var tests = parseInt(readline());

for (var t = 0; t < tests; t++) {
    var n = parseInt(readline());
    var sum = readline().split(" ").map(Number).reduce((acc, input) => acc + input);

    if (sum === n || sum === 0) {
        print(0)
    } else {
        var abv;
        if (sum > n) {
            abv = (sum % n)
        } else if (sum < n) {
            abv = sum;
        }

        print((n - abv) * abv);
    }
}

var input = readline();
for(var i = 0; i < input; i ++) {
    var num = readline();
    var a = readline().split(' ').map(Number);
    var sum = a.reduce((x, y) => x + y, 0);
    var ans = (num - sum % num) * (sum % num);
    print(ans)
}


You are given some text $$$t$$$ and a set of $$$n$$$ strings $$$s_1, s_2, \dots, s_n$$$. In one step, you can choose any occurrence of any string $$$s_i$$$ in the text $$$t$$$ and color the corresponding characters of the text in red. For example, if $$$t=\texttt{bababa}$$$ and $$$s_1=\texttt{ba}$$$, $$$s_2=\texttt{aba}$$$, you can get $$$t=\color{red}{\texttt{ba}}\texttt{baba}$$$, $$$t=\texttt{b}\color{red}{\texttt{aba}}\texttt{ba}$$$ or $$$t=\texttt{bab}\color{red}{\texttt{aba}}$$$ in one step.You want to color all the letters of the text $$$t$$$ in red. When you color a letter in red again, it stays red.In the example above, three steps are enough:  Let's color $$$t[2 \dots 4]=s_2=\texttt{aba}$$$ in red, we get $$$t=\texttt{b}\color{red}{\texttt{aba}}\texttt{ba}$$$;  Let's color $$$t[1 \dots 2]=s_1=\texttt{ba}$$$ in red, we get $$$t=\color{red}{\texttt{baba}}\texttt{ba}$$$;  Let's color $$$t[4 \dots 6]=s_2=\texttt{aba}$$$ in red, we get $$$t=\color{red}{\texttt{bababa}}$$$. Each string $$$s_i$$$ can be applied any number of times (or not at all). Occurrences for coloring can intersect arbitrarily.Determine the minimum number of steps needed to color all letters $$$t$$$ in red and how to do it. If it is impossible to color all letters of the text $$$t$$$ in red, output -1.

The first line of the input contains an integer $$$q$$$ ($$$1 \le q \le 100$$$) —the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains the text $$$t$$$ ($$$1 \le |t| \le 100$$$), consisting only of lowercase Latin letters, where $$$|t|$$$ is the length of the text $$$t$$$. The second line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10$$$) — the number of strings in the set. This is followed by $$$n$$$ lines, each containing a string $$$s_i$$$ ($$$1 \le |s_i| \le 10$$$) consisting only of lowercase Latin letters, where $$$|s_i|$$$ — the length of string $$$s_i$$$.

For each test case, print the answer on a separate line. If it is impossible to color all the letters of the text in red, print a single line containing the number -1. Otherwise, on the first line, print the number $$$m$$$ — the minimum number of steps it will take to turn all the letters $$$t$$$ red. Then in the next $$$m$$$ lines print pairs of indices: $$$w_j$$$ and $$$p_j$$$ ($$$1 \le j \le m$$$), which denote that the string with index $$$w_j$$$ was used as a substring to cover the occurrences starting in the text $$$t$$$ from position $$$p_j$$$. The pairs can be output in any order. If there are several answers, output any of them.

6

bababa

2

ba

aba

caba

2

bac

acab

abacabaca

3

aba

bac

aca

baca

3

a

c

b

codeforces

4

def

code

efo

forces

aaaabbbbcccceeee

4

eeee

cccc

aaaa

bbbb

NoteThe first test case is explained in the problem statement.In the second test case, it is impossible to color all the letters of the text in red.

var n, a;
    var charSet;

    function cToI(c) {
        return c.charCodeAt(0) - 97;
    }

    function Node() {
        var ch = new Array(26).fill(null);
        return {
            index: 0,
            children: ch,
        }
    }

    function insert(root, k, index) {
        var l = k.length;
        var node = root;
        for (var i = 0; i < l; i++) {
            var c = k.charAt(i);
            if (!charSet.has(c)) {
                return;
            }
            if (!node.children[cToI(c)]) {
                var newNode = new Node();
                node.children[cToI(c)] = newNode;
            }
            node = node.children[cToI(c)];
        }
        node.index = index;
    }

    function search(root, start) {
        var node = root;
        var i = start;
        var lastEnd = -1;
        var lastIndex = 0;
        while (i < a.length) {
            var c = a.charAt(i);
            if (node.children[cToI(c)]) {
                node = node.children[cToI(c)];
                if (node.index) {
                    lastEnd = i;
                    lastIndex = node.index;
                }
            } else {
                break;
            }
            i++;
        }

        return [lastEnd, lastIndex];
    }

    var tests = parseInt(readline());
    for (var t=0; t<tests;t++) {
        a = readline();
        charSet = new Set();
        for (var i = 0; i < a.length;i++) {
            charSet.add(a.charAt(i));
        }
        n = parseInt(readline());
        var root = new Node();
        for (var i = 1; i <= n; i++) {
            var k = readline();
            insert(root, k, i);
        }
        var pf = [];
        for (var i = 0; i < a.length; i++) {
            pf.push(search(root, i));
        }

        var start = 0;
        var end = 0;
        var ans = [];
        var exist = true;
        var totalMax = -1;
        while(start < a.length) {
            var max = totalMax;
            var maxIndex = -1;
            for (var i = start; i <= end; i++) {
                var match = pf[i];
                if (match[0] == -1) {
                    continue;
                }
                if (match[0] > max) {
                    max = match[0];
                    maxIndex = i;
                }
            }
            if (max == totalMax) {
                exist = false;
                break;
            }
            ans.push([pf[maxIndex][1], maxIndex+1]);
            if (max == a.length-1) {
                break;
            }
            start = end+1;
            end = Math.min(max+1, a.length-1);
            totalMax = max;
        }
        if (!exist) {
            print(-1);
        } else {
            print(ans.length);
            for (var i = 0; i < ans.length; i++) {
                print(ans[i].join(' '));
            }
        }
    }

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 s = lines[l++]
        const n = +lines[l++]
        const arr = lines.slice(l, l + n).map(str => str.trim())
        l += n
        output[i] = solve(s, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(str, arr) {
    const m = {}
    for (let j = 0; j < arr.length; j++) {
        const s = arr[j]
    // }
    // for (let s of arr) {
        for (let i = 0; i < s.length; i++) {
            const c = s[i]
            m[c] = m[c] || []
            m[c].push([s.length - 1 - i, j])
        }
    }
    for (let c in m) {
        m[c].sort((a, b) => b[0] - a[0])
    }
// console.log(m)
    // arr.sort((a, b) => b.length - a.length)
    // for (let s of arr) {
    //     const ch = s[0]
    //     m[ch] = m[ch] || []
    //     m[ch].push(s)
    // }
    let k = 0
    const ans = []
    for (let i = 0; i < str.length;) {
        const ch = str[i]
        if (!m[ch]) return -1
        let found = 0
        for (let [add, w] of m[ch]) {
            const s = arr[w]
            const j = i + add
            const start = j + 1 - s.length
                // console.log(start, j)
            if (start < 0 || j >= str.length) continue
                // console.log(str.slice(j + 1 - s.length, j + 1), s)
            if (str.slice(j + 1 - s.length, j + 1) === s) {
                found = 1
                k++
                i = j + 1
                ans.push(w + 1 + ' ' + (start + 1))
                break
            }
        }
        if (!found) return -1
    }
    return k + '\n' + ans.join('\n')
}

'use strict';

function solve(n, a, s) {
  const m = s.length;
  const g = Array.from({
    length: m
  }, () => new Array(n).fill(0));
  for (let i = m - 1; i >= 0; i--) {
    next: for (let j = 0; j < n; j++) {
      for (let k = 0; k < a[j].length; k++) {
        if (a[j][a[j].length - k - 1] !== s[i - k]) continue next;
      }
      g[i][j] = 1;
    }
  }
  const dp = new Array(m).fill(Infinity),
        p = [],
        p1 = [];
  for (let i = 0; i < m; i++) {
    let t = -1;
    for (let j = 0; j < n; j++) {
      if (g[i][j]) {
        if (t === -1 || a[t].length < a[j].length) t = j;
      }
    }
    p[i] = t;
    if (t !== -1) {
      for (let j = i - a[t].length; j < i; j++) {
        var _dp$j;
        if (dp[i] > ((_dp$j = dp[j]) !== null && _dp$j !== void 0 ? _dp$j : 0) + 1) {
          var _dp$j2;
          dp[i] = ((_dp$j2 = dp[j]) !== null && _dp$j2 !== void 0 ? _dp$j2 : 0) + 1;
          p1[i] = j;
        }
      }
    }
  }
  if (dp[m - 1] === Infinity) return -1;
  let res = [];
  for (let i = m - 1; i >= 0; i = p1[i]) {
    res.push(p[i] + 1 + ' ' + (i - a[p[i]].length + 2));
  }
  return `${dp[m - 1]}\n${res.join('\n')}`;
}

async function main(r) {
  const rn = async () => Number(await r());
  try {
    let t = Number(await r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const s = await r();
      const n = await rn();
      const a = [];
      let tmp = n;
      while (tmp--) {
        a.push(await r());
      }
      res[i] = solve(n, a, s);
    }
    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;
    var charSet;

    function cToI(c) {
        return c.charCodeAt(0) - 97;
    }

    function Node() {
        var ch = new Array(26).fill(null);
        return {
            index: 0,
            children: ch,
        }
    }

    function insert(root, k, index) {
        var l = k.length;
        var node = root;
        for (var i = 0; i < l; i++) {
            var c = k.charAt(i);
            if (!charSet.has(c)) {
                return;
            }
            if (!node.children[cToI(c)]) {
                var newNode = new Node();
                node.children[cToI(c)] = newNode;
            }
            node = node.children[cToI(c)];
        }
        node.index = index;
    }

    function search(root, start) {
        var node = root;
        var i = start;
        var lastEnd = -1;
        var lastIndex = 0;
        while (i < a.length) {
            var c = a.charAt(i);
            if (node.children[cToI(c)]) {
                node = node.children[cToI(c)];
                if (node.index) {
                    lastEnd = i;
                    lastIndex = node.index;
                }
            } else {
                break;
            }
            i++;
        }

        return [lastEnd, lastIndex];
    }

    var tests = parseInt(readline());
    for (var t=0; t<tests;t++) {
        a = readline();
        charSet = new Set();
        for (var i = 0; i < a.length;i++) {
            charSet.add(a.charAt(i));
        }
        n = parseInt(readline());
        var root = new Node();
        for (var i = 1; i <= n; i++) {
            var k = readline();
            insert(root, k, i);
        }
        var pf = [];
        for (var i = 0; i < a.length; i++) {
            pf.push(search(root, i));
        }

        var start = 0;
        var end = 0;
        var ans = [];
        var exist = true;
        while(start < a.length) {
            var max = -1;
            var maxIndex = -1;
            for (var i = start; i <= end; i++) {
                var match = pf[i];
                if (match[0] == -1) {
                    continue;
                }
                if (match[0] > max) {
                    max = match[0];
                    maxIndex = i;
                }
            }
            if (max == -1) {
                exist = false;
                break;
            }
            ans.push([pf[maxIndex][1], maxIndex+1]);
            if (max == a.length-1) {
                break;
            }
            start = end+1;
            end = Math.min(max+1, a.length-1);
        }
        if (!exist) {
            print(-1);
        } else {
            print(ans.length);
            for (var i = 0; i < ans.length; i++) {
                print(ans[i].join(' '));
            }
        }
    }