You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times):  choose two indexes, i and j (1 ≤ i < j ≤ n; (j - i + 1) is a prime number);  swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments: tmp = a[i], a[i] = a[j], a[j] = tmp (tmp is a temporary variable). You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n distinct integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ n).

In the first line, print integer k (0 ≤ k ≤ 5n) — the number of used operations. Next, print the operations. Each operation must be printed as "i j" (1 ≤ i < j ≤ n; (j - i + 1) is a prime). If there are multiple answers, you can print any of them.

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 n = parseInt(readline()),
		isComposite = new Array(n+1),
		primes = [],
		prime = 1;
	isComposite[1] = true;
	while (true) {
		++prime;
		while (prime <= n && isComposite[prime]) {
			++prime;
		}
		if (prime > n) {
			break;
		}
		primes.push(prime);
		for (var seek = 2*prime; seek <= n; seek += prime) {
			isComposite[seek] = true;
		}
	}
	function primeFloor(target) {
		var low = 0, high = primes.length-1;
		while (low != high) {
			var mid = Math.floor((low+high)/2);
			if (primes[mid] == target) {
				return primes[mid];
			}
			if (primes[mid] > target) {
				high = mid-1;
			} else {
				if (primes[mid+1] > target) {
					return primes[mid];
				}
				low = mid+1;
			}
		}
		return primes[low];
	}
	var arr = tokenizeIntegers(readline()),
		swaps = [], stack = [];
	arr.unshift(null);
	function swap(i, j) {
		var temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
		swaps.push(Math.min(i, j)+' '+Math.max(i, j));
	}
	for (var i = 1; i < arr.length; ++i) {
		if (arr[i] == i) {
			continue;
		}
		var distance = arr[i] - i,
			direction = distance / Math.abs(distance),
			pos = i;
		distance *= direction;
		while (distance != 0) {
			stack.push(primeFloor(distance+1) - 1);
			var jump = stack[stack.length-1],
				next = pos + direction*jump;
			swap(pos, next);
			pos = next;
			distance -= jump;
		}
		pos -= direction*stack.pop();
		while (stack.length != 0) {
			next = pos - direction*stack.pop();
			swap(pos, next);
			pos = next;
		}
		--i;
	}
	print(swaps.length);
	if (swaps.length != 0) {
		print(swaps.join('\n'));
	}
}

main();

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 n = parseInt(readline()),
		isComposite = new Array(n+1),
		primes = [],
		prime = 2;
	while (true) {
		primes.push(prime);
		++prime;
		while (prime <= n && isComposite[prime]) {
			++prime;
		}
		if (prime > n) {
			break;
		}
		for (var seek = 2*prime; seek <= n; seek += prime) {
			isComposite[seek] = true;
		}
	}
	function primeFloor(target) {
		var low = 0, high = primes.length-1;
		while (low != high) {
			var mid = Math.floor((low+high)/2);
			if (primes[mid] == target) {
				return primes[mid];
			}
			if (primes[mid] > target) {
				high = mid-1;
			} else {
				if (primes[mid+1] > target) {
					return primes[mid];
				}
				low = mid+1;
			}
		}
		return primes[low];
	}
	var arr = tokenizeIntegers(readline()),
		swaps = [], stack = [];
	arr.unshift(null);
	function swap(i, j) {
		var temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
		swaps.push(i+' '+j);
	}
	for (var i = 1; i < arr.length; ++i) {
		if (arr[i] == i) {
			continue;
		}
		var distance = arr[i] - i,
			direction = distance / Math.abs(distance),
			pos = i;
		distance *= direction;
		while (distance != 0) {
			stack.push(primeFloor(distance+1) - 1);
			var jump = stack[stack.length-1],
				next = pos + direction*jump;
			swap(pos, next);
			pos = next;
			distance -= jump;
		}
		pos -= direction*stack.pop();
		while (stack.length != 0) {
			next = pos - direction*stack.pop();
			swap(pos, next);
			pos = next;
		}
		--i;
	}
	print(swaps.length);
	if (swaps.length != 0) {
		print(swaps.join('\n'));
	}
}

main();

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 n = parseInt(readline()),
		isComposite = new Array(n+1),
		primes = [],
		prime = 1;
	isComposite[1] = true;
	while (true) {
		++prime;
		while (prime <= n && isComposite[prime]) {
			++prime;
		}
		if (prime > n) {
			break;
		}
		primes.push(prime);
		for (var seek = 2*prime; seek <= n; seek += prime) {
			isComposite[seek] = true;
		}
	}
	function primeFloor(target) {
		var low = 0, high = primes.length-1;
		while (low != high) {
			var mid = Math.floor((low+high)/2);
			if (primes[mid] == target) {
				return primes[mid];
			}
			if (primes[mid] > target) {
				high = mid-1;
			} else {
				if (primes[mid+1] > target) {
					return primes[mid];
				}
				low = mid+1;
			}
		}
		return primes[low];
	}
	var arr = tokenizeIntegers(readline()),
		swaps = [], stack = [];
	arr.unshift(null);
	function swap(i, j) {
		var temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
		swaps.push(i+' '+j);
	}
	for (var i = 1; i < arr.length; ++i) {
		if (arr[i] == i) {
			continue;
		}
		var distance = arr[i] - i,
			direction = distance / Math.abs(distance),
			pos = i;
		distance *= direction;
		while (distance != 0) {
			stack.push(primeFloor(distance+1) - 1);
			var jump = stack[stack.length-1],
				next = pos + direction*jump;
			swap(pos, next);
			pos = next;
			distance -= jump;
		}
		pos -= direction*stack.pop();
		while (stack.length != 0) {
			next = pos - direction*stack.pop();
			swap(pos, next);
			pos = next;
		}
		--i;
	}
	print(swaps.length);
	if (swaps.length != 0) {
		print(swaps.join('\n'));
	}
}

main();


Polycarp has $$$n$$$ friends, the $$$i$$$-th of his friends has $$$a_i$$$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $$$a_i$$$ to be the same. To solve this, Polycarp performs the following set of actions exactly once:   Polycarp chooses $$$k$$$ ($$$0 \le k \le n$$$) arbitrary friends (let's say he chooses friends with indices $$$i_1, i_2, \ldots, i_k$$$);  Polycarp distributes their $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies among all $$$n$$$ friends. During distribution for each of $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies he chooses new owner. That can be any of $$$n$$$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number $$$k$$$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $$$k$$$.For example, if $$$n=4$$$ and $$$a=[4, 5, 2, 5]$$$, then Polycarp could make the following distribution of the candies:   Polycarp chooses $$$k=2$$$ friends with indices $$$i=[2, 4]$$$ and distributes $$$a_2 + a_4 = 10$$$ candies to make $$$a=[4, 4, 4, 4]$$$ (two candies go to person $$$3$$$). Note that in this example Polycarp cannot choose $$$k=1$$$ friend so that he can redistribute candies so that in the end all $$$a_i$$$ are equal.For the data $$$n$$$ and $$$a$$$, determine the minimum value $$$k$$$. With this value $$$k$$$, Polycarp should be able to select $$$k$$$ friends and redistribute their candies so that everyone will end up with the same number of candies.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output:    the minimum value of $$$k$$$, such that Polycarp can choose exactly $$$k$$$ friends so that he can redistribute the candies in the desired way;  "-1" if no such value $$$k$$$ exists.

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
	var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var k = lines[i].split(' ').map(Number);
            var sum = 0;
            for(j = 0; j < n; j++){
                sum+=k[j];
            }
            if(sum % n === 0){
                var avg = sum / n;
                var a = 0;
                for(j = 0; j < n; j++){
                    if(k[j] > avg){
                        a++;
                    }
                }
                console.log(a);
            }else{
                console.log(-1);
            }
        }
    }
});

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    let t = parseInt(readLine());
    while (t-- > 0) {
        console.log(solve());
    }
}
function solve() {
    let n = parseInt(readLine());
    let arr = readLine().split(" ");
    let sum = arr.reduce((acc, cur) => acc + parseInt(cur), 0);
    if (sum % n != 0) {
        return -1;
    }
    let avg = sum / n;
    let presentAvgCount = arr.reduce((acc, cur) => {
        if (parseInt(cur) > avg){
            return acc+1;
        }
        return acc;
    }, 0);
    return presentAvgCount;
}

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let input = '';
process.stdin.on('data', inputStdin => {
    input += inputStdin;
});
process.stdin.on('end', _ => {
    main(input);
});

function main(input) {
    var args = input.split("\n");
    const t = parseInt(args[0], 10);
    for (var i = 1; i <= t; i++) {
        var n = parseInt(args[2 * i - 1], 10);
        var arg = (args[2 * i].split(" ")).map((e) => parseInt(e, 10));
        var s = arg.reduce(function (sum, element) {
            return sum + element;
        }, 0);
        var d = s % n;
        if (d != 0) {
            console.log("-1");
        }
        else {
            var c = Math.floor(s / n);
            var cnt = 0;
            for (var j = 0; j < n; j++) {
                if (arg[j] > c) {
                    cnt++;
                }
            }
            console.log(cnt);
        }
    }
}

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

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

function main() {
  let t = parseInt(readLine()); // number of test cases

  while (t--) {
    let n = parseInt(readLine()); // number of friends

    let a = readLine()
      .split(" ")
      .map((x) => parseInt(x)); // array of candies

    console.log(getMinK(a, n));
  }
}

function getMinK(a, n) {
  let candiesSum = 0;

  for (let i = 0; i < n; i++) {
    candiesSum += a[i];
  }

  let equalNumber = candiesSum / n;

  if (candiesSum % n !== 0) {
    return -1;
  }

  let k = 0;

  for (let j = 0; j < a.length; j++) {
    if (a[j] > equalNumber) {
      k++;
    }
  }

  return k;
}

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

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

function main(input) {
    input = input.split("\n");
    let z = 0;
    let testCases = +input[z++];

    while(testCases--){
        let arrLen = +input[z++];
        let arr = input[z++].split(' ').map(x=>Number(x));

        let sum = arr.reduce((a,b)=>a+b);
        let modular = sum % arrLen;

        if(modular !== 0) console.log(-1);
        else{
            let counter = 0;
            arr.forEach(value => {
                if(value > sum / arrLen) counter++;
            });
            console.log(counter);
        }
    }
}

let data = '';
process.stdin.on('data', c => data += c);

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i < t; i++){
		let n = nl.num();
		let a = nl.nums();
		let s = a.reduce((a, b) => a + b);
		let x = 0;
		let y = 0;
		if (n == 1) {
			ans.push(0);
		} else if(s % n !== 0) {
			ans.push(-1);
		} else {
			let c = s / n;
			a.forEach(e => {
				if (e === c) {
					x++;
				}
				if (e > c) {
					y++;
				}
			});
			if (x === n) {
				ans.push(0);
			} else {
				ans.push(y);
			}
		}
	}
	console.log(ans.join('\n'));
};

process.stdin.on('end', sol);

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 t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        l++
        console.log(solve(lines[l++].split(' ').map(Number)));
    }
});

const solve = (arr) => {
    try{
        const arr_sum = arr.reduce((acc, curr) => acc + curr, 0);

        if(arr_sum % arr.length !== 0){
            return -1;
        }

        let cnt = 0;

        for(let i of arr){
            if(i > arr_sum / arr.length){
                cnt += 1;
            }
        }

        return cnt;
    }catch (ex) {
        console.log('ex:', ex)
    }
};

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

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

function div(a, b) {
   return Math.floor(a / b);
}

function solve() {
   var n = Number(read());
   var sum = 0;
   var arr = readArray((a) => {
      var numA = Number(a);
      sum += numA;
      return numA;
   });
   if (sum % n !== 0) {
      write(-1);
      return;
   }
   var ans = 0;
   var avg = div(sum, n);
   for (var i = 0; i < arr.length; i++) {
      if (arr[i] > avg) {
         ans++;
      }
   }
   write(ans);
}

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

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

let lineContent = ''

process.stdin.on('data', c => lineContent += c)
process.stdin.on('end', () => {
    const { EOL } = require('os')
    const lines = lineContent.split(EOL) /*your input text, split by lines*/

    const testNumbers = parseInt(lines[0]);

    for (let i = 0; i < testNumbers; i++) {
        const [n] = lines[1 + i * 2].split(" ").map((e) => parseInt(e));
        const arr = lines[2 + i * 2].split(" ").map(e => parseInt(e));

        console.log(f(n, arr));
    }

})

const f = (n, arr) => {
    const sum = arr.reduce((c, e) => c += e);
    if (sum % n !== 0) return -1;

    const candy = sum / n;

    let res = 0;

    for (let i = 0; i < n; i++) {
        if (arr[i] > candy) {
            res++;
        }
    }

    return res;
}

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 t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        l++
        console.log(solve(lines[l++].split(' ').map(Number)));
    }
});

function solve(nums) {
    let sum = 0
    for (let i = 0; i < nums.length; i++) {
        sum += nums[i]
    }
    const avg = sum / nums.length
    if (avg !== Math.ceil(avg)) return -1

    let k = 0
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] > avg) {
            k++
        }
    }
    return k
}

//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];
		}
		if(sum % N != 0){
			myout(-1);
			continue;
		}
		var output = 0;
		for(var i = 0; i < N; i++){
			if(list[i] > (sum / N)){
				output++;
			}
		}
		myout(output);
	}
}

var t = parseInt(readline());

for(i = 0; i < t; i++) {
    var n = parseInt(readline());
    var a = readline().split(" ");
    var sum = 0;
    for(j = 0; j < n; j++) sum += parseInt(a[j]);
    if(sum % n !== 0) print(-1);
    else {
        var count = 0, over = 0, div = sum / n;
        for(j = 0; j < n; j++) {
            //if(parseInt(a[j]) === div) count += 1;
            //else
            if(parseInt(a[j]) > div) over += 1;
        }
        /*if(n !== count) {
            //if(n - count - 1 >= Math.ceil(n/2)) {
            //    print(Math.ceil)
            //}
            //else print(n - count - 1);
            print(n - count - 1);
        }*/
        if(over > 0) {print(over);}
        else print(0);
    }
}

var tc=readline();
while(tc--)
{
   var n=readline();
   var arr=readline().split(' ');
   arr.sort(function(u,v){return u-v;});
   var sum=0;
   for(var i=0;i<arr.length;i++) sum+=Number(arr[i]);
    if(sum%arr.length>0) print(-1);
   else
{     var sz=arr.length;
       var u=sum/sz;
       var cnt=0;
for(var i=0;i<sz;i++) cnt+=(Number(arr[i])>u);
    print(cnt);
}

}

// B. Friends and Candies

var l0 = readline();
var n = +l0;
var arr = [];
for (var a = 0; a<n; a++) {
    var ignore = readline();
    arr.push(readline().split(' ').map(v => +v));
}

// output
// 2
// 1
// -1
// 0
// 0

for (var x = 0; x<arr.length; x++) {
    var sum = 0;
    for (y = 0; y<arr[x].length;y++) {
        sum = sum + arr[x][y];
    }

    if (sum%arr[x].length !== 0) {
        print(-1);
    } else {
        var eq = sum/arr[x].length;
        var count = 0;
        for (var z = 0; z<arr[x].length;z++) {
            if (arr[x][z] > eq) {
                count++;
            }
        }
        if (count) {
            print(count);
        } else {
            print(0);
        }
    }
}

var numberOfCases = Number(readline());
for (var i = 0; i < numberOfCases; ++i) {
    processCase();
}

function processCase() {
    var numsCount = Number(readline());
    var nums = readline().split(" ").map(x => Number(x));

    if (numsCount === 1) {
        return print("0");
    }

    var sum = 0;
    for (var i = 0; i < nums.length; ++i) {
        sum += nums[i];
    }

    var avg = sum / nums.length;
    if (avg !== Math.trunc(avg)) {
        return print("-1");
    }

    print(nums.reduce((acc, elem) => {
        if (elem > avg) {
            ++acc;
        }

        return acc;
    }, 0));
}

var tc = parseInt(readline());

while(tc--) {
    var n = parseInt(readline());
    var arr = readline().split(' ').map(i => parseInt(i));

    var sum = arr.reduce((a, b) => {
        return a + b;
    });

    if (sum % n) {
        print ("-1");
    } else  {
        var newArray = arr.filter(e => {
            return e > (sum/n);
        });
        print(newArray.length);
    }
}

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var x = +readline();
    var nums = readNumArray();
    var sum = 0;
    for (var j = 0; j < x; j++) {
      sum+= nums[j];
    }
    var average = sum / x;
    if (average % 1 > 0) {
      print(-1);
      continue;
    }
    var counter = 0;
    for (var j = 0; j < x; j++) {
      if (nums[j] > average) {
        counter++;
      }
    }
    print(counter);
  }
}

main();

var t = parseInt(readline());

for(i = 0; i < t; i++) {
    var n = parseInt(readline());
    var a = readline().split(" ");
    var sum = 0;
    for(j = 0; j < n; j++) sum += parseInt(a[j]);
    if(sum % n !== 0) print(-1);
    else {
        var count = 0, div = sum / n;
        for(j = 0; j < n; j++) {
            if(parseInt(a[j]) === div) count += 1;
        }
        if(n - count !== 0) print(n - count - 1);
        else print(0);
    }
}

var t = parseInt(readline());

for(i = 0; i < t; i++) {
    var n = parseInt(readline());
    var a = readline().split(" ");
    var sum = a.reduce(function(x, y){
        return parseInt(x) + parseInt(y);
    }, 0);
    if(sum % n !== 0) print(-1);
    else {
        var count = 0, div = sum / n;
        for(j = 0; j < n; j++) {
            if(a[j] == div) count += 1;
        }
        if(n - count !== 0) print(n - count - 1);
        else print(0);
    }
}


Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.Their algorithm will be tested on an array of integers, where the $$$i$$$-th integer represents the color of the $$$i$$$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $$$k$$$, and each color should belong to exactly one group.Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $$$k$$$ to the right.   To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.

The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq k \leq 256$$$), the number of pixels in the image, and the maximum size of a group, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$0 \leq p_i \leq 255$$$), where $$$p_i$$$ is the color of the $$$i$$$-th pixel.

Print $$$n$$$ space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter.

NoteOne possible way to group colors and assign keys for the first sample:Color $$$2$$$ belongs to the group $$$[0,2]$$$, with group key $$$0$$$.Color $$$14$$$ belongs to the group $$$[12,14]$$$, with group key $$$12$$$.Colors $$$3$$$ and $$$4$$$ belong to group $$$[3, 5]$$$, with group key $$$3$$$.Other groups won't affect the result so they are not listed here.


The only difference between easy and hard versions is constraints.If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.A session has begun at Beland State University. Many students are taking exams.Polygraph Poligrafovich is going to examine a group of $$$n$$$ students. Students will take the exam one-by-one in order from $$$1$$$-th to $$$n$$$-th. Rules of the exam are following:  The $$$i$$$-th student randomly chooses a ticket.  if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.  if the student finds the ticket easy, he spends exactly $$$t_i$$$ minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.The duration of the whole exam for all students is $$$M$$$ minutes ($$$\max t_i \le M$$$), so students at the end of the list have a greater possibility to run out of time to pass the exam.For each student $$$i$$$, you should count the minimum possible number of students who need to fail the exam so the $$$i$$$-th student has enough time to pass the exam.For each student $$$i$$$, find the answer independently. That is, if when finding the answer for the student $$$i_1$$$ some student $$$j$$$ should leave, then while finding the answer for $$$i_2$$$ ($$$i_2>i_1$$$) the student $$$j$$$ student does not have to go home.

The first line of the input contains two integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le M \le 2 \cdot 10^7$$$) — the number of students and the total duration of the exam in minutes, respectively. The second line of the input contains $$$n$$$ integers $$$t_i$$$ ($$$1 \le t_i \le 100$$$) — time in minutes that $$$i$$$-th student spends to answer to a ticket. It's guaranteed that all values of $$$t_i$$$ are not greater than $$$M$$$.

Print $$$n$$$ numbers: the $$$i$$$-th number must be equal to the minimum number of students who have to leave the exam in order to $$$i$$$-th student has enough time to pass the exam.

NoteThe explanation for the example 1.Please note that the sum of the first five exam times does not exceed $$$M=15$$$ (the sum is $$$1+2+3+4+5=15$$$). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are $$$0$$$.In order for the $$$6$$$-th student to pass the exam, it is necessary that at least $$$2$$$ students must fail it before (for example, the $$$3$$$-rd and $$$4$$$-th, then the $$$6$$$-th will finish its exam in $$$1+2+5+6=14$$$ minutes, which does not exceed $$$M$$$).In order for the $$$7$$$-th student to pass the exam, it is necessary that at least $$$3$$$ students must fail it before (for example, the $$$2$$$-nd, $$$5$$$-th and $$$6$$$-th, then the $$$7$$$-th will finish its exam in $$$1+3+4+7=15$$$ minutes, which does not exceed $$$M$$$).

process.stdin.setEncoding("ascii");

let input = "";
const countingSortTable = Array(101).fill(0);

process.stdin.on("data", data => { input += data; });
process.stdin.on("end", () => {
    const [[n, m], T] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const sum = [0, ...T];
    for (let i = 1; i < sum.length; i++)
        sum[i] += sum[i - 1];
    sum.shift();
    process.stdout.write("0 ");
    for (let i = 1; i < sum.length; i++) {
        let currentSum = sum[i];
        let count = 0;
        countingSortTable[T[i - 1]]++;
        for (let j = 100; j >= 1; j--) {
            if (countingSortTable[j] === 0) continue;
            const repc = countingSortTable[j];
            if (currentSum - repc * j > m) {
                currentSum -= repc * j;
                count += repc;
                continue;
            }
            if (currentSum < m) {
                break;
            }
            count += Math.ceil((currentSum - m) / j);
            break;
        }
        process.stdout.write(count + " ");
    }
});


Allen wants to enter a fan zone that occupies a round square and has $$$n$$$ entrances.There already is a queue of $$$a_i$$$ people in front of the $$$i$$$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.Allen uses the following strategy to enter the fan zone:   Initially he stands in the end of the queue in front of the first entrance.  Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance). Determine the entrance through which Allen will finally enter the fan zone.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of entrances. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the number of people in queues. These numbers do not include Allen.

Print a single integer — the number of entrance that Allen will use.

NoteIn the first example the number of people (not including Allen) changes as follows: $$$[\textbf{2}, 3, 2, 0] \to [1, \textbf{2}, 1, 0] \to [0, 1, \textbf{0}, 0]$$$. The number in bold is the queue Alles stands in. We see that he will enter the fan zone through the third entrance.In the second example the number of people (not including Allen) changes as follows: $$$[\textbf{10}, 10] \to [9, \textbf{9}] \to [\textbf{8}, 8] \to [7, \textbf{7}] \to [\textbf{6}, 6] \to \\ [5, \textbf{5}] \to [\textbf{4}, 4] \to [3, \textbf{3}] \to [\textbf{2}, 2] \to [1, \textbf{1}] \to [\textbf{0}, 0]$$$.In the third example the number of people (not including Allen) changes as follows: $$$[\textbf{5}, 2, 6, 5, 7, 4] \to [4, \textbf{1}, 5, 4, 6, 3] \to [3, 0, \textbf{4}, 3, 5, 2] \to \\ [2, 0, 3, \textbf{2}, 4, 1] \to [1, 0, 2, 1, \textbf{3}, 0] \to [0, 0, 1, 0, 2, \textbf{0}]$$$.

var n = readline(); // Number of queues
var ak = readline()
    .split(' ')
    .map(Number); // People in each queue

var bk = ak.map((ai, i) => {
    return i + Math.ceil((ai - i) / n) * n;
});

var minBk = bk[0];
var posAllen = 1;
for(var i = 1; i < n; i++) {
    if(bk[i] < minBk) {
        minBk = bk[i];
        posAllen = (i+1);
    }
}

print(posAllen);

  var n = parseInt(readline());
  var a = readline().split(' ').map(x => parseInt(x));
  var minp = Infinity;
  var minq = Infinity;
  for(var i = 0; i < n; i += 1) {
    var r = 0;
    if(a[i] > i) {
      r += Math.ceil((a[i] - i) / n) * n;
      r += i;
    } else {
      r += i;
    }
    if(r < minq) {
      minq = r;
      minp = i;
    }
  }
  print(minp + 1);

var numQueues = readline();
var queues = readline()
    .split(' ')
    .map(Number);
var queueAllen = 0;

var minQueue = queues.reduce((a,b) => b < a ? b : a);
if(minQueue > numQueues)
queues = queues.map(q => q % numQueues);

while (queues[queueAllen] > 0) {
    queues = queues.map(q => q - 1);
    queueAllen = (queueAllen + 1) % numQueues;
}

print(queueAllen + 1);


You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of queries. Each of the next $$$T$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 998244353$$$) — inclusive borders of the range. It is guaranteed that testset only includes queries, which have at least one suitable pair.

Print $$$T$$$ lines, each line should contain the answer — two integers $$$x$$$ and $$$y$$$ such that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$. The answer in the $$$i$$$-th line should correspond to the $$$i$$$-th query from the input. If there are multiple answers, print any of them.

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

  let tmp=0, T=0, pairs=[];

  rl.on('line', (input) => {
      if (tmp==0) {T=Number(input); tmp++;}
      else {
          if (tmp<=T){
          let str=input.split(' ').map(a=>{return Number(a);});
            pairs.push(str);
            tmp++;}
          }
    if (tmp>T){ rl.close(); therest();}
    return 0;}
);

let therest=function() {
    for (let i=0; i<T; i++) {
        let l=pairs[i][0], r=pairs[i][1];
        console.log(l, 2*l);

    }
//console.log(T, pairs)
}
//console.log(lngth, str);}

  /*
  rl.question('What do you think of Node.js? ', (answer) => {
    // TODO: Log the answer in a database
    console.log(`Thank you for your valuable feedback: ${answer}`);

    rl.close();
  });*/

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

let l = 0;
let n = 0

rl.on('line', (input) => {
    if (l === 0) {
        n = parseInt(input)
    } else {
        if (l === n)
            rl.close();

        let arr = input.split(" ").map(x => parseInt(x))
        console.log(arr[0], arr[0] * 2)

        if (l === n)
            return
    }
    l++
});

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

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var tmp = nextIntArray();
    var L = tmp[0];
    var R = tmp[1];
    output[i] = L + " " + (L * 2);
  }
  myout(myconv(output, 9));
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  let [a, b] = d.split(' ').map(Number);
  console.log(a, 2*a);

  c++;
});

//var input = readline()

var t = readline()

for(var i=0; i<t; i++) {
    var arr = readline().split(' ')
    var a = arr[0]
    var b = arr[1]

    print(a +' '+ 2*a)
}

//var input = readline()

var t = readline()

for(var i=0; i<t; i++) {
    var arr = readline().split(' ')
    var a = arr[0]
    var b = arr[1]

    print(a +' '+ a*a)
}


A and B are preparing themselves for programming contests.The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.

The first line contains integer n (1 ≤ n ≤ 105) — the number of rooms in the University. The next n - 1 lines describe the corridors. The i-th of these lines (1 ≤ i ≤ n - 1) contains two integers ai and bi (1 ≤ ai, bi ≤ n), showing that the i-th corridor connects rooms ai and bi. The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Next m lines describe the queries. The j-th of these lines (1 ≤ j ≤ m) contains two integers xj and yj (1 ≤ xj, yj ≤ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj.

In the i-th (1 ≤ i ≤ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.

Notein the first sample there is only one room at the same distance from rooms number 2 and 3 — room number 1.

var n;
var e=[],parent=[];
var weight=[],depp=[],st=[],pq=[];

function jump(u,k) {
	for(var i=18;  i>=0;  i--) if (k>=(1 << i)) {
		k-=1 << i;
		u=parent[u][i];
	}
	return Number(u);
}

function lca(u,v) {
	if (depp[u]>depp[v]) u=jump(u,depp[u]-depp[v]);
	if (depp[v]>depp[u]) v=jump(v,depp[v]-depp[u]);
	if (u==v) return u;
	for(var i=18;  i>=0;  i--) if (parent[u][i]!=parent[v][i]) {
		u=parent[u][i];  v=parent[v][i];
	}
	return parent[u][0];
}

function setlink(u,v) {
	e[u].push(v);
}

function Input() {
	var line=readline().split(' ');
	var u,v;
	n=Number(line[0]);
	for(var i=1;  i<=n;  i++) e[i]=new Array();
	for(var i=1;  i<=n-1;  i++) {
		var line=readline().split(' ');
		u=Number(line[0]);  v=Number(line[1]);
		setlink(u,v);  setlink(v,u);
		//print('////////////',u,' ',v);
	}
}

function Dfs() {
	var v,u;
	st.push(1);
	while (st.length>0) {
		u=st[st.length-1];  st.pop();  weight[u]=1;  pq.push(u);
		if (u!=1) {
			for(var i=1;  i<=18;  i++) if (parent[parent[u][i-1]][i-1]==0) break;
			else parent[u][i]=parent[parent[u][i-1]][i-1];
		}
		for(var i=0;  i<=e[u].length-1;  i++) {
			v=e[u][i];
			if (depp[v]==0) {
				depp[v]=depp[u]+1;  parent[v][0]=u;
				st.push(v);
			}
		}
	}
	for(var i=pq.length-1;  i>=0;  i--) {
		u=pq[i];
		for(var j=0;  j<=e[u].length-1;  j++) {
			v=e[u][j];  if (parent[v][0]==u) weight[u]+=weight[v];
		}
	}
}

function main() {
	Input();
	for(var i=0;  i<=n;  i++) parent[i]=new Array();
	for(var i=0;  i<=n;  i++) for(var j=0;  j<=18;  j++) parent[i][j]=0;
	for(var i=1;  i<=n;  i++) depp[i]=0;
	for(var i=1;  i<=n;  i++) weight[i]=0;
	depp[1]=1;
	Dfs();
	var line=readline().split(' '),u,v;
	m=line[0];
	for(var i=1;  i<=m;  i++) {
		var line=readline().split(' ');
		u=Number(line[0]);  v=Number(line[1]);
		//print(u,' ',v);
		var dis=depp[u]+depp[v]-2*depp[lca(u,v)];
		if (depp[u]==depp[v]) {
			if (u==v) print(n);
			else print(n-weight[jump(u,dis/2-1)]-weight[jump(v,dis/2-1)]);
		}
		else {
			if (dis%2) print(0);
			else if (dis==0) print(n);
			else {
				dis/=2;
				if (depp[u]<depp[v]) u=v;
				p=jump(u,dis);  pp=jump(u,dis-1);
				print(weight[p]-weight[pp]);
			}
		}
	}
	return 0;
}

main();

var n;
var e=[],parent=[];
var weight=[],depp=[];

function jump(u,k) {
	for(var i=18;  i>=0;  i--) if (k>=(1 << i)) {
		k-=1 << i;
		u=parent[u][i];
	}
	return u;
}

function lca(u,v) {
	if (depp[u]>depp[v]) u=jump(u,depp[u]-depp[v]);
	if (depp[v]>depp[u]) v=jump(v,depp[v]-depp[u]);
	if (u==v) return u;
	for(var i=18;  i>=0;  i--) if (parent[u][i]!=parent[v][i]) {
		u=parent[u][i];  v=parent[v][i];
	}
	return parent[u][0];
}

function setlink(u,v) {
	e[u].push(v);
}

function Input() {
	var line=readline().split(' ');
	var u,v;
	n=Number(line[0]);
	for(var i=1;  i<=n;  i++) e[i]=new Array();
	for(var i=1;  i<=n-1;  i++) {
		var line=readline().split(' ');
		u=line[0];  v=line[1];
		setlink(u,v);  setlink(v,u);
		//print('////////////',u,' ',v);
	}
}

function Dfs(u) {
	var v;
	weight[u]=1;
	if (u!=1) {
		for(var i=1;  i<=18;  i++) if (parent[parent[u][i-1]][i-1]==0) break;
		else parent[u][i]=parent[parent[u][i-1]][i-1];
	}
	for(var i=0;  i<=e[u].length-1;  i++) {
		v=e[u][i];
		if (depp[v]==0) {
			depp[v]=depp[u]+1;  parent[v][0]=u;
			Dfs(v);
			weight[u]+=weight[v];
		}
	}
}

function main() {
	Input();
	for(var i=1;  i<=n;  i++) parent[i]=new Array();
	for(var i=1;  i<=n;  i++) for(var j=0;  j<=18;  j++) parent[i][j]=0;
	for(var i=1;  i<=n;  i++) depp[i]=0;
	for(var i=1;  i<=n;  i++) weight[i]=0;
	depp[1]=1;
	Dfs(1);
	var line=readline().split(' '),u,v;
	m=line[0];
	for(var i=1;  i<=m;  i++) {
		var line=readline().split(' ');
		u=line[0];  v=line[1];
		if (depp[u]==depp[v]) print(n-weight[lca(u,v)]+1);
		else {
			var dis=depp[u]+depp[v]-2*depp[lca(u,v)];
			if (dis%2) print(0);
			else if (dis==0) print(1);
			else {
				dis/=2;
				if (depp[u]<depp[v]) u=v;
				p=jump(u,dis);  pp=jump(u,dis-1);
				print(weight[p]-weight[pp]);
			}
		}
	}
	return 0;
}

main();

var n;
var e=[],parent=[];
var weight=[],depp=[];

function jump(u,k) {
	for(var i=18;  i>=0;  i--) if (k>=(1 << i)) {
		k-=1 << i;
		u=parent[u][i];
	}
	return u;
}

function lca(u,v) {
	if (depp[u]>depp[v]) u=jump(u,depp[u]-depp[v]);
	if (depp[v]>depp[u]) v=jump(v,depp[v]-depp[u]);
	if (u==v) return u;
	for(var i=18;  i>=0;  i--) if (parent[u][i]!=parent[v][i]) {
		u=parent[u][i];  v=parent[v][i];
	}
	return parent[u][0];
}

function setlink(u,v) {
	e[u].push(v);
}

function Input() {
	var line=readline().split(' ');
	var u,v;
	n=Number(line[0]);
	for(var i=1;  i<=n;  i++) e[i]=new Array();
	for(var i=1;  i<=n-1;  i++) {
		var line=readline().split(' ');
		u=line[0];  v=line[1];
		setlink(u,v);  setlink(v,u);
		//print('////////////',u,' ',v);
	}
}

function Dfs(u) {
	var v;
	weight[u]=1;
	if (u!=1) {
		for(var i=1;  i<=18;  i++) if (parent[parent[u][i-1]][i-1]==0) break;
		else parent[u][i]=parent[parent[u][i-1]][i-1];
	}
	for(var i=0;  i<=e[u].length-1;  i++) {
		v=e[u][i];
		if (depp[v]==0) {
			depp[v]=depp[u]+1;  parent[v][0]=u;
			Dfs(v);
			weight[u]+=weight[v];
		}
	}
}

function main() {
	Input();
	for(var i=1;  i<=n;  i++) parent[i]=new Array();
	for(var i=1;  i<=n;  i++) for(var j=0;  j<=18;  j++) parent[i][j]=0;
	for(var i=1;  i<=n;  i++) depp[i]=0;
	for(var i=1;  i<=n;  i++) weight[i]=0;
	depp[1]=1;
	Dfs(1);
	var line=readline().split(' '),u,v;
	m=line[0];
	for(var i=1;  i<=m;  i++) {
		var line=readline().split(' ');
		u=line[0];  v=line[1];
		if (depp[u]==depp[v]) print(n-weight[lca(u,v)]+1);
		else {
			var dis=depp[u]+depp[v]-2*depp[lca(u,v)];
			if (dis%2) print(0);
			else if (dis==0) print(n);
			else {
				dis/=2;
				if (depp[u]<depp[v]) u=v;
				p=jump(u,dis);  pp=jump(u,dis-1);
				print(weight[p]-weight[pp]);
			}
		}
	}
	return 0;
}

main();


One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.

The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).

In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.

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 data = tokenizeIntegers(readline()),
		n = data[0], k = data[1],
		m = n*k;
	if (m > n*(n-1)/2) {
		print(-1);
		return;
	}
	var parts = [m];
	for (var i = 0; i < n; ++i) {
		for (var d = 1; d <= k; ++d) {
			var a = i + 1, b = (i+d)%n + 1;
			parts.push(a+' '+b);
		}
	}
	print(parts.join('\n'));
}

main();

process.stdin.setEncoding("utf8");
let input = "";
process.stdin.on("data", x => input += x);
process.stdin.on("end", () => {
    const [n, k] = input.split(" ").map(Number);
    if (n * k > n * (n - 1) / 2) {
        process.stdout.write("-1\n");
        return;
    }
    let accumulated = "";
    accumulated += String(n * k) + "\n";
    for (let i = 0; i < n; i++)
        for (let j = 1; j <= k; j++)
            accumulated += (String(i + 1) + " " + String((i + j) % n + 1) + "\n");
    process.stdout.write(accumulated);
});

process.stdin.setEncoding("utf8");
let input = "";
process.stdin.on("data", x => input += x);
process.stdin.on("end", () => {
    const [n, k] = input.split(" ").map(Number);
    if (n * k > n * (n - 1) / 2) {
        process.stdout.write("-1\n");
        return;
    }
    process.stdout.write(String(n * k) + "\n");
    for (let i = 0; i < n; i++)
        for (let j = 0; j < k; j++)
            process.stdout.write(String(i + 1) + " " + String((i + j) % n + 1) + "\n");
});


You have a long stick, consisting of $$$m$$$ segments enumerated from $$$1$$$ to $$$m$$$. Each segment is $$$1$$$ centimeter long. Sadly, some segments are broken and need to be repaired.You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length $$$t$$$ placed at some position $$$s$$$ will cover segments $$$s, s+1, \ldots, s+t-1$$$.You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.Time is money, so you want to cut at most $$$k$$$ continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$n \le m \le 10^9$$$, $$$1 \le k \le n$$$) — the number of broken segments, the length of the stick and the maximum number of pieces you can use. The second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le m$$$) — the positions of the broken segments. These integers are given in increasing order, that is, $$$b_1 < b_2 < \ldots < b_n$$$.

Print the minimum total length of the pieces.

NoteIn the first example, you can use a piece of length $$$11$$$ to cover the broken segments $$$20$$$ and $$$30$$$, and another piece of length $$$6$$$ to cover $$$75$$$ and $$$80$$$, for a total length of $$$17$$$.In the second example, you can use a piece of length $$$4$$$ to cover broken segments $$$1$$$, $$$2$$$ and $$$4$$$, and two pieces of length $$$1$$$ to cover broken segments $$$60$$$ and $$$87$$$.

 const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));

diffArr.pop();
diffArr.sort((eleA, eleB) => eleA - eleB);

const diffArrSM = diffArr.slice(0, n - k);
const ans = diffArrSM.reduce((ac, c) => ac + c, 0) + k;

console.log(ans);

(function() {
    var read = {
        number: function() {
            return +readline();
        },
        arr: function(divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function(divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var n = read.arrNumber(' ');
    var m = n[1];
    var k = n[2];
    var n = n[0];

    var b = read.arrNumber(' ');

    var arr = [];
    for(var i = 1; i < n; i++) {
        arr.push(b[i] - b[i-1]);
    }

    arr = arr.sort((a, b) => a - b);
    var t = n - k;

    var sum = 0;
    for(var i = 0; i < t; i++) {
        sum += arr[i] - 1;
    }

    print(n + sum);
}());

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));
const diffArrSM = diffArr.sort((eleA, eleB) => eleA - eleB).slice(0, n - k);
const ans = diffArrSM.reduce((ac, c) => ac + c, 0) + k;

console.log(ans);

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));

diffArr.pop();
diffArr.sort((eleA, eleB) => parseInt(eleA) > parseInt(eleB));

let ans = k;
for (let i = 0; i < n - k; i++) {
    ans += diffArr[i];
}

console.log(ans);

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));

diffArr.pop();
diffArr.sort((eleA, eleB) => Number(eleA) > Number(eleB));

const diffArrSM = diffArr.slice(0, n - k);
const ans = diffArrSM.reduce((ac, c) => ac + c, 0) + k;

console.log(ans);

// Test

 const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));

diffArr.pop();
diffArr.sort((eleA, eleB) => Number(eleA) > Number(eleB));

const diffArrSM = diffArr.slice(0, n - k);
const ans = diffArrSM.reduce((ac, c) => ac + c, 0) + k;

if (n > 10000) {
    console.log(diffArr[diffArr.length - 1], diffArr[diffArr.length - 2]);
}

console.log(ans);

 const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));

diffArr.pop();
diffArr.sort((eleA, eleB) => Number(eleA) > Number(eleB));

const diffArrSM = diffArr.slice(0, n - k);
const ans = diffArrSM.reduce((ac, c) => ac + c, 0) + k;

if (n > 10000) {
    console.log(diffArr[diffArr.length - 1]);
}

console.log(ans);

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => ({
    diff: arr[idx + 1] - ele,
    idx: idx,
}));

diffArr.pop();
diffArr.sort((eleA, eleB) => eleA.diff < eleB.diff);

const sepIdxList= diffArr.slice(0, k - 1).map((ele) => ele.idx);
const lastSepIdx = sepIdxList[sepIdxList.length - 1];
const lastSegFirstIdx = sepIdxList.length > 0 ? lastSepIdx + 1 : 0;
let ans = 0;

sepIdxList.forEach((sepIdx, idx) => {
   ans += arr[sepIdx] - arr[idx > 0 ? sepIdxList[idx - 1] + 1 : 0] + 1;
});
ans += arr[n - 1] - arr[lastSegFirstIdx] + 1;

console.log(ans);

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));

diffArr.pop();
diffArr.sort((eleA, eleB) => Number(eleA) > Number(eleB));

let ans = k;
for (let i = 0; i < n - k; i++) {
    ans += diffArr[i];
}

console.log(ans);

 const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));

diffArr.pop();
diffArr.sort((eleA, eleB) => parseInt(eleA) > parseInt(eleB));

const diffArrSM = diffArr.slice(0, n - k);
const ans = diffArrSM.reduce((ac, c) => ac + c, 0) + k;

if (n > 10000) {
    console.log(diffArr.slice(0, 100));
}

console.log(ans);

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));
const diffArrSM = diffArr.sort((eleA, eleB) => Number(eleA) > Number(eleB)).slice(0, n - k);
const ans = diffArrSM.reduce((ac, c) => ac + c, 0) + k;

console.log(ans);

 const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));

diffArr.pop();
diffArr.sort((eleA, eleB) => Number(eleA) > Number(eleB));

const diffArrSM = diffArr.slice(0, n - k);
const ans = diffArrSM.reduce((ac, c) => ac + c, 0) + k;

if (n > 10000) {
    console.log(arr.length);
}

console.log(ans);

 const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, m, k], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
const diffArr = arr.map((ele, idx) => (arr[idx + 1] - ele));

diffArr.pop();
diffArr.sort((eleA, eleB) => Number(eleA) > Number(eleB));

const diffArrSM = diffArr.slice(0, n - k);
const ans = diffArrSM.reduce((ac, c) => ac + c, 0) + k;

if (n > 10000) {
    console.log(diffArr.slice(0, 100));
}

console.log(ans);


This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings $$$s$$$ and $$$t$$$ of length $$$n$$$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation exactly once: he takes two positions $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$, the values $$$i$$$ and $$$j$$$ can be equal or different), and swaps the characters $$$s_i$$$ and $$$t_j$$$. Can he succeed?Note that he has to perform this operation exactly once. He has to perform this operation.

The first line contains a single integer $$$k$$$ ($$$1 \leq k \leq 10$$$), the number of test cases. For each of the test cases, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^4$$$), the length of the strings $$$s$$$ and $$$t$$$.  Each of the next two lines contains the strings $$$s$$$ and $$$t$$$, each having length exactly $$$n$$$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.

For each test case, output "Yes" if Ujan can make the two strings equal and "No" otherwise. You can print each letter in any case (upper or lower).

4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca

NoteIn the first test case, Ujan can swap characters $$$s_1$$$ and $$$t_4$$$, obtaining the word "house".In the second test case, it is not possible to make the strings equal using exactly one swap of $$$s_i$$$ and $$$t_j$$$.

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', _ => {
    solveWrap(inputString);
});

function solve(s, t){
	let repl = [];
	for (let i = 0; i < t.length; i++) {
		if(t[i]!=s[i]){
			if(repl.length<2)
				repl.push({t: t[i], s: s[i]});
			else
				return false;
		}
	}
	if(repl.length==1)
		return false;
	else if(repl.length==2){
		if(repl[0].t!=repl[1].t || repl[0].s!=repl[1].s)
			return false;
	}
	return true;
}

function solveWrap(input) {
    let inputAr = input.trim().split('\n');
	let k = inputAr.shift();
	for (let i = 0; i < k; i++) {
		inputAr.shift();
		console.log(solve(inputAr.shift().split(''), inputAr.shift().split(''))?'Yes':'No');
	}
}

'use strict'

const problem = (n, s, t) => {
    for (let i = 0; i < n; i++) {
        if (s[i] !== t[i]) {
            for(let j = i + 1; j < n; j++) {
                if (s[j] !== t[j]) {
                    if (s[i] !== s[j] || t[i] !== t[j]) return 'No';
                    for (let k = j + 1; k < n; k++) {
                        if (s[k] !== t[k]) return 'No'
                    }
                    return 'Yes';
                }
            }
            return 'No';
        }
    }
    return 'Yes';
}
let q = +readline();
while(q--) print(problem(+readline(), readline(), readline()));


You are given an array $$$a$$$ with $$$n$$$ integers. You can perform the following operation at most $$$k$$$ times:  Choose two indices $$$i$$$ and $$$j$$$, in which $$$i \,\bmod\, k = j \,\bmod\, k$$$ ($$$1 \le i < j \le n$$$).  Swap $$$a_i$$$ and $$$a_j$$$. After performing all operations, you have to select $$$k$$$ consecutive elements, and the sum of the $$$k$$$ elements becomes your score. Find the maximum score you can get.Here $$$x \bmod y$$$ denotes the remainder from dividing $$$x$$$ by $$$y$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 600$$$) — the number of test cases. Each test case consists of two lines.  The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$) — the length of the array and the number in the statement above. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$)  — the array itself.

For each test case, print the maximum score you can get, one per line.

NoteIn the first test case, we can get a score of $$$11$$$ if we select $$$a_1, a_2$$$ without performing any operations.In the third test case, we can get a score of $$$15$$$ if we first swap $$$a_1$$$ with $$$a_4$$$ and then select $$$a_3, a_4, a_5$$$.

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++];
}
// Common Template Ends //

function getResult(n, k, inputs) {
	let sums = Array(100).fill(0)
	let sum = 0

	let i = j = 0
	while(i < n)
	{
		if(j==k) j=0

		sums[j] = Math.max(inputs[i], sums[j])
		j++
		i++
	}

	for(let i=0; i<k; i++){
		sum += sums[i]
	}

	return sum
}

function main() {
    let testcases = parseInt( readline() )
    while(testcases--){
    	let inputs = readline().split(' ').map(Number)
    	let n = inputs[0]
    	let k = inputs[1]

    	inputs = readline().split(' ').map(Number)

    	let res = getResult(n, k, inputs)
    	console.log( res )
    }
}

"use strict";

const fs = require("fs");
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

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

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

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

/*
 * Complete the 'decodeString' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts 2D_INTEGER_ARRAY arr as parameter.
 */

function getTotal(arr, start, k) {
  const x = arr.slice(start, start + k);
  return x.reduce((prev, curr) => Number(prev) + Number(curr), 0);
}

function consecutive(cases) {
  // Write your code here
  // swap
  for (let i = 0; i < cases.length; i++) {
    const n = Number(cases[i].n);
    const k = Number(cases[i].k);
    const arr = cases[i].arr;
    const consecutiveArr = {};
    for (let j = 0; j < n; j++) {
      consecutiveArr[j % k] = [
        ...(consecutiveArr[j % k] || []),
        Number(arr[j]),
      ].sort((a, b) => b - a);
    }

    // sum
    let sum = 0;
    Object.keys(consecutiveArr).forEach((field) => {
      sum += consecutiveArr[field][0];
    });
    console.log(sum);
  }
}

function main() {
  const t = parseInt(readLine().trim());
  const cases = [];
  for (let i = 1; i <= t * 2; i++) {
    if (i % 2 === 1) {
      const nk = readLine().split(" ");
      cases[Math.ceil(i / 2) - 1] = {
        ...cases[Math.ceil(i / 2) - 1],
        n: nk[0],
        k: nk[1],
      };
    } else {
      const arr = readLine().split(" ");
      cases[Math.ceil(i / 2) - 1] = { ...cases[Math.ceil(i / 2) - 1], arr };
    }
  }

  consecutive(cases);
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, k = 0;
    for(i = 1; i <= t * 2; i++){
        var a = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = a[0], k = a[1];
        }else{
            var v = new Array(k);
            for(j = 0; j < k; j++){
                v[j] = 0;
            }
            for(j = 0; j < n; j++){
                v[j % k] = Math.max(v[j % k], a[j]);
            }
            var ans = 0;
            for(j = 0; j < v.length; j++){
                ans += v[j];
            }
            console.log(ans);
        }
    }
});

let buf='';

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

process.stdin.on('end', ()=>{
    let lines=buf.split('\n');
    let lc=0;
    let t=parseInt(lines[lc++]);
    while(t--) {
        let _nk=lines[lc++].split(' ');
        let n=parseInt(_nk[0]),k=parseInt(_nk[1]);
        let _=lines[lc++].split(' ');
        let a=[];
        for(let i=0;i<n;i++) {
            a.push(parseInt(_[i]));
        }
        let ans=0;
        for(let i=0;i<k;i++) {
            let cur=0;
            for(let j=i;j<n;j+=k) {
                cur=Math.max(cur,a[j]);
            }
            ans+=cur;
        }
        console.log(ans);
    }
});

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    let t = parseInt(readLine());
    for(let tt=0;tt<t;tt++)
    {
        let a = readLine().trim().split(' ').map(string => {return parseInt(string.trim());});
        let n = a[0], k = a[1];
        m = {};
        a = readLine().trim().split(' ').map(string => {return parseInt(string.trim());});
        for(let i=0;i<n;++i){
            if(m[i%k]){
                m[i%k].push(a[i]);
            }else{
                m[i%k] = [a[i]];
            }
        }
        let sum=0;
        for (const [key, value] of Object.entries(m)) {
          sum+=Math.max(...value);
        }
        console.log(sum);
    }
}

"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++];
}
const solve = () => {
     let t = parseInt(readline());
     while(t--){
             let [n,k] = readline().trim().split(" ").map(cur=>parseInt(cur));
     let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
     let sum = 0;
     for(let i=0;i<k;i++){
          let max = i;
          for(let j=i+1;j<n;j++){
               if(j%k===i%k){
                    if(arr[j]>arr[max]) max = j
               }
          }
          [arr[i],arr[max]] = [arr[max],arr[i]];
          sum+=arr[i];
     }
     console.log(sum);
     }
};
solve();

const { dir, count } = require("console");
let readline = require("readline");

let rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let input = [];
rl.on("line", function (line) {
  input.push(line);

  if (input.length === +input[0] * 2 + 1) {
    // call your function here
    solve(input);
    rl.close();
  }
});

let solve = (input) => {
  for (let testcase = 1; testcase < input.length; testcase += 2) {
    let nk = input[testcase].split(" ");
    let numbers = input[testcase + 1].split(" ");
    let arr = [];
    for (let i = 0; i < numbers.length; i++) {
      let max = 0;
      for (let j = i; j < numbers.length; j += Number(nk[1])) {
        max = Math.max(numbers[j], max);
      }
      arr.push(max);
    }

    let result = 0;

    for (let i = 0; i <= arr.length - Number(nk[1]); i++) {
      let count = 0;

      for (let j = i; j < i + Number(nk[1]); j++) {
        count += arr[j];
      }
      result = Math.max(result, count);
    }

    console.log(result);
  }
};

var readline = require('readline');
var inputString = [], currentLine = 0;
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var rl = readline.createInterface(process.stdin);
rl.on('line', line => { inputString.push(line) });
process.stdin.on('end', () => {  main()  });

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

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        // const n = +readLine();
        const n_k = readLine().split(' ').map(p => +p);
        const arr = readLine().split(' ').map(p => +p);
        let result = myFunc(n_k[0], n_k[1], arr);
        console.log(result);
    }
}

function myFunc(n, k, arr){
    let max = new Array(k).fill(0);
    let resp = BigInt(0);

    for(let i = 0; i < n; i++){
        if(arr[i] > max[i%k]) max[i%k] = arr[i];
    }

    for(let i = 0; i < max.length; i++){
        resp += BigInt(max[i])
    }

    return resp.toString();
}

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        k = rn(),
        a = new Array(n);
  for (let i = 0; i < n; i++) a[i] = rn();
  let res = 0;
  for (let i = 0; i < k; i++) {
    let ans = 0;
    for (let j = i; j < n; j += k) ans = Math.max(ans, a[j]);
    res += ans;
  }
  return res;
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < 100) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= 100) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

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++];
}
// Common Template Ends //

function getResult(n, k, inputs) {
	let res = 0
	let sums = Array(n).fill(0)
	let sum = 0

	for (let i = 0; i < k; i++)
	{
		sum += inputs[i]
	}

	for (let i = 0; i < n; i++)
	{
		let rem = inputs[i] % k
		sums[rem] += inputs[i]
		res = Math.max(res, sums[rem])
	}

	res = Math.max(res, sum)

	for (let i = k; i < n; i++)
	{
		sum = sum - inputs[i - k] + inputs[i]
		res = Math.max(res, sum)
	}

	return res
}

function main() {
    let testcases = parseInt( readline() )
    while(testcases--){
    	let inputs = readline().split(' ').map(Number)
    	let n = inputs[0]
    	let k = inputs[1]

    	inputs = readline().split(' ').map(Number)

    	let res = getResult(n, k, inputs)
    	console.log( res )
    }
}


Tenten runs a weapon shop for ninjas. Today she is willing to sell $$$n$$$ shurikens which cost $$$1$$$, $$$2$$$, ..., $$$n$$$ ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available shurikens) on the showcase, and sometimes a ninja comes in and buys a shuriken from the showcase. Since ninjas are thrifty, they always buy the cheapest shuriken from the showcase.Tenten keeps a record for all events, and she ends up with a list of the following types of records:  + means that she placed another shuriken on the showcase;  - x means that the shuriken of price $$$x$$$ was bought. Today was a lucky day, and all shurikens were bought. Now Tenten wonders if her list is consistent, and what could be a possible order of placing the shurikens on the showcase. Help her to find this out!

The first line contains the only integer $$$n$$$ ($$$1\leq n\leq 10^5$$$) standing for the number of shurikens.  The following $$$2n$$$ lines describe the events in the format described above. It's guaranteed that there are exactly $$$n$$$ events of the first type, and each price from $$$1$$$ to $$$n$$$ occurs exactly once in the events of the second type.

If the list is consistent, print "YES". Otherwise (that is, if the list is contradictory and there is no valid order of shurikens placement), print "NO". In the first case the second line must contain $$$n$$$ space-separated integers denoting the prices of shurikens in order they were placed. If there are multiple answers, print any.

NoteIn the first example Tenten first placed shurikens with prices $$$4$$$ and $$$2$$$. After this a customer came in and bought the cheapest shuriken which costed $$$2$$$. Next, Tenten added a shuriken with price $$$3$$$ on the showcase to the already placed $$$4$$$-ryo. Then a new customer bought this $$$3$$$-ryo shuriken. After this she added a $$$1$$$-ryo shuriken. Finally, the last two customers bought shurikens $$$1$$$ and $$$4$$$, respectively. Note that the order $$$[2, 4, 3, 1]$$$ is also valid.In the second example the first customer bought a shuriken before anything was placed, which is clearly impossible.In the third example Tenten put all her shurikens onto the showcase, after which a customer came in and bought a shuriken with price $$$2$$$. This is impossible since the shuriken was not the cheapest, we know that the $$$1$$$-ryo shuriken was also there.

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

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

function main() {
  let len = +readLine();
  let [i, plusCount, minusCount] = [0, 0, 0];
  const [input, stack, store, ans] = [[], [], [], []];
  while (i++ < 2 * len) {
    const line = readLine();
    if (line.length === 1) {
      sign = line;
      plusCount++;
    } else {
      [sign, num] = line.split(" ");
      store.push(+num);
      minusCount++;
    }
    input.push(sign);
  }

  if (plusCount !== minusCount) {
    console.log("NO");
    return;
  }

  for (let i = 2 * len - 1; i >= 0; i--) {
    const sign = input[i];
    if (sign === "+") {
      if (!stack.length) {
        console.log("NO");
        return;
      } else {
        const top = stack.pop();
        ans.unshift(top);
      }
    } else {
      if (store[store.length - 1] > stack[stack.length - 1]) {
        console.log("NO");
        return;
      } else {
        let n = store.pop();
        stack.push(n);
      }
    }
  }
  console.log("YES");
  console.log(ans.join(" "));
}

#!/usr/bin/env node
'use strict';

const { createInterface } = require('readline');
const rl = createInterface({
  input: process.stdin,
  crlfDelay: Infinity
});

const buf = [];
const prom = [];
let maxBuf = 0;
let maxProm = 0;
rl.on('line', (line) => {
  if (prom.length > 0) {
    maxProm = Math.max(maxProm, prom.length);
    const [resolve, reject] = prom.shift();
    resolve(line);
  } else {
    rl.pause();
    buf.push(line);
    maxBuf = Math.max(maxBuf, buf.length);
  }
});

rl.on('close', () => {
  // console.error({maxProm, maxBuf});
});

async function getLine() {
  return new Promise((resolve, reject) => {
    if (buf.length > 0) {
      const line = buf.shift();
      resolve(line);
    } else {
      prom.push([resolve, reject]);
      rl.resume();
    }
  });
}

/**
 *
 * @param {Number []} trans
 * @returns {String}
 */
function solve(trans) {
  const stack = [];
  const res = [];
  while (trans.length > 0) {
    const t = trans.pop();
    if (t === 0) {
      if (stack.length < 1) {
        return 'NO';
      }
      res.push(stack.pop());
    } else if (stack.length > 0 && stack[stack.length-1] < t) {
      return 'NO';
    } else {
      stack.push(t);
    }
  }
  res.reverse();
  return 'YES\n' + res.join(' ');
}

async function main() {
  const n = Number(await getLine());
  const trans = [];
  for (let i = 0; i < 2 * n; i++) {
    const l = (await getLine()).split(' ');
    if (l[0] === '+') {
      trans[i] = 0;
    } else {
      trans[i] = Number(l[1]);
    }
  }
  const res = solve(trans);
  console.log(res);
}

if (require.main === module) {
  main();
}


Polycarp likes arithmetic progressions. A sequence $$$[a_1, a_2, \dots, a_n]$$$ is called an arithmetic progression if for each $$$i$$$ ($$$1 \le i < n$$$) the value $$$a_{i+1} - a_i$$$ is the same. For example, the sequences $$$[42]$$$, $$$[5, 5, 5]$$$, $$$[2, 11, 20, 29]$$$ and $$$[3, 2, 1, 0]$$$ are arithmetic progressions, but $$$[1, 0, 1]$$$, $$$[1, 3, 9]$$$ and $$$[2, 3, 1]$$$ are not.It follows from the definition that any sequence of length one or two is an arithmetic progression.Polycarp found some sequence of positive integers $$$[b_1, b_2, \dots, b_n]$$$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $$$1$$$, an element can be increased by $$$1$$$, an element can be left unchanged.Determine a minimum possible number of elements in $$$b$$$ which can be changed (by exactly one), so that the sequence $$$b$$$ becomes an arithmetic progression, or report that it is impossible.It is possible that the resulting sequence contains element equals $$$0$$$.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 100\,000)$$$ — the number of elements in $$$b$$$. The second line contains a sequence $$$b_1, b_2, \dots, b_n$$$ $$$(1 \le b_i \le 10^{9})$$$.

If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).

NoteIn the first example Polycarp should increase the first number on $$$1$$$, decrease the second number on $$$1$$$, increase the third number on $$$1$$$, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to $$$[25, 20, 15, 10]$$$, which is an arithmetic progression.In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.In the third example it is impossible to make an arithmetic progression.In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like $$$[0, 3, 6, 9, 12]$$$, which is an arithmetic progression.

var n = +readline();
var b = readline().split(' ').map(Number);

var CountMin = 1000000;

for (var i=-1; i<2; i++){
	for (var j=-1; j<2; j++){

	var count = 0;
	if (i != 0) count++;
	if (j != 0) count++;
	var d = b[1] + j - b[0] - i;

		for(var k=2; k<n; k++){

			if (Math.abs(b[k] - b[0] - i - d * k) == 1) count++;
			else if (Math.abs(b[k] - b[0] - i - d * k) == 0) continue;
			else {
				count = -1;
				break;
			};
		}
	if (count >= 0 && count < CountMin) CountMin = count;
	}
}
if (CountMin == 1000000) print (-1);
else print (CountMin);


Kuro is living in a country called Uberland, consisting of $$$n$$$ towns, numbered from $$$1$$$ to $$$n$$$, and $$$n - 1$$$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $$$a$$$ and $$$b$$$. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns $$$(u, v)$$$ ($$$u \neq v$$$) and walk from $$$u$$$ using the shortest path to $$$v$$$ (note that $$$(u, v)$$$ is considered to be different from $$$(v, u)$$$).Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index $$$x$$$) and Beetopia (denoted with the index $$$y$$$). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns $$$(u, v)$$$ if on the path from $$$u$$$ to $$$v$$$, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.Kuro wants to know how many pair of city $$$(u, v)$$$ he can take as his route. Since he’s not really bright, he asked you to help him with this problem.

The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \leq n \leq 3 \cdot 10^5$$$, $$$1 \leq x, y \leq n$$$, $$$x \ne y$$$) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively. $$$n - 1$$$ lines follow, each line contains two integers $$$a$$$ and $$$b$$$ ($$$1 \leq a, b \leq n$$$, $$$a \ne b$$$), describes a road connecting two towns $$$a$$$ and $$$b$$$. It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.

A single integer resembles the number of pair of towns $$$(u, v)$$$ that Kuro can use as his walking route.

NoteOn the first example, Kuro can choose these pairs:   $$$(1, 2)$$$: his route would be $$$1 \rightarrow 2$$$,  $$$(2, 3)$$$: his route would be $$$2 \rightarrow 3$$$,  $$$(3, 2)$$$: his route would be $$$3 \rightarrow 2$$$,  $$$(2, 1)$$$: his route would be $$$2 \rightarrow 1$$$,  $$$(3, 1)$$$: his route would be $$$3 \rightarrow 2 \rightarrow 1$$$. Kuro can't choose pair $$$(1, 3)$$$ since his walking route would be $$$1 \rightarrow 2 \rightarrow 3$$$, in which Kuro visits town $$$1$$$ (Flowrisa) and then visits town $$$3$$$ (Beetopia), which is not allowed (note that pair $$$(3, 1)$$$ is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).On the second example, Kuro can choose the following pairs:   $$$(1, 2)$$$: his route would be $$$1 \rightarrow 2$$$,  $$$(2, 1)$$$: his route would be $$$2 \rightarrow 1$$$,  $$$(3, 2)$$$: his route would be $$$3 \rightarrow 1 \rightarrow 2$$$,  $$$(3, 1)$$$: his route would be $$$3 \rightarrow 1$$$.

function Tree(directed) {
  this.directed = !!directed;
  this.edges = [];
  this.initSearch();
}

Tree.prototype.addEdge = function (v1, v2, directed) {
  if (!this.edges[v1]) {
    this.edges[v1] = [];
  }
  this.edges[v1].push(v2);
  if (!directed) {
    // pass true to prevent infinite loop
    this.addEdge(v2, v1, true);
  }
}

Tree.prototype.initSearch = function () {
  this.processed = [];
  this.earlyProcessed = [];
  this.discovered = [];
  this.parents = [];
  this.time = 0;
  this.entryTime = [];
  this.exitTime = [];
  this.found = false;
}

Tree.prototype.BFS = function (root) {
  var _this = this;
  this.queue = [];
  var v1; // current vertex
  this.queue.push(root);
  this.discovered[root] = true;
  while (this.queue.length) {
    v1 = this.queue.shift();
    //processVertexEarly(v1);
    this.processed[v1] = true;
    this.edges[v1].map(function (v2) {
      if (!_this.processed[v2] || _this.directed) {
        processEdge(v1, v2);
      }
      if (!_this.discovered[v2]) {
        _this.queue.push(v2);
        _this.discovered[v2] = true;
        _this.parents[v2] = v1;
      }
    });
    //processVertexLate(v1);
  }
};

Tree.prototype.DFSNonRecursive = function (root) {
  var _this = this;
  this.stack = [];
  var v1; // current vertex
  this.stack.push(root);
  while (this.stack.length) {
    v1 = this.stack[this.stack.length - 1];
    this.discovered[v1] = true;
    if (!this.earlyProcessed[v1]) {
      //processVertexEarly(v1);
      this.time++;
      this.entryTime[v1] = this.time;
      if (v1 === this.x) {
        this.found = true;
      }
      this.earlyProcessed[v1] = true;
      // this.stack.unshift(v1);
      // this.processed[v1] = true;
      this.edges[v1].map(function (v2) {
        // if (!_this.processed[v2] || _this.directed) {
        //   processEdge(v1, v2);
        // }
        if (!_this.discovered[v2]) {
          _this.stack.push(v2);
          _this.discovered[v2] = true;
          _this.parents[v2] = v1;
        }
      });
    } else {
      //processVertexLate(v1);
      if (this.parents[v1] === this.y && this.found) {
        this.found = false;
        this.z = v1;
      }

      this.time++;
      this.exitTime[v1] = this.time;
      this.processed[v1] = true;
      this.stack.pop();
    }
  }
};

Tree.prototype.DFS = function (v1) {
  var _this = this;
  this.discovered[v1] = true;
  this.time++;
  this.entryTime[v1] = this.time;
  // processVertexEarly(v1, this);
  if (v1 === this.x) {
    this.found = true;
  }
  for (var i = 0; i< this.edges[v1].length; i++) {
    var v2 = this.edges[v1][i];
    if (!_this.discovered[v2]) {
      _this.parents[v2] = v1;

      // processEdge(v1, v2);
      _this.DFS(v2);
    } else if (!_this.processed[v2] || _this.directed) {
      // processEdge(v1, v2);
    }
  }
  // this.edges[v1].map(function (v2) {
  //   if (!_this.discovered[v2]) {
  //     _this.parents[v2] = v1;

  //     // processEdge(v1, v2);
  //     _this.DFS(v2);
  //   } else if (!_this.processed[v2] || _this.directed) {
  //     // processEdge(v1, v2);
  //   }
  // });
  // processVertexLate(v1, this);
  if (this.parents[v1] === this.y && this.found) {
    this.found = false;
    this.z = v1;
  }

  this.time++;
  this.exitTime[v1] = this.time;
  this.processed[v1] = true;
};

// function processVertexEarly(v, tree) {
//   if (v === tree.x) {
//     tree.found = true;
//   }
// }

// function processVertexLate(v, tree) {
//   // under root
//   if (tree.parents[v] === tree.y && tree.found) {
//     tree.found = false;
//     this.z = v;
//   }
// }

var tree = new Tree(false);

var nxy = readline().split(" ");
var n = parseInt(nxy[0]);
var x = parseInt(nxy[1]);
var y = parseInt(nxy[2]);
var vals;
tree.x = x;
tree.y = y;

for (var i = 0; i< n-1; i++) {
  vals = readline().split(" ");
  tree.addEdge(parseInt(vals[0]), parseInt(vals[1]));
}

tree.DFSNonRecursive(y);
function calcChildren(a, tree) {
  return Math.floor((tree.exitTime[a] - tree.entryTime[a]) / 2) + 1;
}

//print(tree.entryTime);
//print(tree.exitTime);
//print(calcChildren(x, tree));
// print(calcChildren(y, tree));
// print(calcChildren(z, tree));

print(n*(n-1) - calcChildren(x, tree) * (calcChildren(y, tree) - calcChildren(tree.z, tree)))

function Tree(directed) {
  this.directed = !!directed;
  this.edges = [];
  this.initSearch();
}

Tree.prototype.addEdge = function (v1, v2, directed) {
  if (!this.edges[v1]) {
    this.edges[v1] = [];
  }
  this.edges[v1].push(v2);
  if (!directed) {
    // pass true to prevent infinite loop
    this.addEdge(v2, v1, true);
  }
}

Tree.prototype.initSearch = function () {
  this.processed = [];
  this.discovered = [];
  this.parents = [];
  this.time = 0;
  this.entryTime = [];
  this.exitTime = [];
  this.found = false;
}

Tree.prototype.BFS = function (root) {
  var _this = this;
  this.queue = [];
  var v1; // current vertex
  this.queue.push(root);
  this.discovered[root] = true;
  while (this.queue.length) {
    v1 = this.queue.shift();
    //processVertexEarly(v1);
    this.processed[v1] = true;
    this.edges[v1].map(function (v2) {
      if (!_this.processed[v2] || _this.directed) {
        processEdge(v1, v2);
      }
      if (!_this.discovered[v2]) {
        _this.queue.push(v2);
        _this.discovered[v2] = true;
        _this.parents[v2] = v1;
      }
    });
    //processVertexLate(v1);
  }
};

Tree.prototype.DFS = function (v1) {
  var _this = this;
  this.discovered[v1] = true;
  this.time++;
  this.entryTime[v1] = this.time;
  processVertexEarly(v1, this);
  this.edges[v1].map(function (v2) {
    if (!_this.discovered[v2]) {
      _this.parents[v2] = v1;

      // processEdge(v1, v2);
      _this.DFS(v2);
    } else if (!_this.processed[v2] || _this.directed) {
      // processEdge(v1, v2);
    }
  });
  processVertexLate(v1, this);

  this.time++;
  this.exitTime[v1] = this.time;
  this.processed[v1] = true;
};

function processVertexEarly(v, tree) {
  if (v === tree.x) {
    tree.found = true;
  }
}

function processVertexLate(v, tree) {
  // under root
  if (tree.parents[v] === tree.y && tree.found) {
    tree.found = false;
    this.z = v;
  }
}

var tree = new Tree(false);

var nxy = readline().split(" ");
var n = parseInt(nxy[0]);
var x = parseInt(nxy[1]);
var y = parseInt(nxy[2]);
var vals;
tree.x = x;
tree.y = y;

for (var i = 0; i< n-1; i++) {
  vals = readline().split(" ");
  tree.addEdge(parseInt(vals[0]), parseInt(vals[1]));
}

tree.DFS(y);
function calcChildren(a, tree) {
  return Math.floor((tree.exitTime[a] - tree.entryTime[a]) / 2);
}

// print(calcChildren(x, tree));
// print(calcChildren(y, tree));
// print(calcChildren(z, tree));

print(n*(n-1) - calcChildren(x, tree) * (calcChildren(y, tree) - calcChildren(z, tree)) - 1)

function computeMaxCallStackSize() {
        try {
            return 1 + computeMaxCallStackSize();
        } catch (e) {
            // Call stack overflow
            return 1;
        }
    }

    print(computeMaxCallStackSize())

function Tree(directed) {
  this.directed = !!directed;
  this.edges = [];
  this.initSearch();
}

Tree.prototype.addEdge = function (v1, v2, directed) {
  if (!this.edges[v1]) {
    this.edges[v1] = [];
  }
  this.edges[v1].push(v2);
  if (!directed) {
    // pass true to prevent infinite loop
    this.addEdge(v2, v1, true);
  }
}

Tree.prototype.initSearch = function () {
  this.processed = [];
  this.earlyProcessed = [];
  this.discovered = [];
  this.parents = [];
  this.time = 0;
  this.entryTime = [];
  this.exitTime = [];
  this.found = false;
}

Tree.prototype.BFS = function (root) {
  var _this = this;
  this.queue = [];
  var v1; // current vertex
  this.queue.push(root);
  this.discovered[root] = true;
  while (this.queue.length) {
    v1 = this.queue.shift();
    //processVertexEarly(v1);
    this.processed[v1] = true;
    this.edges[v1].map(function (v2) {
      if (!_this.processed[v2] || _this.directed) {
        processEdge(v1, v2);
      }
      if (!_this.discovered[v2]) {
        _this.queue.push(v2);
        _this.discovered[v2] = true;
        _this.parents[v2] = v1;
      }
    });
    //processVertexLate(v1);
  }
};

Tree.prototype.DFSNonRecursive = function (root) {
  var _this = this;
  this.stack = [];
  var v1; // current vertex
  this.stack.unshift(root);
  this.discovered[root] = true;
  while (this.stack.length) {
    v1 = this.stack.shift();
    if (!this.earlyProcessed[v1]) {
      //processVertexEarly(v1);
      this.earlyProcessed[v1] = true;
      this.stack.unshift(v1);
      // this.processed[v1] = true;
      this.edges[v1].map(function (v2) {
        // if (!_this.processed[v2] || _this.directed) {
        //   processEdge(v1, v2);
        // }
        if (!_this.discovered[v2]) {
          _this.stack.unshift(v2);
          _this.discovered[v2] = true;
          _this.parents[v2] = v1;
        }
      });
    } else {
      //processVertexLate(v1);

      this.time++;
      this.exitTime[v1] = this.time;
      this.processed[v1] = true;
    }
  }
};

Tree.prototype.DFS = function (v1) {
  var _this = this;
  this.discovered[v1] = true;
  this.time++;
  this.entryTime[v1] = this.time;
  // processVertexEarly(v1, this);
  if (v1 === this.x) {
    this.found = true;
  }
  for (var i = 0; i< this.edges[v1].length; i++) {
    var v2 = this.edges[v1][i];
    if (!_this.discovered[v2]) {
      _this.parents[v2] = v1;

      // processEdge(v1, v2);
      _this.DFS(v2);
    } else if (!_this.processed[v2] || _this.directed) {
      // processEdge(v1, v2);
    }
  }
  // this.edges[v1].map(function (v2) {
  //   if (!_this.discovered[v2]) {
  //     _this.parents[v2] = v1;

  //     // processEdge(v1, v2);
  //     _this.DFS(v2);
  //   } else if (!_this.processed[v2] || _this.directed) {
  //     // processEdge(v1, v2);
  //   }
  // });
  // processVertexLate(v1, this);
  if (this.parents[v1] === this.y && this.found) {
    this.found = false;
    this.z = v1;
  }

  this.time++;
  this.exitTime[v1] = this.time;
  this.processed[v1] = true;
};

// function processVertexEarly(v, tree) {
//   if (v === tree.x) {
//     tree.found = true;
//   }
// }

// function processVertexLate(v, tree) {
//   // under root
//   if (tree.parents[v] === tree.y && tree.found) {
//     tree.found = false;
//     this.z = v;
//   }
// }

var tree = new Tree(false);

var nxy = readline().split(" ");
var n = parseInt(nxy[0]);
var x = parseInt(nxy[1]);
var y = parseInt(nxy[2]);
var vals;
tree.x = x;
tree.y = y;

for (var i = 0; i< n-1; i++) {
  vals = readline().split(" ");
  tree.addEdge(parseInt(vals[0]), parseInt(vals[1]));
}

tree.DFSNonRecursive(y);
function calcChildren(a, tree) {
  return Math.floor((tree.exitTime[a] - tree.entryTime[a]) / 2) + 1;
}

// print(calcChildren(x, tree));
// print(calcChildren(y, tree));
// print(calcChildren(z, tree));

print(n*(n-1) - calcChildren(x, tree) * (calcChildren(y, tree) - calcChildren(tree.z, tree)))