You are given a set $$$S$$$, which contains the first $$$n$$$ positive integers: $$$1, 2, \ldots, n$$$.You can perform the following operation on $$$S$$$ any number of times (possibly zero):   Choose a positive integer $$$k$$$ where $$$1 \le k \le n$$$, such that there exists a multiple of $$$k$$$ in $$$S$$$. Then, delete the smallest multiple of $$$k$$$ from $$$S$$$. This operation requires a cost of $$$k$$$. You are given a set $$$T$$$, which is a subset of $$$S$$$. Find the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$. We can show that such a transformation is always possible.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The description of the test cases follows. The first line contains a single positive integer $$$n$$$ ($$$1 \le n \le 10^6$$$). The second line of each test case contains a binary string of length $$$n$$$, describing the set $$$T$$$. The $$$i$$$-th character of the string is '1' if and only if $$$i$$$ is an element of $$$T$$$, and '0' otherwise. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.

For each test case, output one non-negative integer — the minimum possible total cost of operations such that $$$S$$$ would be transformed into $$$T$$$.

NoteIn the first test case, we shall not perform any operations as $$$S$$$ is already equal to $$$T$$$, which is the set $$$\{1, 2, 3, 4, 5, 6\}$$$.In the second test case, initially, $$$S = \{1, 2, 3, 4, 5, 6, 7\}$$$, and $$$T = \{1, 2, 4, 7\}$$$. We shall perform the following operations:   Choose $$$k=3$$$, then delete $$$3$$$ from $$$S$$$.  Choose $$$k=3$$$, then delete $$$6$$$ from $$$S$$$.  Choose $$$k=5$$$, then delete $$$5$$$ from $$$S$$$. The total cost is $$$3+3+5 = 11$$$. It can be shown that this is the smallest cost possible.In the third test case, initially, $$$S = \{1, 2, 3, 4\}$$$ and $$$T = \{\}$$$ (empty set). We shall perform $$$4$$$ operations of $$$k=1$$$ to delete $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$.In the fourth test case, initially, $$$S = \{1, 2, 3, 4\}$$$ and $$$T = \{3\}$$$. We shall perform two operations with $$$k=1$$$ to delete $$$1$$$ and $$$2$$$, then perform one operation with $$$k=2$$$ to delete $$$4$$$.

"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 = parseInt(readline());
          let arr = readline().trim().split("").map(cur=>parseInt(cur));
          arr.unshift(0);
          let cost = 0;
          for(let i=1;i<=n;i++){
               if(arr[i]===1) continue;
               for(let j=i;j<=n;j+=i){
                    if(arr[j]==-1) continue;
                    if(arr[j]!==1){
                         cost+=i;
                         arr[j] = -1;
                    }
                    else break;
               }
          }
          console.log(cost);
     }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let bin = readline().split('').map(Number);
        let R = bin.map(x => x === 1 ? 0 : 1);
        let T = bin;
        let toRemove = R.filter(x => x === 1).length;
        let cost = 0;

        let curr = 1;
        let p = 1;
        let removed = 0;

        while (removed < toRemove) {
            if (R[p-1] === 1) {
                R[p-1] = 0;
                removed++;
                cost += curr;
            } else if (T[p-1] === 1) {
                curr += 1;
                p = curr;
            } else {
                p += curr;
                if (p > n) {
                    curr += 1;
                    p = curr;
                }
            }
        }

        output(cost);

    }
}

"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 = parseInt(readline());
          let arr = readline().trim().split("").map(cur=>parseInt(cur));
          arr.unshift(0);
          let cost = 0;
          for(let i=1;i<=n;i++){
               if(arr[i]===0){
                    for(let j=i;j<=n;j=j+i){
                         if(arr[j]===0){
                              cost+=i;
                              arr[j] = 1;
                         }
                         else break;
                    }
               }
          }
          console.log(cost);
     }
};
solve();


Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that:  the cashier needs 5 seconds to scan one item;  after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.

The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k1, k2, ..., kn (1 ≤ ki ≤ 100), where ki is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains ki space-separated integers: mi, 1, mi, 2, ..., mi, ki (1 ≤ mi, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has.

Print a single integer — the minimum number of seconds Vasya needs to get to the cashier.

NoteIn the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.

print(function(n, k){
	var min=Infinity;
	for(var i=0;i<n;i++)
		min = Math.min(min, 15*k[i] + 5*readline().split(' ').map(Number).reduce(function(a, b){
			return a+b;
		}) );
	return min;
}(+readline(), readline().split(' ').map(Number)));

;(function () {
	print(function (n) {
		var m = null, w = readline().split(' ').map(Number);
		while (n--) {
			var q = readline().split(' ').reduce(function (p, e) { return p + (+e)*5; }, w[w.length - n - 1] * 15);
			if (m === null || q < m) {
				m = q;
			}
		}

		return m;
	}(+readline()));
}.call(this));

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 lineNum = parseInt(readline()),
		lines = tokenizeIntegers(readline());
	var best;
	for (var i = 0; i < lineNum; ++i) {
		var wait = 0,
			items = tokenizeIntegers(readline());
		for (var j = 0; j < items.length; ++j) {
			wait += items[j]*5 + 15;
		}
		if (best === undefined || wait < best) {
			best = wait;
		}
	}
	print(best);
}

main();

var tokenizer;
var index = 0;

function next(){
    while(tokenizer == null || index == tokenizer.length){
        tokenizer = readline().split(" ");
        index = 0;
    }
    var res = tokenizer[index++];
    return res;
}

function nextInt(){
    return parseInt(next());
}

function nextFloat(){
    return parseFloat(next());
}

function solve(){
    var n = nextInt();
    var k =[];
    for(var i = 0; i < n; ++i){
        k[i] = nextInt();
    }
    var min = Number.MAX_VALUE;
    for(var i = 0; i < n; ++i){
        var cur = 0;
        for(var j = 0; j < k[i]; ++j){
            var m = nextInt();
            cur += 5*m + 15;
        }
        if(cur < min){
            min = cur;
        }
    }
    print(min);
}
solve();

function main() {

    var n = Number(readline());
    var arr1 = readline().split(' ').map(Number);
    var arr2=[];
    for(var k=0;k<n;k++){
        arr2.push(readline().split(' ').map(Number));
    }

    var res = 1000000;
    for (var i = 0; i < n; i++) {
        var temp = 0;
        for (var j = 0; j < arr1[i]; j++) {
            temp += arr2[i][j] * 5 + 15;
        }
        if (temp < res) {
            res = temp;
        }
    }

    print(res);
}

main();

/**
 * Created by artyom.
 */

readline();
readline().split(' ').map(function (q) {
    var time = q * 15 + readline().split(' ').reduce(function (s, v) {
        return s + 5 * v;
    }, 0);
    if (typeof min === 'undefined' || time < min) {
        min = time;
    }
});

print(min);

let data = '';
process.stdin.on('data', c => data += c);
function* nextLine() {
	for(let l of data.trim().split(/\n/g)){
		yield l;
	}
}

const sol = () => {
	let nl = nextLine();
	let n = Number(nl.next().value);
	nl.next();
	let res = [];
	for(let i = 0; i < n; i++){
		let p = nl.next().value.trim().split(/\s/g).map(Number);

		let t = p.reduce((a, b) => a + b * 5 + 15,0);
		res.push(t);
	}
	console.log(Math.min(...res));;

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

let data = '';
process.stdin.on('data', c => data += c);
function* nextLine() {
	for(let l of data.trim().split(/\n/g)){
		console.log(l);
		yield l;
	}
}

const sol = () => {
	let nl = nextLine();
	let n = Number(nl.next().value);
	nl.next();
	let res = [];
	for(let i = 0; i < n; i++){
		let p = nl.next().value.split(/\s/g).map(Number);

		let t = p.reduce((a, b) => a + b * 5 + 15,0);
		res.push(t);
	}
	console.log(Math.min(...res));;

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

let data = '';
process.stdin.on('data', c => data += c);
function* nextLine() {
	for(let l of data.trim().split(/\n/g)){
		yield l;
	}
}

const sol = () => {
	let nl = nextLine();
	let n = Number(nl.next().value);
	nl.next();
	let res = [];
	for(let i = 0; i < n; i++){
		let p = nl.next().value.split(/\s/g).map(Number);

		let t = p.reduce((a, b) => a + b * 5 + 15,0);
		res.push(t);
	}
	console.log(Math.min(...res));;

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


Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.

For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).

'use strict';

var readline = require('readline');

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

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

function solve(s) {
  const n = s.length;
  const chars = new Set(s);
  for (let char of chars) {
    let count = new Map();
    for (let i = -1, j = 0; j < n; j++) {
      var _count$get2;
      if (s[j] === char) {
        if (i !== -1) {
          for (let key of chars) {
            if (key === char) continue;
            if (!count.has(key) || count.get(key) > 3) {
              console.log('NO');
              return;
            }
          }
        } else {
          for (let key of chars) {
            var _count$get;
            if (key === char) continue;
            if (((_count$get = count.get(key)) !== null && _count$get !== void 0 ? _count$get : 0) > 2) {
              console.log('NO');
              return;
            }
          }
        }
        i = j;
        count = new Map();
      }
      count.set(s[j], ((_count$get2 = count.get(s[j])) !== null && _count$get2 !== void 0 ? _count$get2 : 0) + 1);
    }
  }
  console.log('YES');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const s1 = await read();
    solve(s1);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
        const string = nextCharArray().join("");

		const map = new Map();

		for (let i = 0; i < string.length; i++) {
			if (!map.has(string[i])) {
				map.set(string[i], i)
			} else {
				break;
			}
		}

		let mapSize = map.size;
		let stop = false;

		for (const [key, value] of map) {
			let index = value;
			let i = 0;
			while (index + i * mapSize < string.length) {
				if (string[index] !== string[index + i * mapSize]) {
					stop = true;
				};
				i++
			}
			if (stop) break;
		}
		if (stop) {
			myout("NO");
			continue
		}

		myout("YES");

	}
}

const readline = require('readline')

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

function solve(str) {
    const chs = {}
    for (let i = 0; i < str.length; i++) {
        chs[str[i]] = 1
    }
    //
    const prev = {}
    const count = Array(str.length)
    const arr = Array(26).fill(0)
    for (let i = 0; i < str.length; i++) {
        const x = str[i]
        const idx = str.charCodeAt(i) - 'a'.charCodeAt(0)
        arr[idx]++
        count[i] = arr.slice()
        if (x in prev) {
            const p = prev[x]
            for (let ch in chs) {
                const j = ch.charCodeAt(0) - 'a'.charCodeAt(0)
                const y = count[i][j] - (count[p][j] || 0)
                if (!y) return false
            }
        }
        //
        prev[x] = i
    }
    return true
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const s = rl();
		const n = s.length;

		let p = '', ok = 1;
		for (let i = 0, seen = []; i < n && ok; i++) {
			if (i && s[i] == s[0]) break;
			p += s[i];
			if (seen[s[i]]) ok = 0; seen[s[i]] = 1;
		}

		for (let i = 0; i < n && ok; i++) {
			ok &= s[i] == p[i%p.length];
		}

		console.log(ok ? 'YES' : 'NO');
	}
}


For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:   Determine the probability with which an aim can be successfully hit by an anvil.You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.

The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases. Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106). Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10.

Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(1, -1).map(l => l.split(' ').map(v => parseInt(v)))
  ils.forEach(([a, b]) => {
    if (b == 0) {
      console.log(1)
    } else if (a == 0) {
      console.log(0.5)
    } else if (a > 4 * b) {
      let sbt = a * (a / 4) / 2
      let p = a / 4 / b
      let sst = sbt / p / p
      console.log(0.5 + (a * b - sst) / (a * b) / 2)
    } else if (a < 4 * b) {
      let st = a * (a / 4) / 2
      console.log(0.5 + st / (a * b) / 2)
    } else {
      console.log(0.75)
    }
  })
})

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(1, -1).map(l => l.split(' ').map(v => parseInt(v)))
  ils.forEach(([a, b]) => {
    if (a > 4 * b) {
      let sbt = a * (a / 4) / 2
      let p = a / 4 / b
      let sst = sbt / p / p
      console.log(0.5 + (a * b - sst) / (a * b) / 2)
    } else if (a < 4 * b) {
      let st = a * (a / 4) / 2
      console.log(0.5 + st / (a * b) / 2)
    } else {
      console.log(0.75)
    }
  })
})

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  const ils = ipt.split(EOL).slice(1, -1).map(l => l.split(' ').map(v => parseInt(v)))
  ils.forEach(([a, b]) => {
    if (a > 4 * b) {
      let sbt = a * (a / 4) / 2
      let p = a / 4 / b
      let sst = sbt * p * p
      console.log(0.5 + (a * b - sst) / (a * b) / 2)
    } else if (a < 4 * b) {
      let st = a * (a / 4) / 2
      console.log(0.5 + st / (a * b) / 2)
    } else {
      console.log(0.75)
    }
  })
})


There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.

The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000,  - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.

Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers.

NoteExplanation to the first and second samples from the statement, respectively:

function rda(){ return readline().split(" ").map(Number); }
function rdn(){ return Number(readline()); }

var inp = rda(), n = inp[0], x1 = inp[1], y1 = inp[2];
var t = [];
for(var i = 0; i < n; i++) t[i] = rda();

var ans = 0;
for(var i = 0; i < n; i++){
    if(t[i] == undefined) continue;
    var x2 = t[i][0], y2 = t[i][1];
    var a = y1-y2, b = x2-x1, c = x1*y2-x2*y1;
    ans++;

    for(var j = 0; j < n; j++){
        if(t[j] == undefined) continue;
        if((a*t[j][0] + b*t[j][1] + c) == 0) delete t[j];
    }
}

write(ans);

function resolve(x, y, arr) {
  var memo = {};
  for (var i = 0; i < arr.length; i++) {
    var d = (arr[i][1] - y) / (arr[i][0] - x);
    if (d === -Infinity) {
      d = Infinity;
    }
    if (memo[d] === undefined) {
      memo[d] = [];
    }
    memo[d].push(i);
  }
  return Object.keys(memo).length;
}

const p = readline().split(' ');
var arr = [];
for (var i = 0; i < parseInt(p[0], 10); i++) {
  var st = readline().split(' ');
  arr.push(
    st.map(el => {
      return parseInt(el, 10);
    })
  );
}
print(resolve(parseInt(p[1], 10), parseInt(p[2], 10), arr));

function Point(x,y){
	this.x = x;
	this.y = y;
}

function vp(a,b,c){
	return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
}

var s = readline().split(' ');
var n = +s[0];
var p0 = new Point(+s[1],+s[2]);

var u = [], p = [];
for(var i=0; i<n; i++){
	u.push(false);
	s = readline().split(' ');
	p.push(new Point(+s[0],+s[1]));
}

var ans = 0;
for(var i=0; i<n; i++){
	if(u[i]) continue;
	for(var j=i+1; j<n; j++){
		if(vp(p0,p[i],p[j])==0) u[j]=true;
	}
	ans++;
}

print(ans);

var firstLine = readline().split(" ");
var n = parseInt(firstLine[0]);

function Pair(x, y) {
	this.x = x;
	this.y = y;
}

var z0 = new Pair(parseInt(firstLine[1]), parseInt(firstLine[2]));
var p = new Array(n),
	isDead = new Array(n);

for (var i = 0; i < n; i++) {
	var line = readline().split(" ");
	p[i] = new Pair(parseInt(line[0]), parseInt(line[1]));
	isDead[i] = false;
}

function isSameLine(a, b, c) {
	if (c.x == b.x && c.y == b.y) {
		return true;
	}
	var z0 = new Pair(b.x - a.x, b.y - a.y);
	var z1 = new Pair(c.x - a.x, c.y - a.y);

	return z0.x * z1.y == z0.y * z1.x;
}

var ans = 0;
for (var i = 0; i < n; i++) {
	if (isDead[i]) {
		continue;
	}
	ans++;
	isDead[i] = true;
	for (var j = i + 1; j < n; j++) {
		if (isSameLine(z0, p[i], p[j])) {
			isDead[j] = true;
		}
	}
}

print(ans);

function rda(){ return readline().split(" ").map(Number); }
function rdn(){ return Number(readline()); }

var inp = rda(), n = inp[0], x1 = inp[1], y1 = inp[2];
var t = [];
for(var i = 0; i < n; i++) t[i] = rda();

var ans = 0;
for(var i = 0; i < n; i++){
    if(t[i] == undefined) continue;
    var x2 = t[i][0], y2 = t[i][1];
    var a = y1-y2, b = x2-x1, c = x1*y2-x2*y1;
    ans++;

    for(var j = 0; j < n; j++){
        if(t[j] == undefined) continue;
        if((a*t[j][0] + b*t[j][1] + c) == 0) delete t[j];
    }
    print(a, b, c, i);
}

write(ans);

function resolve(x, y, arr) {
  var memo = {};
  for (var i = 0; i < arr.length; i++) {
    var d = (arr[i][1] - y) / (arr[i][0] - x);
    if (memo[d] === undefined) {
      memo[d] = [];
    }
    memo[d].push(i);
  }
  return Object.keys(memo).length;
}

const p = readline().split(' ');
var arr = [];
for (var i = 0; i < parseInt(p[0], 10); i++) {
  var st = readline().split(' ');
  arr.push(
    st.map(el => {
      return parseInt(el, 10);
    })
  );
}
print(resolve(parseInt(p[1], 10), parseInt(p[2], 10), arr));

function Point(x,y){
	this.x = x;
	this.y = y;
}

var s = readline().split(' ');
var n = +s[0];
var p0 = new Point(+s[1],+s[2]);

var p = [];
for(var i=0; i<n; i++){
	s = readline().split(' ');
	p.push(new Point(+s[0],+s[1]));
}

var map = {};
for(var i=0; i<n; i++){
	map[(p[i].y-p0.y)/(p[i].x-p0.x)]=1;
}

var ans=0;
for( var x in map){
	ans++;
}

print(ans);


Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.Valentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of actions Valentin did. The next n lines contain descriptions of his actions, each line contains description of one action. Each action can be of one of three types:    Valentin pronounced some word and didn't get an electric shock. This action is described by the string ". w" (without quotes), in which "." is a dot (ASCII-code 46), and w is the word that Valentin said.  Valentin pronounced some word and got an electric shock. This action is described by the string "! w" (without quotes), in which "!" is an exclamation mark (ASCII-code 33), and w is the word that Valentin said.  Valentin made a guess about the selected letter. This action is described by the string "? s" (without quotes), in which "?" is a question mark (ASCII-code 63), and s is the guess — a lowercase English letter.  All words consist only of lowercase English letters. The total length of all words does not exceed 105. It is guaranteed that last action is a guess about the selected letter. Also, it is guaranteed that Valentin didn't make correct guesses about the selected letter before the last action. Moreover, it's guaranteed that if Valentin got an electric shock after pronouncing some word, then it contains the selected letter; and also if Valentin didn't get an electric shock after pronouncing some word, then it does not contain the selected letter.

Output a single integer — the number of electric shocks that Valentin could have avoided if he had told the selected letter just after it became uniquely determined.

8
! hello
! codeforces
? c
. o
? d
? h
. l
? e

7
! ababahalamaha
? a
? b
? a
? b
? a
? h

NoteIn the first test case after the first action it becomes clear that the selected letter is one of the following: a, b, c. After the second action we can note that the selected letter is not a. Valentin tells word "b" and doesn't get a shock. After that it is clear that the selected letter is c, but Valentin pronounces the word cd and gets an excessive electric shock. In the second test case after the first two electric shocks we understand that the selected letter is e or o. Valentin tries some words consisting of these letters and after the second word it's clear that the selected letter is e, but Valentin makes 3 more actions before he makes a correct hypothesis.In the third example the selected letter can be uniquely determined only when Valentin guesses it, so he didn't get excessive electric shocks.

function intersection(array, word) {
  for (var i = 0; i < word.length; i++) {
    var index = word.charCodeAt(i) - 'a'.charCodeAt(0);
    // print('index ->', index);
    if (array[index] === -1) array[index] = 1;
    if (array[index] === 0) continue;
  }
  for (var i = 0; i < array.length; i++) {
    if (array[i] === -1) array[i] = 0;
    if (array[i] === 1) array[i] = -1;
  }
  return array;
}

function exclusion(array, word) {
  for (var i = 0; i < word.length; i++) {
    var index = word.charCodeAt(i) - 'a'.charCodeAt(0);
    // print('index ->', index);
    if (array[index] === -1) array[index] = 0;
    if (array[index] === 0) continue;
  }
  return array;
}

function main(){
  var n = parseInt(readline());
  // print(n);

  var letters = [];
  for (var i = 0; i < 26; i++) letters.push(-1);

  var i = 0, solved = false, res = 0;
  for (; i < n - 1; i++) {
    var result = readline().split(" ");
    var word = result[1];
    result = result[0];
    // print(result, word);
    if (solved && (result === '!' || result === '?')) res++;
    if (result === '!') {
      // print('shock');
      letters = intersection(letters, word);
    }
    if (result === '.') {
      // print('no shock');
      letters = exclusion(letters, word);
    }
    if (result === '?') {
      // print('guess');
      letters = exclusion(letters, word);
    }

    // print('letters ->', letters);
    var cnt = 0;
    for (var k = 0; k < letters.length; k++) {
      if(letters[k] == -1) cnt++;
    }
    // print ('RES -->', cnt);
    if (cnt === 1) {
      // print('SOLVED on turn ', i);
      solved = true;
    }
  }
  print(res);
}

main()


В самолёте есть n рядов мест. Если смотреть на ряды сверху, то в каждом ряду есть 3 места слева, затем проход между рядами, затем 4 центральных места, затем ещё один проход между рядами, а затем ещё 3 места справа.Известно, что некоторые места уже заняты пассажирами. Всего есть два вида пассажиров — статусные (те, которые часто летают) и обычные. Перед вами стоит задача рассадить ещё k обычных пассажиров так, чтобы суммарное число соседей у статусных пассажиров было минимально возможным. Два пассажира считаются соседями, если они сидят в одном ряду и между ними нет других мест и прохода между рядами. Если пассажир является соседним пассажиром для двух статусных пассажиров, то его следует учитывать в сумме соседей дважды.

В первой строке следуют два целых числа n и k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10·n) — количество рядов мест в самолёте и количество пассажиров, которых нужно рассадить. Далее следует описание рядов мест самолёта по одному ряду в строке. Если очередной символ равен '-', то это проход между рядами. Если очередной символ равен '.', то это свободное место. Если очередной символ равен 'S', то на текущем месте будет сидеть статусный пассажир. Если очередной символ равен 'P', то на текущем месте будет сидеть обычный пассажир.  Гарантируется, что количество свободных мест не меньше k. Гарантируется, что все ряды удовлетворяют описанному в условии формату.

В первую строку выведите минимальное суммарное число соседей у статусных пассажиров. Далее выведите план рассадки пассажиров, который минимизирует суммарное количество соседей у статусных пассажиров, в том же формате, что и во входных данных. Если в свободное место нужно посадить одного из k пассажиров, выведите строчную букву 'x' вместо символа '.'.

4 9
PP.-PPPS-S.S
PSP-PPSP-.S.
.S.-S..P-SS.
P.S-P.PP-PSP

15
PPx-PPPS-S.S
PSP-PPSP-xSx
xSx-SxxP-SSx
P.S-PxPP-PSP

ПримечаниеВ первом примере нужно посадить ещё двух обычных пассажиров. Для минимизации соседей у статусных пассажиров, нужно посадить первого из них на третье слева место, а второго на любое из оставшихся двух мест, так как независимо от выбора места он станет соседом двух статусных пассажиров. Изначально, у статусного пассажира, который сидит на самом левом месте уже есть сосед. Также на четвёртом и пятом местах слева сидят статусные пассажиры, являющиеся соседями друг для друга (что добавляет к сумме 2).Таким образом, после посадки ещё двух обычных пассажиров, итоговое суммарное количество соседей у статусных пассажиров станет равно пяти.

var signalPassanger = 'S';
var separator = '-';
var commonPassanger = 'P';
var newPassanger = 'x';
var freePlace = '.';

var firstLine = readline().split(' ').map(function(v){return +v;});
var rowsCount = +firstLine[0];
var rows = [];
var passangerCount = +firstLine[1];

for (var i = 0; i < rowsCount; i++) {
    rows.push(readline());
}

function replaceAt(string, index, replace) {
  return string.substring(0, index) + replace + string.substring(index + 1);
}

function calcWeight(string, index) {
    var result = 0;
    switch (index) {
        case 0: case 4: case 9:
            if (string.charAt(index + 1) == signalPassanger) result++;
            break;
        case 2: case 7: case 11:
            if (string.charAt(index - 1) == signalPassanger) result++;
            break;
        default:
            if (string.charAt(index - 1) == signalPassanger) result++;
            if (string.charAt(index + 1) == signalPassanger) result++;
    }

    return result;
}

function arrangePassangers(weight) {
    if (passangerCount === 0) return;

    for (var i = 0; i < rowsCount; i++) {
        for (var j = 0; j < 12; j++) {
            if (rows[i].charAt(j) == freePlace) {
                if ((calcWeight(rows[i], j) === weight) && (passangerCount > 0)) {
                    rows[i] = replaceAt(rows[i], j, newPassanger);
                    passangerCount--;
                }
            }
        }
    }
}

function isPassanger(string, index) {
    return (string.charAt(index) != freePlace);
}

arrangePassangers(0);
arrangePassangers(1);
arrangePassangers(2);

var result = 0;
var currentChar = '';

for (var i = 0; i < rowsCount; i++) {
    for (var j = 0; j < 12; j++) {
        if (rows[i].charAt(j) == signalPassanger) {
            switch (j) {
                case 0: case 4: case 9:
                    if (isPassanger(rows[i], j + 1)) result++;
                    break;
                case 2: case 7: case 11:
                    if (isPassanger(rows[i], j - 1)) result++;
                    break;
                default:
                    if (isPassanger(rows[i], j - 1)) result++;
                    if (isPassanger(rows[i], j + 1)) result++;
            }
        }
    }
}

print(result);

for (var i = 0; i < rowsCount; i++) {
    print(rows[i])
}

var first = readline().split(' ');
	var rows_count = +first[0];
	var people = +first[1];
	var matrix = [];
	var zero = 0;
	var one = 0;
	var two = 0;
	var return_val = 0;
	var dif_val = 0;
	for (var inc1=0; inc1<rows_count; inc1++)
	{
		matrix[inc1] = readline();
		if ((matrix[inc1][0] == 'S')&&(matrix[inc1][1] != '.')) return_val++;
		if ((matrix[inc1][11] == 'S')&&(matrix[inc1][10] != '.')) return_val++;
		if (matrix[inc1][0] == '.')
		{
			if (matrix[inc1][1] == 'S') one++;
			else zero++;
		}
		if (matrix[inc1][11] == '.')
		{
			if (matrix[inc1][10] == 'S') one++;
			else zero++;
		}
		for (var inc2=1; inc2<11; inc2++)
		{
			if ((matrix[inc1][inc2] == 'S')&&(matrix[inc1][inc2-1] != '.')&&(matrix[inc1][inc2-1] != '-')) return_val++;
			if ((matrix[inc1][inc2] == 'S')&&(matrix[inc1][inc2+1] != '.')&&(matrix[inc1][inc2+1] != '-')) return_val++;
			if (matrix[inc1][inc2] == '.')
			{
				if ((matrix[inc1][inc2-1] == 'S')&&(matrix[inc1][inc2+1] == 'S')) two++;
				else if ((matrix[inc1][inc2-1] != 'S')&&(matrix[inc1][inc2+1] != 'S')) zero++;
				else one++;
			}
		}
	}
	if (people > zero + one ) dif_val = 2;
	else if (people > zero ) dif_val = 1;
	if (dif_val == 1)
		{
			return_val = return_val + ( people - zero );
			people = people - zero;
		}
	if (dif_val == 2)
		{
			return_val = return_val + one + ( people - zero - one )*2;
			people = people - zero - one;
		}

	print(return_val);

	for (var inc1=0; inc1<rows_count; inc1++)
	{
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] != 'S')&&(dif_val == 0)&&(people > 0))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
			people--;
		}
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] != 'S')&&(dif_val > 0))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
		}
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] == 'S')&&(dif_val == 1)&&(people > 0))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
			people--;
		}
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] == 'S')&&(dif_val > 1))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] != 'S')&&(dif_val == 0)&&(people > 0))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
			people--;
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] != 'S')&&(dif_val > 0))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] == 'S')&&(dif_val == 1)&&(people > 0))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
			people--;
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] == 'S')&&(dif_val > 1))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
		}
		for (var inc2=1; inc2<11; inc2++)
		{
			if ((matrix[inc1][inc2] == '.')&&(dif_val == 2))
			{
				if ((matrix[inc1][inc2-1] == 'S')&&(matrix[inc1][inc2+1] == 'S'))
				{
					if (people > 0)
					{
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
					people--;
					}
				}
				else matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
			}
			if ((matrix[inc1][inc2] == '.')&&(dif_val == 0)&&(people > 0))
			{
				if ((matrix[inc1][inc2-1] != 'S')&&(matrix[inc1][inc2+1] != 'S'))
				{
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
					people--;
				}
			}
			if ((matrix[inc1][inc2] == '.')&&(dif_val == 1))
			{
				if ((matrix[inc1][inc2-1] == 'S')&&(matrix[inc1][inc2+1] == 'S')) {}
				else if ((matrix[inc1][inc2-1] != 'S')&&(matrix[inc1][inc2+1] != 'S'))
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
				else if (people > 0)
				{
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
					people--;
				}
			}
		}
		print(matrix[inc1]);
	}

var numbers = readline().split(" ").map(function(x) { return parseInt(x); });
var N = numbers[0];
var K = numbers[1];

var lines = [];
var indexWith0Score = [];
var indexWith1Score = [];
var indexWith2Score = [];
var score = 0;

for(var i = 0; i < N; i++) {
    var newLine = readline();
    lines.push(newLine.split(''));
    for(var k = 0; k < newLine.length; k++) {
        var position = {row: i, col: k};
        if(newLine[k] === '.') {
            if(k === 0) {
                if(newLine[k + 1] === 'S') {
                    indexWith1Score.push(position);
                } else {
                    indexWith0Score.push(position);
                }
            } else if(k === newLine[newLine.length - 1]) {
                if(newLine[k - 1] === 'S') {
                    indexWith1Score.push(position);
                } else {
                    indexWith0Score.push(position);
                }
            } else {
                if(newLine[k + 1] === 'S' && newLine[k - 1] === 'S') {
                    indexWith2Score.push(position);
                } else if(newLine[k + 1] === 'S' || newLine[k - 1] === 'S') {
                    indexWith1Score.push(position);
                } else {
                    indexWith0Score.push(position);
                }
            }
        } else if(newLine[k] === 'S') {
            if(newLine[k + 1] === 'P' || newLine[k + 1] === 'S') {
                score++;
            }
            if(newLine[k - 1] === 'P' || newLine[k - 1] === 'S' ) {
                score++;
            }
        }
    }
}

var placedPassangers = 0;

for(var i = 0; i < indexWith0Score.length; i++) {
    if(placedPassangers >= K) break;
    var position = indexWith0Score[i];
    lines[position.row][position.col] = 'x';
    placedPassangers++;
}

for(var i = 0; i < indexWith1Score.length; i++) {
    if(placedPassangers >= K) break;
    var position = indexWith1Score[i];
    lines[position.row][position.col] = 'x';
    score++;
    placedPassangers++;
}

for(var i = 0; i < indexWith2Score.length; i++) {
    if(placedPassangers >= K) break;
    var position = indexWith2Score[i];
    lines[position.row][position.col] = 'x';
    score+=2;
    placedPassangers++;
}

write(score + '\n' + lines.map(function(item) {return item.join('')}).join('\n'));

'use strict'
let config = readline()
function getPlaneData(){
    let x = readline()
	let i=x;
    while(typeof x != 'undefined'){
		x=readline()
		if(x){
			i+='-'+x
		}
    }
    return i
}

let inputs = getPlaneData()
let passengers = parseInt(config.split(" ")[1])
let none = []
let one = []
let two = []
let nb = 0
function parser(s){
	for(let i=0,l=s.length;i<l;i++){
		if(s[i]=='.'){
			let enbrs = 0//elite neigbours
			if(s[i-1] == 'S'){
				enbrs++
			}
			if(s[i+1] == 'S'){
				enbrs++
			}
			switch(enbrs){
				case 0:
					none.push(i)
				break
				case 1:
					one.push(i)
				break
				case 2:
					two.push(i)
				break
			}
		}
		if(s[i]=='S'){
			if(s[i-1]){
				if(s[i-1] != '-' && s[i-1] != '.'){
					nb++
				}
			}
			if(s[i+1]){
				if(s[i+1] != '-' && s[i+1] != '.'){
					nb++
				}
			}
		}
	}
	let strarr = s.split('')
	let x = 'x'
	while(passengers!=0){
		if(none.length!=0){
			strarr[none.shift()] = x
		} else if(one.length!=0){
			strarr[one.shift()] = x
			nb+=1
		} else {
			strarr[two.shift()] = x
			nb+=2
		}
		passengers--;
	}
	print(nb)
	let m = strarr.join('').match(/.{1,12}./g)
	for(let out of m){
		if(out.length==13){
			print(out.slice(0,-1))
		} else{
			print(out)
		}
	}
}
parser(inputs)

var signalPassanger = 'S';
var separator = '-';
var commonPassanger = 'P';
var newPassanger = 'x';
var freePlace = '.';

var firstLine = readline().split(' ').map(function(v){return +v;});
var rowsCount = +firstLine[0];
var rows = [];
var passangerCount = +firstLine[1];

for (var i = 0; i < rowsCount; i++) {
    rows.push(readline());
}

function replaceAt(string, index, replace) {
  return string.substring(0, index) + replace + string.substring(index + 1);
}

function calcWeight(string, index) {
    var result = 0;
    switch (index) {
        case 0: case 4: case 9:
            if (string.charAt(index + 1) == signalPassanger) result++;
            break;
        case 2: case 7: case 11:
            if (string.charAt(index - 1) == signalPassanger) result++;
            break;
        default:
            if (string.charAt(index - 1) == signalPassanger) result++;
            if (string.charAt(index + 1) == signalPassanger) result++;
    }

    return result;
}

function arrangePassangers(weight) {
    if (passangerCount === 0) return;

    for (var i = 0; i < rowsCount; i++) {
        for (var j = 0; j < 12; j++) {
            if (rows[i].charAt(j) == freePlace) {
                if ((calcWeight(rows[i], j) === weight) && (passangerCount > 0)) {
                    rows[i] = replaceAt(rows[i], j, newPassanger);
                    passangerCount--;
                }
            }
        }
    }
}

function isPassanger(string, index) {
    return (string.charAt(index) == commonPassanger) ||
            (string.charAt(index) == newPassanger);
}

arrangePassangers(0);
arrangePassangers(1);
arrangePassangers(2);

var result = 0;
var currentChar = '';

for (var i = 0; i < rowsCount; i++) {
    for (var j = 0; j < 12; j++) {
        if (rows[i].charAt(j) == signalPassanger) {
            switch (j) {
                case 0: case 4: case 9:
                    if (isPassanger(rows[i], j + 1)) result++;
                    break;
                case 2: case 7: case 11:
                    if (isPassanger(rows[i], j - 1)) result++;
                    break;
                default:
                    if (isPassanger(rows[i], j - 1)) result++;
                    if (isPassanger(rows[i], j + 1)) result++;
            }
        }
    }
}

print(result + 2);

for (var i = 0; i < rowsCount; i++) {
    print(rows[i]);
}

var first = readline().split(' ');
	var rows_count = +first[0];
	var people = +first[1];
	var matrix = [];
	var zero = 0;
	var one = 0;
	var two = 0;
	var return_val = 0;
	var dif_val = 0;
	for (var inc1=0; inc1<rows_count; inc1++)
	{
		matrix[inc1] = readline();
		if ((matrix[inc1][0] == 'S')&&(matrix[inc1][1] != '.')) return_val++;
		if ((matrix[inc1][11] == 'S')&&(matrix[inc1][10] != '.')) return_val++;
		if (matrix[inc1][0] == '.')
		{
			if (matrix[inc1][1] == 'S') one++;
			else zero++;
		}
		if (matrix[inc1][11] == '.')
		{
			if (matrix[inc1][10] == 'S') one++;
			else zero++;
		}
		for (var inc2=1; inc2<11; inc2++)
		{
			if ((matrix[inc1][inc2] == 'S')&&(matrix[inc1][inc2-1] != '.')&&(matrix[inc1][inc2-1] != '-')) return_val++;
			if ((matrix[inc1][inc2] == 'S')&&(matrix[inc1][inc2+1] != '.')&&(matrix[inc1][inc2+1] != '-')) return_val++;
			if (matrix[inc1][inc2] == '.')
			{
				if ((matrix[inc1][inc2-1] == 'S')&&(matrix[inc1][inc2+1] == 'S')) two++;
				else if ((matrix[inc1][inc2-1] != 'S')&&(matrix[inc1][inc2+1] != 'S')) zero++;
				else one++;
			}
		}
	}
	if (people > zero + one ) dif_val = 2;
	else if (people > zero ) dif_val = 1;
	if (dif_val == 1)
		{
			return_val = return_val + ( people - zero );
			people = people - zero;
		}
	if (dif_val == 2)
		{
			return_val = return_val + one + ( people - zero - one )*2;
			people = people - zero - one;
		}

	print(return_val);

	for (var inc1=0; inc1<rows_count; inc1++)
	{
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] != 'S')&&(dif_val == 0)&&(people > 0))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
			//matrix[inc1][0] = 'x';
			people--;
		}
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] != 'S')&&(dif_val > 0))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
		}
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] == 'S')&&(dif_val == 1)&&(people > 0))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
			people--;
		}
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] == 'S')&&(dif_val > 1))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] != 'S')&&(dif_val == 0)&&(people > 0))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
			people--;
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] != 'S')&&(dif_val > 0))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] == 'S')&&(dif_val == 1)&&(people > 0))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
			people--;
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] == 'S')&&(dif_val > 1))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
		}
		for (var inc2=1; inc2<11; inc2++)
		{
			if ((matrix[inc1][inc2] == '.')&&(dif_val == 2)&&(people > 0))
			{
				if ((matrix[inc1][inc2-1] == 'S')&&(matrix[inc1][inc2+1] == 'S'))
				{
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
					people--;
				}
				else matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
			}
			if ((matrix[inc1][inc2] == '.')&&(dif_val == 0)&&(people > 0))
			{
				if ((matrix[inc1][inc2-1] != 'S')&&(matrix[inc1][inc2+1] != 'S'))
				{
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
					people--;
				}
			}
			if ((matrix[inc1][inc2] == '.')&&(dif_val == 1)&&(people > 0))
			{
				if ((matrix[inc1][inc2-1] == 'S')&&(matrix[inc1][inc2+1] == 'S')) {}
				else if ((matrix[inc1][inc2-1] != 'S')&&(matrix[inc1][inc2+1] != 'S'))
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
				else
				{
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
					people--;
				}
			}
		}
		print(matrix[inc1]);
	}

var first = readline().split(' ');
	var rows_count = +first[0];
	var people = +first[1];
	var matrix = [];
	var zero = 0;
	var one = 0;
	var two = 0;
	var return_val = 0;
	var dif_val = 0;
	for (var inc1=0; inc1<rows_count; inc1++)
	{
		matrix[inc1] = readline();
		if ((matrix[inc1][0] == 'S')&&(matrix[inc1][1] != '.')) return_val++;
		if ((matrix[inc1][11] == 'S')&&(matrix[inc1][10] != '.')) return_val++;
		if (matrix[inc1][0] == '.')
		{
			if (matrix[inc1][1] == 'S') one++;
			else zero++;
		}
		if (matrix[inc1][11] == '.')
		{
			if (matrix[inc1][10] == 'S') one++;
			else zero++;
		}
		for (var inc2=1; inc2<11; inc2++)
		{
			if ((matrix[inc1][inc2] == 'S')&&(matrix[inc1][inc2-1] != '.')&&(matrix[inc1][inc2-1] != '-')) return_val++;
			if ((matrix[inc1][inc2] == 'S')&&(matrix[inc1][inc2+1] != '.')&&(matrix[inc1][inc2+1] != '-')) return_val++;
			if (matrix[inc1][inc2] == '.')
			{
				if ((matrix[inc1][inc2-1] == 'S')&&(matrix[inc1][inc2+1] == 'S')) two++;
				else if ((matrix[inc1][inc2-1] != 'S')&&(matrix[inc1][inc2+1] != 'S')) zero++;
				else one++;
			}
		}
	}
	if (people > zero + one ) dif_val = 2;
	else if (people > zero ) dif_val = 1;
	if (dif_val == 1)
		{
			return_val = return_val + ( people - zero );
			people = people - zero;
		}
	if (dif_val == 2)
		{
			return_val = return_val + one + ( people - zero - one )*2;
			people = people - zero - one;
		}

	print(return_val);

	for (var inc1=0; inc1<rows_count; inc1++)
	{
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] != 'S')&&(dif_val == 0)&&(people > 0))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
			//matrix[inc1][0] = 'x';
			people--;
		}
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] != 'S')&&(dif_val > 0))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
		}
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] == 'S')&&(dif_val == 1)&&(people > 0))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
			people--;
		}
		if ((matrix[inc1][0] == '.')&&(matrix[inc1][1] == 'S')&&(dif_val > 1))
		{
			matrix[inc1] = 'x' + matrix[inc1].substr(1);
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] != 'S')&&(dif_val == 0)&&(people > 0))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
			people--;
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] != 'S')&&(dif_val > 0))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] == 'S')&&(dif_val == 1)&&(people > 0))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
			people--;
		}
		if ((matrix[inc1][11] == '.')&&(matrix[inc1][10] == 'S')&&(dif_val > 1))
		{
			matrix[inc1] = matrix[inc1].substr(0, 11) + 'x';
		}
		for (var inc2=1; inc2<11; inc2++)
		{
			if ((matrix[inc1][inc2] == '.')&&(dif_val == 2))
			{
				if ((matrix[inc1][inc2-1] == 'S')&&(matrix[inc1][inc2+1] == 'S')&&(people > 0))
				{
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
					people--;
				}
				else matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
			}
			if ((matrix[inc1][inc2] == '.')&&(dif_val == 0)&&(people > 0))
			{
				if ((matrix[inc1][inc2-1] != 'S')&&(matrix[inc1][inc2+1] != 'S'))
				{
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
					people--;
				}
			}
			if ((matrix[inc1][inc2] == '.')&&(dif_val == 1))
			{
				if ((matrix[inc1][inc2-1] == 'S')&&(matrix[inc1][inc2+1] == 'S')) {}
				else if ((matrix[inc1][inc2-1] != 'S')&&(matrix[inc1][inc2+1] != 'S'))
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
				else if (people > 0)
				{
					matrix[inc1] = matrix[inc1].substr(0, inc2) + 'x' + matrix[inc1].substr(inc2 + 1);
					people--;
				}
			}
		}
		print(matrix[inc1]);
	}


A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a ≤ b, he or she likes it if and only if he can climb into this car and 2a ≥ b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.

You are given four integers V1, V2, V3, Vm(1 ≤ Vi ≤ 100) — sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V1 > V2 > V3.

Output three integers — sizes of father bear's car, mother bear's car and son bear's car, respectively. If there are multiple possible solutions, print any. If there is no solution, print "-1" (without quotes).

NoteIn first test case all conditions for cars' sizes are satisfied.In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20.

var N = readline().split(' ');
var a1 = parseInt(N[0]),a2 = parseInt(N[1]),a3 = parseInt(N[2]),a4 = parseInt(N[3]);
var b1left = a1 , b2left = a2 ,b3left = a3;
var b1right = 2 * a1 , b2right = 2 *a2 , b3right = 2 * a3 ;
var b1=0, b2=0, b3=0;
for(var i=200;i>=0;i--){
  if(i>=b1left && i <= b1right && b1 == 0 && a4 <= i && i > 2 * a4) {
      b1 = i;
      continue;
  }
  if(i >= b2left && i <= b2right && b2 ==0 && a4 <= i && i > 2 * a4) {
    b2 = i;
    continue;
  }
  if(i >= b3left && i <= b3right && a4 <= i && i <= 2 * a4){
    b3 = i;
    break;
  }

}

if(b1 == 0 || b2 == 0 || b3 == 0){
  print("-1");
}
else{
  print(b1);
  print(b2);
  print(b3);
}

mas=readline().split(' ');
v1=parseInt(mas[0])*2;
v2=parseInt(mas[1])*2;
v3=parseInt(mas[2]);
vm=parseInt(mas[3])*2;
no=false;
if(v1 <= vm) {
    no=true;
}
if(v2 <= vm) {
    no=true;
}
vm=vm/2;
if(v3 > vm) {
    min = vm;
    max = v3;
} else {
    min = v3;
    max = vm;
}

if(max > min*2 || no) {
    print('-1');
} else {
    print(v1);
    print(v2);
    print(max);
}

'use strict'

const input = readline();

// const print = console.log;
// const line0 = "50 30 10 19";

// const input = line0;
const arr = input.split(' ').map(x => parseInt(x));

const bear3 = arr[0];
const bear2 = arr[1];
const bear1 = arr[2];
const masha = arr[3];

const car1_low = bear1;
const car2_low = bear2;
const car3_low = bear3;

const car1_high = bear1 * 2;
const car2_high = bear2 * 2;
const car3_high = bear3 * 2;

const masha_likes_low = masha;
const masha_likes_high = masha * 2;

if (masha_likes_low > car1_high || masha_likes_high < car1_low || masha_likes_high >= car2_high) {
    print(-1);
} else {
    const car1 = masha_likes_low < car1_low ? car1_low : masha_likes_low;
    print(car3_high);
    print(car2_high);
    print(car1);
}

var line = readline();
var bears = line.split(' ').map(function(x) {return parseInt(x)});
var big = 2 * bears[0];
var medium = Math.min(2 * bears[1], big - 1);
var small = Math.min(2 * bears[2], 2 * bears[3], medium - 1);

if (bears[1] > medium ||
    bears[2] > small ||
    bears[3] > small ||
    2 * bears[3] >= big ||
    2 * bears[3] >= medium) {
    print(-1);
} else {
  print(big);
  print(medium);
  print(small);
}

/**
 * 已知 a1 a2 a3 a4
 *  b1>b2>b3   a1<=b1<=2a1   b3<=a4<=2b3
 */

var N = readline().split(' ');
var a1 = parseInt(N[0]),a2 = parseInt(N[1]),a3 = parseInt(N[2]),a4 = parseInt(N[3]);
var b1left = a1 , b2left = a2 ,b3left = a3;
var b1right = 2 * a1 , b2right = 2 *a2 , b3right = 2 * a3 ;
var b1=0, b2=0, b3=0;
for(var i=200;i>=0;i--){
  if(i>=b1left && i <=b1right){
      b1 = i;
      continue;
  }
  if(i >= b2left && i <= b2right){
    b2 = i;
    continue;
  }
  if(i >= b3left && i <= b3right && b3left <= a4 && a4 <= b3right){
    b3 = i;
  }

}

if(b1 == 0 || b2 == 0 || b3 == 0){
  print("-1");
}
else{
  print(b1);
  print(b2);
  print(b3);
}

var N = readline().split(' ');
var a1 = parseInt(N[0]),a2 = parseInt(N[1]),a3 = parseInt(N[2]),a4 = parseInt(N[3]);
var b1left = a1 , b2left = a2 ,b3left = a3;
var b1right = 2 * a1 , b2right = 2 *a2 , b3right = 2 * a3 ;
var b1=0, b2=0, b3=0;
for(var i=200;i>=0;i--){
  if(i>=b1left && i <= b1right && b1 == 0) {
      b1 = i;
      continue;
  }
  if(i >= b2left && i <= b2right && b2 ==0) {
    b2 = i;
    continue;
  }
  if(i >= b3left && i <= b3right && a4 <= i && i <= 2 * a4){
    b3 = i;
    break;
  }

}

print(b1, b2, b3);

if(b1 == 0 || b2 == 0 || b3 == 0){
  print("-1");
}
else{
  print(b1);
  print(b2);
  print(b3);
}

var N = readline().split(' ');
var a1 = parseInt(N[0]),a2 = parseInt(N[1]),a3 = parseInt(N[2]),a4 = parseInt(N[3]);
var b1left = a1 , b2left = a2 ,b3left = a3;
var b1right = 2 * a1 , b2right = 2 *a2 , b3right = 2 * a3 ;
var b1=0, b2=0, b3=0;
for(var i=200;i>=0;i--){
  if(i>=b1left && i <= b1right && b1 == 0) {
      b1 = i;
      continue;
  }
  if(i >= b2left && i <= b2right && b2 ==0) {
    b2 = i;
    continue;
  }
  if(i >= b3left && i <= b3right && a4 <= i && i <= 2 * a4){
    b3 = i;
    break;
  }

}

if(b1 == 0 || b2 == 0 || b3 == 0){
  print("-1");
}
else{
  print(b1);
  print(b2);
  print(b3);
}

mas=readline().split(' ');
v1=parseInt(mas[0])*2;
v2=parseInt(mas[1])*2;
v3=parseInt(mas[2])*2;
vm=parseInt(mas[3])*2;
no=false;
if(v1 <= vm) {
    no=true;
}
if(v2 <= vm) {
    no=true;
}
if(v3 <= vm) {
    no=true;
}

if(no) {
    print('-1');
} else {
    print(v1);
    print(v2);
    print(v3);
}

mas=readline().split(' ');
v1=parseInt(mas[0])*2;
v2=parseInt(mas[1])*2;
v3=parseInt(mas[2])*2;
vm=parseInt(mas[3])*2;
no=false;
if(v1 <= vm) {
    no=true;
}
if(v2 <= vm) {
    no=true;
}
if(v3 < vm) {
    no=true;
}

if(no) {
    print('-1');
} else {
    print(v1);
    print(v2);
    print(v3);
}

mas=readline().split(' ');
v1=parseInt(mas[0]);
v2=parseInt(mas[1]);
v3=parseInt(mas[2]);
vm=parseInt(mas[3]);
no=false;
if(v1 <= vm*2) {
    if (vm*2+2 <= v1*2) {
        v1 = vm*2+2;
    } else {
        no=true;
    }
}
if(v2 <= vm*2) {
    if (vm*2+1 <= v2*2) {
        v2 = vm*2+1;
    } else {
        no=true;
    }
}
if(v3 > vm) {
    min = vm;
    max = v3;
} else {
    min = v3;
    max = vm;
}

if(max > min*2 || no) {
    print('-1');
} else {
    print(v1);
    print(v2);
    print(max);
}

mas=readline().split(' ');
v1=parseInt(mas[0]);
v2=parseInt(mas[1]);
v3=parseInt(mas[2]);
vm=parseInt(mas[3]);
no=false;
if(v1 <= vm*2) {
    if (vm*2+1 <= v1*2) {
        v1 = vm*2+1;
    } else {
        no=true;
    }
}
if(v2 <= vm*2) {
    if (vm*2+1 <= v2*2) {
        v2 = vm*2+1;
    } else {
        no=true;
    }
}
if(v3 > vm) {
    min = vm;
    max = v3;
} else {
    min = v3;
    max = vm;
}

if(max > min*2 || no) {
    print('-1');
} else {
    print(v1);
    print(v2);
    print(max);
}

mas=readline().split(' ');
v1=parseInt(mas[0]);
v2=parseInt(mas[1]);
v3=parseInt(mas[2]);
vm=parseInt(mas[3]);
if(v3 > vm) {
    min = vm;
    max = v3;
} else {
    min = v3;
    max = vm;
}

if(max > min*2) {
    print('-1');
} else {
    print(v1);
    print(v2);
    print(max);
}

var line = readline();
var bears = line.split(' ').map(function(x) {return parseInt(x)});
var big = 2 * bears[0];
var medium = Math.min(2 * bears[1], big - 1);
var small = Math.min(2 * bears[2], 2 * bears[3], medium - 1);

if (bears[1] > medium || bears[2] > small || bears[3] > small) {
    print(-1);
} else {
  print(big);
print(medium);
print(small);
}


You are given a sequence of integers of length $$$n$$$ and integer number $$$k$$$. You should print any integer number $$$x$$$ in the range of $$$[1; 10^9]$$$ (i.e. $$$1 \le x \le 10^9$$$) such that exactly $$$k$$$ elements of given sequence are less than or equal to $$$x$$$.Note that the sequence can contain equal elements.If there is no such $$$x$$$, print "-1" (without quotes).

The first line of the input contains integer numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le n$$$). The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the sequence itself.

Print any integer number $$$x$$$ from range $$$[1; 10^9]$$$ such that exactly $$$k$$$ elements of given sequence is less or equal to $$$x$$$. If there is no such $$$x$$$, print "-1" (without quotes).

NoteIn the first example $$$5$$$ is also a valid answer because the elements with indices $$$[1, 3, 4, 6]$$$ is less than or equal to $$$5$$$ and obviously less than or equal to $$$6$$$.In the second example you cannot choose any number that only $$$2$$$ elements of the given sequence will be less than or equal to this number because $$$3$$$ elements of the given sequence will be also less than or equal to this number.

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

let stdinInput = '';

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

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

function main(data) {
    data = data.split(/\r?\n/);
    const split = data[0].split(" ");
    const count = split[0]
    const k = split[1]
    const n = data[1]

    solve(n,k,count)
}

function solve(n, k, count) {
    let sorted = n.split(" ").map( x => x * 1).sort((a,b) => a - b)
    if (k === "0" && sorted[0] > 1) {
        console.log(sorted[0] - 1)
        return
    }

    if (k === "0" ||
        sorted.length < k ||
        sorted[k-1] === sorted[k] ||
        sorted[k - 1] < 1) {
        console.log(-1)
    } else {
        console.log(sorted[k - 1])
    }
}

// https://codeforces.com/problemset/problem/977/C
// Big O:
// Time complexity:
// Space complexity:

const readline = require("readline");

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

let kValue;
rl.on('line', (input) => {
    if (kValue != undefined) {
        const numbers = input.split(" ").map(Number);
        console.log(findLessOrEqual(numbers, kValue));
        rl.close();
    } else {
        kValue = parseInt(input.split(" ")[1]);
    }
});

// Problem
function findLessOrEqual(numbers, kValue) {
    const orderedNumbers = numbers.sort((a, b) => a - b);

    if (kValue === numbers.length) {
        return numbers[kValue - 1];
    }

    const numberAtKPos = orderedNumbers[kValue];
    const lessOrEqualValue = numberAtKPos - 1;

    if (lessOrEqualValue === 0) {
        return -1;
    }

    if (kValue === 0) {
        return numberAtKPos > lessOrEqualValue ? lessOrEqualValue : -1;
    }

    const index = kValue - 1;
    const comparisonNumber = orderedNumbers[index];
    return comparisonNumber <= lessOrEqualValue ? comparisonNumber : -1;
}

// https://codeforces.com/problemset/problem/977/C
// Big O:
// Time complexity: O(n*log(n))
// Space complexity: O(n)

const readline = require("readline");

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

let kValue;
rl.on('line', (input) => {
    if (kValue != undefined) {
        const numbers = input.split(" ").map(Number);
        console.log(findLessOrEqual(numbers, kValue));
        rl.close();
    } else {
        kValue = parseInt(input.split(" ")[1]);
    }
});

// Problem
function findLessOrEqual(numbers, kValue) {
    const orderedNumbers = numbers.sort((a, b) => a - b);

    if (kValue === numbers.length) {
        return numbers[kValue - 1];
    }

    const numberAtKPos = orderedNumbers[kValue];
    const comparisonValue = numberAtKPos - 1;

    if (comparisonValue === 0) {
        return -1;
    }

    if (kValue === 0) {
        return comparisonValue;
    }

    const previousNumber = orderedNumbers[kValue - 1];
    return previousNumber <= comparisonValue ? previousNumber : -1;
}

var args = readline().split(' ').map((s) => parseInt(s, 10));

var length = args[0];
var k = args[1];
var arr = readline().split(' ').map((s) => parseInt(s, 10));

function main(length, k, arr) {
    var sorted = arr.sort((a, b) => a - b);

    if (k === 0) {
        var smallest = arr[k];

        return smallest > 1 ? smallest - 1 : -1;
    }

    var border = arr[k - 1];

    if (border === arr[k]) {
        return -1;
    }

    return border;
}

print(main(length, k, arr));

var s = readline().split(' ');
var n = +s[0];
var k = +s[1]
var a = readline().split(' ');
a.sort(function(a, b){return a-b});
if(k == 0){
    if(a[0] > 1){
        print('1');
    } else{
        print('-1');
    }
} else if(k < n && a[k-1] == a[k]){
    print('-1');
} else{
    print(a[k-1]);
}

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

let stdinInput = '';

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

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

function main(data) {
    data = data.split(/\r?\n/);
    const split = data[0].split(" ");
    const count = split[0]
    const k = split[1]
    const n = data[1]

    solve(n,k,count)
}

function solve(n, k, count) {
    let sorted = n.split(" ").map( x => x * 1).sort((a,b) => a - b)
    if (sorted.length < k ||
        sorted[k-1] === sorted[k] || k === 0) {
        console.log(-1)
    } else {
        console.log(sorted[k - 1])
    }
}

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

let stdinInput = '';

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

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

function main(data) {
    data = data.split(/\r?\n/);
    const split = data[0].split(" ");
    const count = split[0]
    const k = split[1]
    const n = data[1]

    solve(n,k,count)
}

function solve(n, k, count) {
    let sorted = n.split(" ").map( x => x * 1).sort((a,b) => a - b)
    if (k === "0" && sorted[0] > 1) {
        console.log(sorted[0] - 1)
        return
    }

    if (sorted.length < k ||
        sorted[k-1] === sorted[k] ||
        sorted[k - 1] <= 1) {
        console.log(-1)
    } else {
        console.log(sorted[k - 1])
    }
}

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

let stdinInput = '';

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

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

function main(data) {
    data = data.split(/\r?\n/);
    const split = data[0].split(" ");
    const count = split[0]
    const k = split[1]
    const n = data[1]

    solve(n,k,count)
}

function solve(n, k, count) {
    let sorted = n.split(" ").map( x => x * 1).sort((a,b) => a - b)
    if (sorted.length < k ||
        sorted[k-1] === sorted[k] || k === "0") {
        console.log(-1)
    } else {
        console.log(sorted[k - 1])
    }
}

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

let stdinInput = '';

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

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

function main(data) {
    data = data.split(/\r?\n/);
    const split = data[0].split(" ");
    const count = split[0]
    const k = split[1]
    const n = data[1]

    solve(n,k,count)
}

function solve(n, k, count) {
    let sorted = n.split(" ").map( x => x * 1).sort((a,b) => a - b)
    if (k === "0" && sorted[0] > 1) {
        console.log(sorted[0] - 1)
        return
    }

    if (k === "0" ||
        sorted.length < k ||
        sorted[k-1] === sorted[k] ||
        sorted[k - 1] <= 1) {
        console.log(-1)
    } else {
        console.log(sorted[k - 1])
    }
}

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

let stdinInput = '';

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

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

function main(data) {
    data = data.split(/\r?\n/);
    const split = data[0].split(" ");
    const count = split[0]
    const k = split[1]
    const n = data[1]

    solve(n,k,count)
}

function solve(n, k, count) {
    let sorted = n.split(" ").map( x => x * 1).sort((a,b) => a - b)
    if (k === "0" && sorted[0] >= 1) {
        console.log(sorted[0] - 1)
        return
    } else {
        console.log(-1)
        return
    }

    if (sorted.length < k ||
        sorted[k-1] === sorted[k] ||
        sorted[k - 1] <= 1) {
        console.log(-1)
    } else {
        console.log(sorted[k - 1])
    }
}

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

let stdinInput = '';

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

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

function main(data) {
    data = data.split(/\r?\n/);
    const split = data[0].split(" ");
    const count = split[0]
    const k = split[1]
    const n = data[1]

    solve(n,k,count)
}

function solve(n, k, count) {
    let sorted = n.split(" ").map( x => x * 1).sort((a,b) => a - b)
    if (k === "0" && sorted[0] >= 1) {
        console.log(sorted[0] - 1)
        return
    }

    if (sorted.length < k ||
        sorted[k-1] === sorted[k] ||
        sorted[k - 1] <= 1) {
        console.log(-1)
    } else {
        console.log(sorted[k - 1])
    }
}

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

let stdinInput = '';

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

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

function main(data) {
    data = data.split(/\r?\n/);
    const split = data[0].split(" ");
    const count = split[0]
    const k = split[1]
    const n = data[1]

    solve(n,k,count)
}

function solve(n, k, count) {
    let sorted = n.split(" ").map( x => x * 1).sort((a,b) => a - b)
    if (sorted.length < k ||
        sorted[k-1] === sorted[k]) {
        console.log(-1)
    } else {
        console.log(sorted[k - 1])
    }
}

// https://codeforces.com/problemset/problem/977/C
// Big O:
// Time complexity:
// Space complexity:

const readline = require("readline");

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

let kValue;
rl.on('line', (input) => {
    if (kValue != undefined) {
        const numbers = input.split(" ").map(Number);
        console.log(findLessOrEqual(numbers, kValue));
        rl.close();
    } else {
        kValue = parseInt(input.split(" ")[1]);
    }
});

// Problem
function findLessOrEqual(numbers, kValue) {
    const orderedNumbers = numbers.sort((a, b) => a - b);
    const numberAtKIndex = orderedNumbers[kValue - 1];
    const isKValidIndex = kValue < numbers.length
    const isNextNumberLessThanK = isKValidIndex && orderedNumbers[kValue] <= numberAtKIndex ? true : false;
    const isNumberHigherThanK = numberAtKIndex >= kValue
    return isNumberHigherThanK && !isNextNumberLessThanK ? numberAtKIndex : -1;
}

// https://codeforces.com/problemset/problem/977/C
// Big O:
// Time complexity:
// Space complexity:

const readline = require("readline");

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

let kValue;
rl.on('line', (input) => {
    if (kValue) {
        const numbers = input.split(" ").map(Number);
        console.log(findLessOrEqual(numbers, kValue));
        rl.close();
    } else {
        kValue = input.split(" ")[1];
    }
});

// Problem
function findLessOrEqual(numbers, kValue) {
    if (kValue === 0) {
        return -1;
    }
    const orderedNumbers = numbers.sort((a, b) => a - b);
    const numberAtKValueIndex = orderedNumbers[kValue - 1];
    const isThereANextNumber = kValue < numbers.length
    const isNextNumberLessThanK = isThereANextNumber && orderedNumbers[kValue] <= numberAtKValueIndex ? true : false;
    return kValue <= numberAtKValueIndex && !isNextNumberLessThanK ? numberAtKValueIndex : -1;
}

// https://codeforces.com/problemset/problem/977/C
// Big O:
// Time complexity:
// Space complexity:

const readline = require("readline");

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

let kValue;
rl.on('line', (input) => {
    if (kValue) {
        const numbers = input.split(" ").map(Number);
        console.log(findLessOrEqual(numbers, kValue));
        rl.close();
    } else {
        kValue = parseInt(input.split(" ")[1]);
    }
});

// Problem
function findLessOrEqual(numbers, kValue) {
    if (kValue === 0) {
        return -1;
    }
    const orderedNumbers = numbers.sort((a, b) => a - b);
    const numberAtKIndex = orderedNumbers[kValue - 1];
    const isKValidIndex = kValue < numbers.length
    const isNextNumberLessThanK = isKValidIndex && orderedNumbers[kValue] <= numberAtKIndex ? true : false;
    const isNumberHigherThanK = numberAtKIndex >= kValue
    return isNumberHigherThanK && !isNextNumberLessThanK ? numberAtKIndex : -1;
}

// https://codeforces.com/problemset/problem/977/C
// Big O:
// Time complexity:
// Space complexity:

const readline = require("readline");

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

let kValue;
rl.on('line', (input) => {
    if (kValue) {
        const numbers = input.split(" ").map(Number);
        console.log(findLessOrEqual(numbers, kValue));
        rl.close();
    } else {
        kValue = input.split(" ")[1];
    }
});

// Problem
function findLessOrEqual(numbers, kValue) {
    const orderedNumbers = numbers.sort((a, b) => a - b);
    const numberAtKValueIndex = orderedNumbers[kValue - 1];
    const isThereANextNumber = kValue < numbers.length
    const isNextNumberLessThanK = isThereANextNumber && orderedNumbers[kValue] <= numberAtKValueIndex ? true : false;
    return kValue <= numberAtKValueIndex && !isNextNumberLessThanK ? numberAtKValueIndex : -1;
}

// https://codeforces.com/problemset/problem/977/C
// Big O:
// Time complexity:
// Space complexity:

const readline = require("readline");

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

let kValue;
rl.on('line', (input) => {
    if (kValue) {
        const numbers = input.split(" ").map(Number);
        console.log(findLessOrEqual(numbers, kValue));
        rl.close();
    } else {
        kValue = parseInt(input.split(" ")[1]);
    }
});

// Problem
function findLessOrEqual(numbers, kValue) {
    if (kValue === 0) {
        return -1;
    }
    const orderedNumbers = numbers.sort((a, b) => a - b);
    const numberAtKValue = orderedNumbers[kValue - 1];
    const isKValidIndex = kValue < numbers.length
    const isNextNumberHigherThanK = isKValidIndex && orderedNumbers[kValue] > numberAtKValue ? false : true;
    const isNumberHigherThanK = numberAtKValue >= kValue
    return isNumberHigherThanK && isNextNumberHigherThanK ? numberAtKValue : -1;
}

// https://codeforces.com/problemset/problem/977/C
// Big O:
// Time complexity:
// Space complexity:

const readline = require("readline");

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

let kValue;
rl.on('line', (input) => {
    if (kValue != undefined) {
        const numbers = input.split(" ").map(Number);
        console.log(findLessOrEqual(numbers, kValue));
        rl.close();
    } else {
        kValue = parseInt(input.split(" ")[1]);
    }
});

// Problem
function findLessOrEqual(numbers, kValue) {
    const orderedNumbers = numbers.sort((a, b) => a - b);
    const numberAtKPos = orderedNumbers[kValue];
    const lessOrEqualValue = numberAtKPos - 1;

    if (lessOrEqualValue === 0) {
        return -1;
    }

    if (kValue === 0) {
        return numberAtKPos > lessOrEqualValue ? lessOrEqualValue : -1;
    }

    const index = kValue - 1;
    const comparisonNumber = orderedNumbers[index];
    return comparisonNumber <= lessOrEqualValue ? comparisonNumber : -1;
}

// https://codeforces.com/problemset/problem/977/B
// Big O:
// Time complexity: O(n)
// Space complexity: O(n)

const readline = require("readline");

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

let stringLength;
rl.on('line', (input) => {
    if (stringLength) {
        console.log(findMostCommonGram(input, stringLength));
        rl.close();
    } else {
        stringLength = input;
    }
});

// Problem
function findMostCommonGram(string, stringLength) {
    let mostCommonGram = "";
    let mostCommonGramOccurrences = 0;
    const gramOccurrences = {};

    for (let i = 0; i < stringLength - 1; i++) {
        const twogram = string[i] + string[i + 1];
        const occurrences = gramOccurrences[twogram] ? gramOccurrences[twogram] + 1 : 1;
        const currentOcurrences = occurrences + 1;
        if (currentOcurrences > mostCommonGramOccurrences) {
            mostCommonGram = twogram;
            mostCommonGramOccurrences = currentOcurrences;
        }

        gramOccurrences[twogram] = currentOcurrences;
    }

    return mostCommonGram;
}

var args = readline().split(' ').map((s) => parseInt(s, 10));

var length = args[0];
var k = args[1];
var arr = readline().split(' ').map((s) => parseInt(s, 10));

function main(length, k, arr) {
    var sorted = arr.sort((a, b) => a - b);

    var border = arr[k - 1];

    if (border === arr[k]) {
        return -1;
    }

    return border;
}

print(main(length, k, arr));

var args = readline().split(' ').map((s) => parseInt(s, 10));

var length = args[0];
var k = args[1];
var arr = readline().split(' ').map((s) => parseInt(s, 10));

function main(length, k, arr) {
    if (k === 0) {
        return -1;
    }

    var sorted = arr.sort((a, b) => a - b);

    var border = arr[k - 1];

    if (border === arr[k]) {
        return -1;
    }

    return border;
}

print(main(length, k, arr));

var s = readline().split(' ');
var n = +s[0];
var k = +s[1]
var a = readline().split(' ');
a.sort(function(a, b){return a-b});
if(k < n && a[k-1] == a[k] || k == 0){
    print('-1');
} else{
    print(a[k-1]);
}

var s = readline().split(' ');
var n = +s[0];
var k = +s[1]
var a = readline().split(' ');
a.sort(function(a, b){return a-b});
if(k < n && a[k-1] == a[k]){
    print('-1');
} else{
    print(a[k-1]);
}