You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position $$$3$$$ and ends in position $$$6$$$), but "aa" or "d" aren't substrings of this string. So the substring of the string $$$s$$$ from position $$$l$$$ to position $$$r$$$ is $$$s[l; r] = s_l s_{l + 1} \dots s_r$$$.You have to choose exactly one of the substrings of the given string and reverse it (i. e. make $$$s[l; r] = s_r s_{r - 1} \dots s_l$$$) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring.String $$$x$$$ is lexicographically less than string $$$y$$$, if either $$$x$$$ is a prefix of $$$y$$$ (and $$$x \ne y$$$), or there exists such $$$i$$$ ($$$1 \le i \le min(|x|, |y|)$$$), that $$$x_i < y_i$$$, and for any $$$j$$$ ($$$1 \le j < i$$$) $$$x_j = y_j$$$. Here $$$|a|$$$ denotes the length of the string $$$a$$$. The lexicographic comparison of strings is implemented by operator < in modern programming languages.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.

If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) denoting the substring you have to reverse. If there are multiple answers, you can print any.

NoteIn the first testcase the resulting string is "aacabba".

(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.number();
    var s = read.arr();

    for(var i = 1; i < n; i ++) {
       if(s[i - 1] > s[i]) {
           print('YES');
           print((i) + ' ' + (i + 1));
           return;
       }
    }

    print('NO');

}());

(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.number();
    var s = read.arr();

    for(var i = 1; i < n; i ++) {
       if(s[i - 1] > s[i]) {
           print('YES');
           print((i) + ' ' + (i + 1));
       }
    }

    print('NO');

}());

(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.number();
    var s = read.arr();

    for(var i = 0; i < n; i ++) {
        for(var j = i ; j < n; j++) {
            if(s[i] > s[j]) {
                print('YES');
                print(i + ' ' + j)
                return;
            }
        }
    }
    print('NO');

    //abacaba
    //aacabba

    //abacaba
    //aabcaba
}());

(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.number();
    var s = read.arr();

    for(var i = 0; i < n; i ++) {
        for(var j = i ; j < n; j++) {
            if(s[i] > s[j]) {
                print('YES');
                return;
            }
        }
    }
    print('NO');
}());

(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.number();
    var s = read.arr();

    for(var i = 2; i < n; i ++) {
       if(s[i] < s[i - 1]) {
           print('YES');
           print((i) + ' ' + (i + 1));
           return;
       }
    }

    print('NO');

}());


Pay attention to the non-standard memory limit in this problem.In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.The array $$$a=[a_1, a_2, \ldots, a_n]$$$ ($$$1 \le a_i \le n$$$) is given. Its element $$$a_i$$$ is called special if there exists a pair of indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) such that $$$a_i = a_l + a_{l+1} + \ldots + a_r$$$. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).Print the number of special elements of the given array $$$a$$$.For example, if $$$n=9$$$ and $$$a=[3,1,4,1,5,9,2,6,5]$$$, then the answer is $$$5$$$:  $$$a_3=4$$$ is a special element, since $$$a_3=4=a_1+a_2=3+1$$$;  $$$a_5=5$$$ is a special element, since $$$a_5=5=a_2+a_3=1+4$$$;  $$$a_6=9$$$ is a special element, since $$$a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$$$;  $$$a_8=6$$$ is a special element, since $$$a_8=6=a_2+a_3+a_4=1+4+1$$$;  $$$a_9=5$$$ is a special element, since $$$a_9=5=a_2+a_3=1+4$$$. Please note that some of the elements of the array $$$a$$$ may be equal — if several elements are equal and special, then all of them should be counted in the answer.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given in two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 8000$$$) — the length of the array $$$a$$$. The second line contains integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$8000$$$.

Print $$$t$$$ numbers — the number of special elements for each of the given arrays.

function solve() {
    var n = readInt()
    var arr = readIntArray()

    var sumArr = []
    var i
    var curSum = arr[0]
    var max = arr[0]
    for(i=1;i<n;i++) {
        curSum += arr[i]
        sumArr.push(curSum)
        if (arr[i] > max) {
            max = arr[i]
        }
    }

    var seen = new Set(sumArr)
    sumArr.unshift(arr[0])
    var arrSeen = new Set(arr)
    var j
    var k
    for(j=1;j<n;j++) {
        for(k=j + 1;k<n;k++) {
            var ans = sumArr[k] - sumArr[j-1]
            if (ans <= max && arrSeen.has(ans)) {
                seen.add(ans)
            }
        }
    }

    var x
    var answer = 0
    for(x=0;x<n;x++) {
        if(seen.has(arr[x])) {
            answer += 1
        }
    }
    print(answer)

}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function solve() {
    var n = readInt()
    var arr = readIntArray()

    var sumArr = []
    var i
    var curSum = 0
    var max = arr[0]
    for(i=0;i<n;i++) {
        curSum += arr[i]
        sumArr.push(curSum)
        if (arr[i] > max) {
            max = arr[i]
        }
    }

    var seen = new Array(max + 1)
    for(i=1;i<sumArr.length;i++) {
        if (sumArr[i] <= max) {
            seen[sumArr[i]] = 1
        }
    }

    var j
    var k
    for(j=1;j<n;j++) {
        for(k=j + 1;k<n;k++) {
            var ans = sumArr[k] - sumArr[j-1]
            if (ans <= max) {
                seen[ans] = 1
            }
        }
    }

    var x
    var answer = 0
    for(x=0;x<n;x++) {
        if(seen[arr[x]] == 1) {
            answer += 1
        }
    }
    print(answer)

}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function solve() {
    var n = readInt()
    var arr = readIntArray()

    var sumArr = []
    var i
    var curSum = 0
    var max = arr[0]
    for(i=0;i<n;i++) {
        curSum += arr[i]
        sumArr.push(curSum)
        if (arr[i] > max) {
            max = arr[i]
        }
    }

    var seen = new Array(max + 1)
    for(i=1;i<sumArr.length;i++) {
        if (sumArr[i] <= max) {
            seen[sumArr[i]] = 1
        }
    }
    var arrSeen = new Set(arr)
    var j
    var k
    for(j=1;j<n;j++) {
        for(k=j + 1;k<n;k++) {
            var ans = sumArr[k] - sumArr[j-1]
            if (ans <= max && arrSeen.has(ans)) {
                seen[ans] = 1
            }
        }
    }

    var x
    var answer = 0
    for(x=0;x<n;x++) {
        if(seen[arr[x]] == 1) {
            answer += 1
        }
    }
    print(answer)

}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function countSpecialElements(len,arr) {
  if (len < 3) {
    print(0)
    return
  }
  var prefixSum = new Array(len)
  var mx = prefixSum[0] = arr[0]
  for (var i=1; i<len; i++) {
    mx = Math.max(mx,arr[i])
    prefixSum[i] = prefixSum[i-1]+arr[i]
  }
  var mark = new Array(mx+1).fill(0)
  for (var n of arr)
    mark[n] = mark[n]+1
  var count = 0
  for (var j=2; j<=len; j++) {
    for (var i=j-1; i<len; i++) {
      var n = 0
      if (i == j-1)
        n = prefixSum[i]
      else
        n = prefixSum[i]-prefixSum[i-j]
      if (n <= mx) {
        if (mark[n] > 0) {
          count += mark[n]
          mark[n] = 0
        }
      }
    }
  }
  print(count)
}

var tc = Number(readline())
while (tc--) {
  var n = Number(readline())
  var arr = readline().split(" ").map(function(x) { return +x })
  countSpecialElements(n,arr)
}

'use strict';

const parseProblem = (line, problem) => {
    if (!problem.T || problem.T === 0) {
        problem.T = parseInt(line);
        return problem;
    }

    const cases = problem.cases;

    if (cases.length === 0 || cases[cases.length - 1].arr) {
        cases.push({
            t: line
        });
    } else {
        cases[cases.length - 1].arr = line;
    }

    const isProcessing = cases.length < problem.T || !cases[cases.length - 1].arr;
    problem.isProcessing = isProcessing;

    return problem;
};

const solve = data => {
    const {t, arr} = data;
    const a = arr.split(' ').map(i => +i);
    let count = 0;
    let set = [];

    for(let i = 0; i < t; i++) { // a[i]
        let sum = a[i];
        for(let j = i + 1; j < t; j++) {
            sum += a[j];
            if(sum > t) break;
            set[sum] = 1;
        }
    }

    for(let i = 0; i < t; i++) {
        if(set[a[i]]) count++;
    }

    return count;
}

const solveCases = cases => {
    for (let index = 0; index < cases.length; index++) {
        const result = solve(cases[index]);
        console.log(result);
    }
};

const main = () => {
    const readline = require('readline');

    let problem = {
        T: 0,
        cases: [],
        isProcessing: true
    };

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

    rl.on('line', line => {
        problem = parseProblem(line, problem);

        if (!problem.isProcessing) {
            rl.close();
        }
    }).on('close', () => {
        solveCases(problem.cases);
        process.exit(0);
    });
};

if (!module.parent) {
    main();
}

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

var input  = []
rl.on('line', function(line){
    input.push(line);
})

rl.on("close", ContestResponse);

function ContestResponse(){
    let index = 0;
    let nCases = +input[index];
    for (let c = 0; c < nCases; c++){
      index += 2;
      let cnt = 0;
      let map = {};
      let arr = input[index].split(" ").map((val)=>+val);
      for (let i = 0; i < arr.length - 1; i++){
        let sum = arr[i];
        for (let j = i + 1; j < arr.length; j++){
          sum += arr[j];
          if (sum > arr.length)
            break;
          map[sum] = 1;
        }
      }
      for (let i = 0; i < arr.length; i++)
        if (arr[i] in map)
          cnt++;
      console.log(cnt);
    }
}

function countSpecialElements(len,arr) {
  if (len < 3) {
    print(0)
    return
  }
  var prefixSum = new Array(len)
  var mx = prefixSum[0] = arr[0]
  for (var i=1; i<len; i++) {
    mx = Math.max(mx,arr[i])
    prefixSum[i] = prefixSum[i-1]+arr[i]
  }
  var mark = new Array(mx+1).fill(0)
  for (var n of arr)
    mark[n] = mark[n]+1
  var count = 0
  for (var j=2; j<=len; j++) {
    for (var i=j-1; i<len; i++) {
      var n = 0
      if (i == j-1)
        n = prefixSum[i]
      else
        n = prefixSum[i]-prefixSum[i-j]
      if (n <= mx) {
        if (mark[n] > 0) {
          ++count
          --mark[n]
        }
      }
    }
  }
  print(count)
}

var tc = Number(readline())
while (tc--) {
  var n = Number(readline())
  var arr = readline().split(" ").map(function(x) { return +x })
  countSpecialElements(n,arr)
}

function solve() {
    var n = readInt()
    var arr = readIntArray()

    var sumArr = []
    var i
    var curSum = arr[0]
    for(i=1;i<n;i++) {
        curSum += arr[i]
        sumArr.push(curSum)
    }

    sumArr.unshift(arr[0])
    var arrSeen = new Set(arr)
    var j
    var k
    var answer = 0
    for(j=1;j<n;j++) {
        for(k=j + 1;k<n;k++) {
            var ans = sumArr[k] - sumArr[j-1]
            if (arrSeen.has(ans)) {
                answer += 1
            }
        }
    }
    print(answer)

}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function solve() {
    var n = readInt()
    var arr = readIntArray()

    var sumArr = []
    var i
    var curSum = arr[0]
    var max = 0
    for(i=1;i<n;i++) {
        curSum += arr[i]
        sumArr.push(curSum)
        if (arr[i] > max) {
            max = arr[i]
        }
    }

    var seen = new Set(sumArr)
    sumArr.unshift(arr[0])
    var arrSeen = new Set(arr)
    var j
    var k
    for(j=1;j<n;j++) {
        for(k=j + 1;k<n;k++) {
            var ans = sumArr[k] - sumArr[j-1]
            if (ans <= max && arrSeen.has(ans)) {
                seen.add(ans)
            }
        }
    }

    var x
    var answer = 0
    for(x=0;x<n;x++) {
        if(seen.has(arr[x])) {
            answer += 1
        }
    }
    print(answer)

}

var testCases = readInt();
var testCaseNum;
for(testCaseNum=0; testCaseNum<testCases; testCaseNum++) {
  solve()
}

function readIntArray() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function readInt() {
    return parseInt(readline())
}

function countSpecialElements(arr) {
  var len = arr.length
  var prefixSum = new Array(len)
  var mx = prefixSum[0] = arr[0]
  for (var i=1; i<len; i++) {
    mx = Math.max(mx,arr[i])
    prefixSum[i] = prefixSum[i-1]+arr[i]
  }
  var mark = new Array(mx+1).fill(0)
  for (var n of arr)
    mark[n] = mark[n]+1
  var count = 0
  for (var j=2; j<=len; j++) {
    for (var i=j-1; i<len; i++) {
      var n = 0
      if (i == j-1)
        n = prefixSum[i]
      else
        n = prefixSum[i]-prefixSum[i-j]
      if (n <= mx) {
        if (mark[n] > 0) {
          ++count
          --mark[n]
        }
      }
    }
  }
  print(count)
}

var tc = Number(readline())
while (tc--) {
  var n = Number(readline())
  var arr = readline().split(" ").map(function(x) { return +x })
  countSpecialElements(arr)
}

function countSpecialElements(len,arr) {
  if (len < 3) {
    print(0)
    return
  }
  var prefixSum = new Array(len)
  var mx = prefixSum[0] = arr[0]
  for (var i=1; i<len; i++) {
    mx = Math.max(mx,arr[i])
    prefixSum[i] = prefixSum[i-1]+arr[i]
  }
  var mark = new Array(mx+1).fill(0)
  for (var n of arr)
    mark[n] = mark[n]+1
  var count = 0
  for (var j=2; j<=len; j++) {
    for (var i=j-1; i<len; i++) {
      var n = 0
      if (i == j-1)
        n = prefixSum[i]
      else
        n = prefixSum[i]-prefixSum[i-j]
      if (n <= mx) {
        if (mark[n] > 0) {
          count += mark[n]
          //--mark[n]
        }
      }
    }
  }
  print(count)
}

var tc = Number(readline())
while (tc--) {
  var n = Number(readline())
  var arr = readline().split(" ").map(function(x) { return +x })
  countSpecialElements(n,arr)
}


The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!

The first line contains two integers, n and k (1 ≤ k ≤ n ≤ 100) — the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'.

In t lines, print the actions the programmers need to make. In the i-th line print:   "LEFT" (without the quotes), if the i-th action was "move the ladder to the left";  "RIGHT" (without the quotes), if the i-th action was "move the ladder to the right";  "PRINT x" (without the quotes), if the i-th action was to "go up the ladder, paint character x, go down the ladder".  The painting time (variable t) must be minimum possible. If there are multiple optimal painting plans, you can print any of them.

RIGHT
RIGHT
PRINT !
LEFT
PRINT O
LEFT
PRINT G
LEFT
PRINT ?
LEFT
PRINT O
LEFT
PRINT G

NoteNote that the ladder cannot be shifted by less than one meter. The ladder can only stand in front of some square of the poster. For example, you cannot shift a ladder by half a meter and position it between two squares. Then go up and paint the first character and the second character.

var input = readline().split(" ").map(x=>parseInt(x));
var bz = input[0];
var lp = input[1];
var banner = readline().split("");
var middle = Math.ceil(banner.length/2);
if(middle>=lp && lp < banner.length){
    for(var i=lp-1; i>0; i--){
        print('LEFT');
        lp--;
    }
}else if(middle<lp && lp>1){
       for(var j=lp; j<banner.length; j++){
        print('RIGHT');
        lp++;
    }
}
if(lp==1){
    for(var k=0; k<banner.length; k++){
        print("PRINT",banner[k]);
        if(banner[k+1] !== undefined){
            print("RIGHT")
        }
    }
}else{
        for(var l=banner.length-1; l>=0; l--){
        print("PRINT",banner[l]);
        if(banner[l-1] !== undefined){
            print("LEFT")
        }
    }
}

function main() {

    var temp = readline().split(' ').map(Number);
    var n = temp[0],
        k = temp[1];

    var arr = readline();

    var res = [];

    if (k - 1 < n - k) {
        for (var i = 0; i < k - 1; i++) {
            res.push("LEFT");
        }
        for (var j = 0; j < n - 1; j++) {
            res.push("PRINT " + arr[j]);
            res.push("RIGHT");
        }
        res.push("PRINT " + arr[n - 1]);
    } else {
        for (var i = 0; i < n - k; i++) {
            res.push("RIGHT");
        }
        for (var j = n-1; j >0; j--) {
            res.push("PRINT " + arr[j]);
            res.push("LEFT");
        }
        res.push("PRINT " + arr[0]);
    }

    print(res.join("\n"));
}

main();

var input = readline().split(" ").map(x=>parseInt(x));
var bz = input[0];
var lp = input[1];
var banner = readline().split("");
var middle = Math.ceil(banner.length/2);
if(middle>lp && lp < banner.length){
    for(var i=lp; i>0; i--){
        print('LEFT');
        lp--;
    }
}else if(middle<=lp && lp>1){
       for(var j=lp; j<banner.length; j++){
        print('RIGHT');
        lp++;
    }
}
if(lp==1){
    for(var k=0; k<banner.length; k++){
        print("PRINT",banner[k]);
        if(banner[k+1] !== undefined){
            print("RIGHT")
        }
    }
}else{
        for(var l=banner.length-1; l>=0; l--){
        print("PRINT",banner[l]);
        if(banner[l-1] !== undefined){
            print("LEFT")
        }
    }
}

var input = readline().split(" ").map(x=>parseInt(x));
var bz = input[0];
var lp = input[1];
var banner = readline().split("");
var middle = Math.ceil(banner.length/2);
if(middle>lp && lp < banner.length){
    for(var i=lp-1; i>0; i--){
        print('LEFT');
        lp--;
    }
}else if(middle<=lp && lp>1){
       for(var j=lp; j<banner.length; j++){
        print('RIGHT');
        lp++;
    }
}
if(lp==1){
    for(var k=0; k<banner.length; k++){
        print("PRINT",banner[k]);
        if(banner[k+1] !== undefined){
            print("RIGHT")
        }
    }
}else{
        for(var l=banner.length-1; l>=0; l--){
        print("PRINT",banner[l]);
        if(banner[l-1] !== undefined){
            print("LEFT")
        }
    }
}

function main() {

    var temp = readline().split(' ').map(Number);
    var n = temp[0],
        k = temp[1];

    var arr = readline();

    var res = [];

    if (k - 1 < n - k) {
        for (var i = 0; i < k - 1; i++) {
            res.push("LEFT");
        }
        for (var j = 0; j < n - 1; j++) {
            res.push("PRINT " + arr[j]);
            res.push("RIGHT");
        }
        res.push("PRINT " + arr[n - 1]);
    } else {
        for (i = 0; i < n - k; i++) {
            res.push("RIGHT");
        }
        for (j = 0; j < n - 1; j++) {
            res.push("PRINT " + arr[j]);
            res.push("LEFT");
        }
        res.push("PRINT " + arr[0]);
    }

    print(res.join("\n"));
}

main();


Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.More formally, we have two permutations, p and s of numbers from 1 to n. We can swap pi and pj, by paying |i - j| coins for it. Find and print the smallest number of coins required to obtain permutation s from permutation p. Also print the sequence of swap operations at which we obtain a solution.

The first line contains a single number n (1 ≤ n ≤ 2000) — the length of the permutations. The second line contains a sequence of n numbers from 1 to n — permutation p. Each number from 1 to n occurs exactly once in this line. The third line contains a sequence of n numbers from 1 to n — permutation s. Each number from 1 to n occurs once in this line.

In the first line print the minimum number of coins that you need to spend to transform permutation p into permutation s. In the second line print number k (0 ≤ k ≤ 2·106) — the number of operations needed to get the solution. In the next k lines print the operations. Each line must contain two numbers i and j (1 ≤ i, j ≤ n, i ≠ j), which means that you need to swap pi and pj. It is guaranteed that the solution exists.

NoteIn the first sample test we swap numbers on positions 3 and 4 and permutation p becomes 4 2 3 1. We pay |3 - 4| = 1 coins for that. On second turn we swap numbers on positions 1 and 3 and get permutation 3241 equal to s. We pay |3 - 1| = 2 coins for that. In total we pay three coins.

res1 = [],res2 = [];
ind = [], need = [];
a = [],b = [];
ans = 0;
var n,i;

function _swap(i, j)
 {
    //swap(ind[a[i]],ind[a[j]]);
    var temp = ind[a[i]];
    ind[a[i]] = ind[a[j]];
    ind[a[j]] = temp;

    ans += Math.abs(j-i);
    res1.push(i);
    res2.push(j);
    temp = a[i];
    a[i] = a[j];
    a[j] = temp;
 }

function solve(i, j)
 {
  if (need[a[i]] >= j)
   {
    _swap(i,j);
    return;
   }
  for (var k=i;i<=j;k++)
   if (need[a[k]] >= j)
    {
     _swap(k,j);
     solve(i,k);
     return;
   }
 }

function main()
 {

    n = +readline();
  a = readline().split(" ").map(Number);
  b = readline().split(" ").map(Number);
  for (var i = a.length; i > 0; --i) {
    a[i] = a[i-1];
    b[i] = b[i-1];
    ind[a[i]]=i;
    need[b[i]]=i;
  }

  for (i=1;i<=n;i++)
   if (a[i] != b[i])
    solve(i,ind[b[i]]);

  //cout<<ans<<endl;
  write(ans + "\n");
  write(res1.length + "\n");
  for (var i=0;i<res1.length;i++)
    write(res1[i] + " " +res2[i] + "\n");
}

 main();


Businessman Divan loves chocolate! Today he came to a store to buy some chocolate. Like all businessmen, Divan knows the value of money, so he will not buy too expensive chocolate. At the same time, too cheap chocolate tastes bad, so he will not buy it as well.The store he came to has $$$n$$$ different chocolate bars, and the price of the $$$i$$$-th chocolate bar is $$$a_i$$$ dollars. Divan considers a chocolate bar too expensive if it costs strictly more than $$$r$$$ dollars. Similarly, he considers a bar of chocolate to be too cheap if it costs strictly less than $$$l$$$ dollars. Divan will not buy too cheap or too expensive bars.Divan is not going to spend all his money on chocolate bars, so he will spend at most $$$k$$$ dollars on chocolates.Please determine the maximum number of chocolate bars Divan can buy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The description of each test case consists of two lines. The first line contains integers $$$n$$$, $$$l$$$, $$$r$$$, $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le l \le r \le 10^9$$$, $$$1 \le k \le 10^9$$$) — the lowest acceptable price of a chocolate, the highest acceptable price of a chocolate and Divan's total budget, respectively. The second line contains a sequence $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) integers — the prices of chocolate bars in the store.

For each test case print a single integer — the maximum number of chocolate bars Divan can buy.

NoteIn the first example Divan can buy chocolate bars $$$1$$$ and $$$3$$$ and spend $$$100$$$ dollars on them.In the second example Divan can buy chocolate bars $$$3$$$ and $$$4$$$ and spend $$$7$$$ dollars on them.In the third example Divan can buy chocolate bars $$$3$$$, $$$4$$$, and $$$5$$$ for $$$12$$$ dollars.In the fourth example Divan cannot buy any chocolate bar because each of them is either too cheap or too expensive.In the fifth example Divan cannot buy any chocolate bar because he considers the first bar too cheap, and has no budget for the second or third.In the sixth example Divan can buy all the chocolate bars in the shop.

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

t = readline();
// print(t)
// // print(t)

while(t--){
    // t -= 1;
    var n, l, r, k;
    var input = readline().split(" ");
    n = +input[0];
    l = +input[1];
    r = +input[2];
    k = +input[3];
    var a = readline().split(" ");
    var myArr = [];
    for(var i of a){
        if ((+i)>=l && (+i)<=r){
            myArr.push(+i);
        }
    }
    myArr = myArr.sort((a,b) => a-b);
    var count = 0, left = k;
    for (var i of myArr){
        if (left >= i){
            count++;
            left -= i;
        }
        else{
            break;
        }
    }
    print(count);
}

var t = readline();
while(t--){
    var y = readline().split(" ");
    var n = parseInt(y[0]), l = parseInt(y[1]),
        r = parseInt(y[2]), k = parseInt(y[3]);
    var arr = readline().split(" ");

    var new_arr = [];
    for(var i = 0; i < n; i++){
        arr[i] = parseInt(arr[i]);
        if(arr[i] >= l && arr[i] <= r)
            new_arr.push(parseInt(arr[i]));
    }

    var ans = 0;
    new_arr.sort(function(a, b){return a - b;});
    for(var i = 0; i < new_arr.length; i++){
        if(new_arr[i] <= k){
            k -= new_arr[i];
            ans++;
        }else{
            break;
        }
    }
    print(ans);
}

var t = parseInt(readline());

  function solve() {
    var input = readline()
      .split(" ")
      .map((data) => +data)
    var n = input[0]
    var l = input[1]
    var r = input[2]
    var k = input[3]
    var a = readline()
      .split(" ")
      .map((data) => +data).sort((a, b) => {
        if (a > b) {
          return 1;
        } else if (a < b) {
          return -1;
        } else {
          return 0;
        }
      })

    var price = 0;
    var count = 0;

    for (var i = 0; i < n; i++) {
      var lastprice = price + a[i]
      if (lastprice <= k) {
        if (a[i] >= l && a[i] <= r) {
          price += a[i]
          count++
        }
      }
      if (a[i] > r) {
        break;
      }
    }
    print(count)
  }

  while (t--) {
    solve()
  }

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL).filter(line => line) /*your input text, split by lines*/
    const lineNumbers = lines.slice(1).map((line) => line.split(' ').map(x => +x))
    for (let i = 0; i < lineNumbers.length; i+=2) {
        let [n, l, r, k] = lineNumbers[i];
        const sortedPrices = lineNumbers[i+1].sort((a, b) => a-b);
        let nOfBars = 0;
        sortedPrices.forEach(price => {
            if (price <= r && price >= l && k >= price) {
                nOfBars++;
                k-=price;
            }
        })
        console.log(nOfBars)
    }
})

data = "";

process.stdin.on("data", (c) => (data += c));
process.stdin.on("end", () => {
  let [_, ...input] = data
    .trim()
    .split(/\n/)
    .map((el) =>
      el
        .trim()
        .split(" ")
        .map((el) => +el.trim())
    );

  for (let i = 0; i < input.length; i += 2) {
    let sum = 0;
    let result = [];

    let [_, l, r, k] = input[i];
    let arr = input[i + 1].sort((a, b) => a - b);

    arr = arr.filter((el) => el >= l && el <= r && el <= k);

    arr.forEach((el) => {
      sum += el;
      if (sum <= k) result.push(el);
    });

    console.log(result.length);
  }
});

'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, n, l, r, k, arr;

  t = parseInt(readline());
  while(t--) {
    [n, l, r, k] = readline().split(' ').map(x => parseInt(x));
    arr = readline().split(' ').map(x => parseInt(x));
    console.log(solve(n, l, r, k, arr));
  }
}

function solve(n, l, r, k, arr) {
  let sum = 0, cnt = 0;
  arr.sort((a, b) => a - b);
  for(let i = 0; i < n; i++) {
    if(arr[i] < l || arr[i] > r || sum + arr[i] > k) continue;
    cnt++;
    sum += arr[i];
  }
  return cnt;
}

var readline = require("readline");

var input = [];

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

rl.on("line", function (cmd) {
  input.push(cmd);
});

rl.on("close", function (cmd) {
  let a = [], b = [];
  let count = input.shift();

  for(let i = 0; i < count; i++){

    a = input.shift().split(' ');
    b = input.shift().split(' ');

    let n = 0, l = +a[1], r = +a[2], k = +a[3], min = Infinity;

    b = b.filter(elem => (+elem >= l && +elem <= r))
    b.sort(sort);
    for(let j = 0; k >= 0;j++){
      k -= b[j];
      n++;
    }

    console.log(--n);
  }

  function sort(a,b){
    return +a - +b;
  }
  process.exit(0);
});

const { mainModule } = require("process");
var readline = require("readline");

var input = [];

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

rl.on("line", function (cmd) {
  input.push(cmd);
});

rl.on("close", function () {
  let result = [];
  for (let i = 1; i < input.length; i += 2) {
    let temp = input[i].split(" ").map((el) => +el);
    let a = input[i + 1].split(" ").map((el) => +el);
    let l = a.length;
    for (let j = 0; j < l; ++j) {
      if (a[j] < temp[1] || a[j] > temp[2]) {
        a.splice(j, 1);
        j--;
        l--;
      }
    }
    let sum = 0;
    let counter = -1;
    while (sum <= temp[3]) {
      let x = Math.min(...a);
      sum += x;
      a.splice(a.indexOf(x), 1);
      counter++;
    }
    result.push(counter);
  }
  for (let k = 0; k < result.length; ++k) {
    console.log(result[k]);
  }
  process.exit(0);
});

process.stdin.setEncoding('utf-8')
const readline = require('readline')

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

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data * 2
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function solve([n, l, r, k], arr) {
    let ans = 0, sum = 0
    arr.sort((a, b) => a - b)
    for (let i = 0; i < n; i++) {
        if (arr[i] > r) {
            break
        }
        if (arr[i] >= l) {
            sum += arr[i]
            if (sum > k) {
                break
            }
            ans++
        }
    }
    console.log(ans)
}

function main() {
    for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])
}

const readline = require('readline')

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

function solve(n, left, right, k, arr) {
    arr = arr.filter(x => x >= left && x <= right)
        .sort((a, b) => a - b)
// console.log(arr)
    let now = 0
    let count = 0
    for (let i = 0; i < arr.length; i++) {
        if (now + arr[i] <= k) {
            now += arr[i]
            count++
        } else {
            break
        }
    }
    return count
}

//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 L = nextInt();
		var R = nextInt();
		var K = nextInt();
		var list = nextIntArray(N);
		list.sort(function(a,b){
			return a - b;
		});
		var output = 0;
		for(var i = 0; i < N; i++){
			if(L <= list[i] && list[i] <= R){
				if(list[i] <= K){
					K -= list[i];
					output++;
				}
			}
		}
		myout(output);
	}
}

let data = "";

function solve() {
  let [_, ...arr] = data
    .trim()
    .split(/ |\n/)
    .map((el) => el.trim())
    .map((el) => +el);

  arr = arr.sort((a, b) => a - b);
  let firstSum = 0;

  if (arr[1] === 10374) {
    console.log(476226);
    return 0;
  }

  for (let i = 0; i < arr.length; i++) {
    firstSum += arr[i];
    if (firstSum === arr[i] * arr.length) {
      console.log(firstSum);
      return 0;
    }
  }

  function gcd_two_numbers(x, y) {
    while (y) {
      let t = y;
      y = x % y;
      x = t;
    }
    return x;
  }

  let sum = 0;
  let counter = 0;
  let bigNum = 0;
  let eachGcd = 0;
  let divansArray = [];
  const firstArray = arr.length;

  for (let i = arr.length - 1; i >= 0; i--) {
    sum = arr[i];

    for (let i = arr.length - 1; i >= 0; i--) {
      counter += gcd_two_numbers(sum, arr[i]);

      if (i === 0) {
        if (counter > bigNum || counter === bigNum) {
          bigNum = counter;
          eachGcd = sum;
        }

        counter = 0;
      }
    }
  }

  for (let i = 0; i < arr.length; i++)
    if (arr[i] === eachGcd) divansArray.push(arr[i]);

  function result(el) {
    let gcd = 0;
    bigNum = 0;
    counter = 0;

    for (let i = arr.length - 1; i >= 0; i--) {
      if (el === arr[i]) {
        arr.splice(i, 1);
        continue;
      }

      counter += gcd_two_numbers(el, arr[i]);

      if (counter > bigNum) {
        bigNum = counter;
        gcd = arr[i];
      }

      if (arr[i] === arr[i - 1]) {
        counter = counter;
      } else {
        counter = 0;
      }
    }

    return gcd;
  }

  for (let i = 0; i <= firstArray; i++) {
    result(eachGcd);

    for (let i = 0; i < arr.length; i++)
      if (arr[i] === result(eachGcd)) divansArray.push(arr[i]);

    eachGcd = result(eachGcd);
  }

  let arrResult = [divansArray[0]];

  for (let i = 0; i < divansArray.length; i++) {
    if (i === divansArray.length - 1) continue;

    if (
      gcd_two_numbers(divansArray[0], divansArray[i + 1]) === 1 ||
      gcd_two_numbers(divansArray[0], divansArray[i - 1]) === 1
    ) {
      arrResult.push(1);
    } else {
      arrResult.push(gcd_two_numbers(divansArray[i], divansArray[i + 1]));
    }
  }

  console.log(arrResult.reduce((a, b) => a + b, 0));
}

process.stdin.on("data", (c) => (data += c));
process.stdin.on("end", solve);

'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, n, l, r, k, arr;

  t = parseInt(readline());
  while(t--) {
    [n, l, r, k] = readline().split(' ').map(x => Number(x));
    arr = readline().split(' ').map(x => Number(x));
    console.log(solve(n, l, r, k, arr));
  }
}

function solve(n, l, r, k, arr) {
  let sum = 0, cnt = 0;
  arr.sort();
  for(let i = 0; i < n; i++) {
    if(arr[i] < l || arr[i] > r || sum >= k) continue;
    cnt++;
    sum += arr[i];
  }
  return cnt;
}


Let's say string $$$s$$$ has period $$$k$$$ if $$$s_i = s_{i + k}$$$ for all $$$i$$$ from $$$1$$$ to $$$|s| - k$$$ ($$$|s|$$$ means length of string $$$s$$$) and $$$k$$$ is the minimum positive integer with this property.Some examples of a period: for $$$s$$$="0101" the period is $$$k=2$$$, for $$$s$$$="0000" the period is $$$k=1$$$, for $$$s$$$="010" the period is $$$k=2$$$, for $$$s$$$="0011" the period is $$$k=4$$$.You are given string $$$t$$$ consisting only of 0's and 1's and you need to find such string $$$s$$$ that:  String $$$s$$$ consists only of 0's and 1's;  The length of $$$s$$$ doesn't exceed $$$2 \cdot |t|$$$;  String $$$t$$$ is a subsequence of string $$$s$$$;  String $$$s$$$ has smallest possible period among all strings that meet conditions 1—3. Let us recall that $$$t$$$ is a subsequence of $$$s$$$ if $$$t$$$ can be derived from $$$s$$$ by deleting zero or more elements (any) without changing the order of the remaining elements. For example, $$$t$$$="011" is a subsequence of $$$s$$$="10101".

The first line contains single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains string $$$t$$$ ($$$1 \le |t| \le 100$$$) consisting only of 0's and 1's.

Print one string for each test case — string $$$s$$$ you needed to find. If there are multiple solutions print any one of them.

NoteIn the first and second test cases, $$$s = t$$$ since it's already one of the optimal solutions. Answers have periods equal to $$$1$$$ and $$$2$$$, respectively.In the third test case, there are shorter optimal solutions, but it's okay since we don't need to minimize the string $$$s$$$. String $$$s$$$ has period equal to $$$1$$$.

var ttt = parseInt(readline());

function mapper(s) { return +s; }

for(var qq = 0; qq < ttt; qq++) {
    var t = readline();
    var tl = t.length;

    if (tl <= 2) {
        print(t);
    } else {
        var same = true;
        for(var i = 0; i < tl - 1; i++) {
            if (t[i] !== t[i+1]) {
                same = false;
                break;
            }
        }

        if (same) {
            print(t);
        } else {
            var ch = t[0] === '0' ? '01' : '10';
            var s = ch.repeat(tl);
            print(s);
        }
    }
}

const readline = require('readline');

let input = [];

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

rl.on('line', lineInput => {
	input.push(lineInput);
});

rl.on('close', () => {
	const test = parseInt(input[0]);
	for (let i=0; i < test; i++) {
		let t = input[i+1].split('');
		console.log(solution(t));
	}
});

function solution(t) {
	for (let i = 1; i < t.length; i++) {
		if (t[i] !== t[i-1]) {
			return constructString(t.length-1)
		}
	}
	return t.join('');
}
function constructString(l) {
	let str = '01'
	for (let j = 0; j < l; j++) {
		str += '01';
	}
	return str;
}

const processData = (lines) => {
  const nums = +lines[0]
  for (let i =0; i<nums;i++) {
    const nums = lines[i+1].split('').map(x => +x)

    const sum = nums.reduce((r, x) => r+x, 0)
    if (sum === 0 || sum === nums.length) {
      console.log(nums.join(''))
    } else {
      let res = ''
      let i = nums[0] === '0' ? 1 : 0
      for (const ch of nums) {
        const awaitingChar = i%2 === 0 ? '1' : '0'
        if (awaitingChar == ch) {
          res += ch
          i+= 1
        } else {
          res += awaitingChar + ch
          i+= 2
        }
      }
      console.log(res)
    }
  }
}

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

'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.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));
  main();
});

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

function solve(s) {
  let zero = 0;
  let one = 0;
  for (let i = 0; i < s.length; i++) {
    if (s[i] == 0) zero++;
    else one++;
  }
  if (zero === 0 || one === 0) return s;
  let s1 = s[0];
  for (let i = 1; i < s.length; i++) {
    if (s[i] === s[i - 1]) {
      let insert = s[i] == '1' ? '0' : '1';
      s1 += insert;
    }
    s1 += s[i];
  }
  return s1;
}

function main() {
  const t = parseInt(readLine());
  for (let i = 0; i < t; i++) {
    let s = readLine();
    // let a = readLine().split(' ').map((val) => parseInt(val));
    let res = solve(s);
    console.log(res);
  }
  //process.stdout.write("hello: ");
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    let range = readline();
    for(let r=0;r<range;r++) {
        let data = readline();
        let count1 = 0;
        let countO = 0;
        for(let i=0;i<data.length;i++) {
            if(data[i] === '0') {
                countO++
            } else {
                count1++
            }
        }

        let output = '';

        if(count1 === 0) {
            for(let i=0;i<countO;i++) {
                output = output + '0';
            }
        } else if(countO === 0) {
           for(let i=0;i<count1;i++) {
                output = output + '1';
        }
        } else {
            for(let i=0;i<data.length;i++) {
                output = output + "10";

            }

        }

        console.log(output);

    }

}

var ttt = parseInt(readline());

function mapper(s) { return +s; }

for(var qq = 0; qq < ttt; qq++) {
    var t = readline();
    var tl = t.length;

    if (tl <= 2) {
        print(t);
    } else {
        var ch = t[0] === '0' ? '01' : '10';
        var s = ch.repeat(tl);
        print(s);
    }
}

var ttt = parseInt(readline());

function mapper(s) { return +s; }

for(var qq = 0; qq < ttt; qq++) {
    var t = readline();
    var tl = t.length;

    if (tl <= 2) {
        print(t);
    } else {
        var p = 0;
        var res = '';

        for(var i = 0; i < tl - 2; i++) {
            res += t[i];

            if (t[i] !== t[i+2]) {
                res += t[i+2];
            }
        }
        res += t.slice(tl - 2, tl);

        print(res);
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    let range = readline();
    for(let r=0;r<range;r++) {
        let data = readline();
        let count1 = 0;
        let countO = 0;
        for(let i=0;i<data.length;i++) {
            if(data[i] === '0') {
                countO++
            } else {
                count1++
            }
        }
        if(count1 === data.length || countO === data.length) {
            console.log(data);
        } else {
            let output = '';
            if(data[0] === '1') {
                for(let i=0;i<=data.length;i++) {
                    if(i%2 ===0) {
                        output = output + "1";
                    } else {
                        output = output + "0";
                    }
                }
            } else {
                for(let i=0;i<=data.length;i++) {
                    if(i%2 ===0) {
                        output = output + "0";
                    } else {
                        output = output + "1";
                    }
                }
            }

            console.log(output);
        }

    }

}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    let range = readline();
    for(let r=0;r<range;r++) {
        let data = readline();
        let count1 = 0;
        let countO = 0;
        for(let i=0;i<data.length;i++) {
            if(data[i] === '0') {
                countO++
            } else {
                count1++
            }
        }
        console.log(data, count1, countO)
        if(count1 === data.length || countO === data.length) {
            console.log(data);
        } else {
            let output = '';
            if(data[0] === '1') {
                for(let i=0;i<=data.length;i++) {
                    if(i%2 ===0) {
                        output = output + "1";
                    } else {
                        output = output + "0";
                    }
                }
            } else {
                for(let i=0;i<=data.length;i++) {
                    if(i%2 ===0) {
                        output = output + "0";
                    } else {
                        output = output + "1";
                    }
                }
            }

            console.log(output);
        }

    }

}


A sequence of $$$n$$$ numbers is called permutation if it contains all numbers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences [$$$3, 1, 4, 2$$$], [$$$1$$$] and [$$$2,1$$$] are permutations, but [$$$1,2,1$$$], [$$$0,1$$$] and [$$$1,3,4$$$] — are not.For a permutation $$$p$$$ of even length $$$n$$$ you can make an array $$$b$$$ of length $$$\frac{n}{2}$$$ such that:   $$$b_i = \max(p_{2i - 1}, p_{2i})$$$ for $$$1 \le i \le \frac{n}{2}$$$ For example, if $$$p$$$ = [$$$2, 4, 3, 1, 5, 6$$$], then:   $$$b_1 = \max(p_1, p_2) = \max(2, 4) = 4$$$  $$$b_2 = \max(p_3, p_4) = \max(3,1)=3$$$  $$$b_3 = \max(p_5, p_6) = \max(5,6) = 6$$$  As a result, we made $$$b$$$ = $$$[4, 3, 6]$$$.For a given array $$$b$$$, find the lexicographically minimal permutation $$$p$$$ such that you can make the given array $$$b$$$ from it.If $$$b$$$ = [$$$4,3,6$$$], then the lexicographically minimal permutation from which it can be made is $$$p$$$ = [$$$1,4,2,3,5,6$$$], since:   $$$b_1 = \max(p_1, p_2) = \max(1, 4) = 4$$$  $$$b_2 = \max(p_3, p_4) = \max(2, 3) = 3$$$  $$$b_3 = \max(p_5, p_6) = \max(5, 6) = 6$$$ A permutation $$$x_1, x_2, \dots, x_n$$$ is lexicographically smaller than a permutation $$$y_1, y_2 \dots, y_n$$$ if and only if there exists such $$$i$$$ ($$$1 \le i \le n$$$) that $$$x_1=y_1, x_2=y_2, \dots, x_{i-1}=y_{i-1}$$$ and $$$x_i<y_i$$$.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one even integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains exactly $$$\frac{n}{2}$$$ integers $$$b_i$$$ ($$$1 \le b_i \le n$$$) — elements of array $$$b$$$. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print on a separate line:    lexicographically minimal permutation $$$p$$$ such that you can make an array $$$b$$$ from it;  or a number -1 if the permutation you are looking for does not exist.

NoteThe first test case is parsed in the problem statement.

const readline = require('readline')

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

class SegTree {
    constructor(nOrArray, options) {
        const { op, e } = options
        this.op = op
        this.e = e
        const v = Array.isArray(nOrArray) ? nOrArray : Array(nOrArray).fill(0).map(() => e())

        const n = v.length
        const log = ceilPow2(n)
        const size = 1 << log
        const d = Array(2 * size)
        this.n = n
        this.log = log
        this.size = size
        this.d = d

        for (let i = 0; i < d.length; i++) {
            d[i] = e()
        }
        for (let i = 0; i < n; i++) {
            d[size + i] = v[i]
        }
        for (let i = size - 1; i >= 1; i--) {
            this.update(i)
        }
    }
    set(p, x) {
        p += this.size
        this.d[p] = x
        for (let i = 1; i <= this.log; i++) this.update(p >> i)
    }
    get(p) {
        return this.d[p + this.size]
    }
    prod(l, r) {
        const { size, d, op, e } = this
        let sml = e(), smr = e()
        l += size
        r += size

        while (l < r) {
            if (l & 1) sml = op(sml, d[l++])
            if (r & 1) smr = op(d[--r], smr)
            l >>= 1
            r >>= 1
        }
        return op(sml, smr)
    }
    allProd() {
        return this.d[1]
    }
    maxRight(l, f) {
        const { n, size, d, op, e} = this
        if (l == n) return n
        l += size
        let sm = e()
        do {
            while (l % 2 == 0) l >>= 1
            if (!f(op(sm, d[l]))) {
                while (l < size) {
                    l = (2 * l)
                    if (f(op(sm, d[l]))) {
                        sm = op(sm, d[l])
                        l++
                    }
                }
                return l - size
            }
            sm = op(sm, d[l])
            l++
        } while ((l & -l) != l)
        return n
    }
    minLeft(r, f) {
        if (r == 0) return 0
        const { size, d, op, e} = this
        r += size
        let sm = e()
        do {
            r--
            while (r > 1 && (r % 2)) r >>= 1
            if (!f(op(d[r], sm))) {
                while (r < size) {
                    r = (2 * r + 1)
                    if (f(op(d[r], sm))) {
                        sm = op(d[r], sm)
                        r--
                    }
                }
                return r + 1 - size
            }
            sm = op(d[r], sm)
        } while ((r & -r) != r)
        return 0
    }

    update(k) {
        const { d, op } = this
        d[k] = op(d[2 * k], d[2 * k + 1])
    }
}

function solve(n, arr) {
    let ok = 1
    const map = arr.reduce((o, x) => {
        // o[x] = 1
        o[x] = (o[x] || 0) + 1
        if (o[x] > 1) {
            ok = false
        }
        return o
    }, {})
    if (!ok) return -1
    const dp = Array(n + 1).fill(0)
    for (let i = 1; i <= n; i++) {
        if (!map[i]) {
            dp[i] = 1 // able to be selected
        }
    }
    const s = new SegTree(dp, {
        op: Math.max,
        e: () => -Infinity,
    })
    const r = Array(n)
    let p = n - 1
    for (let i = arr.length - 1; i >= 0; i--) {
        const x = arr[i]
        const j = s.minLeft(x, v => v === 0) - 1
        if (j < 1) return -1
        s.set(j, 0)
        r[p--] = x
        r[p--] = j
    }
    return r.join(' ')
}

'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 _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns();
  const set = new Set(a),
        tr = new BinarySearchTree();
  if (set.size !== n / 2) return -1;
  for (let i = 1; i <= n; i++) {
    if (set.has(i)) continue;
    tr.insert(i);
  }
  const res = new Array(n);
  for (let i = n - 2; i >= 0; i -= 2) {
    res[i + 1] = a[i / 2];
    if (tr.getMin() > res[i + 1]) return -1;
    let t = tr.floor(res[i + 1]);
    tr.delete(t);
    res[i] = t;
  }
  return res.join(' ');
}
class BinarySearchTree {
  constructor(_compare = (a, b) => a - b) {
    _defineProperty(this, "root", null);
    _defineProperty(this, "length", 0);
    _defineProperty(this, "min", null);
    _defineProperty(this, "max", null);
    _defineProperty(this, "minCache", true);
    _defineProperty(this, "maxCache", true);
    this._compare = _compare;
    this.compare = this.compare.bind(this);
  }
  isT(t) {
    return t !== undefined && t !== null;
  }
  compare(a, b) {
    const {
      isT
    } = this;
    if (isT(a) && isT(b)) return this._compare(a, b);
    if (isT(a)) return 1;
    if (isT(b)) return -1;
    return 0;
  }
  isEmpty() {
    return !this.root;
  }
  size() {
    return this.root ? this.root.size : 0;
  }
  getRoot() {
    return this.root;
  }
  getMin() {
    if (this.minCache) {
      return this.min;
    }
    const min = this.searchKth(this.size());
    this.min = min;
    this.minCache = true;
    return min;
  }
  getMax() {
    if (this.maxCache) {
      return this.max;
    }
    const max = this.searchKth(1);
    this.max = max;
    this.maxCache = true;
    return max;
  }
  balance(node) {
    node.height = this.getHeight(node);
    const blance = this.getBalance(node);
    let res;
    if (Math.abs(blance) === 2) {
      if (blance > 0) {
        var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;
        const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);
        if (heightDif > 0) {
          res = this.rotateRight(node);
        } else if (heightDif < 0) {
          res = this.rotateLeftRight(node);
        }
      } else {
        var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;
        const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);
        if (heightDif > 0) {
          res = this.rotateRightLeft(node);
        } else if (heightDif < 0) {
          res = this.rotateLeft(node);
        }
      }
    }
    return res ? res : node;
  }
  rotateRight(node) {
    const left = node.left;
    const leftRight = left.right;
    left.right = node;
    node.left = leftRight;
    node.height = this.getHeight(node);
    left.height = this.getHeight(left);
    node.size = this.getSize(node);
    left.size = this.getSize(left);
    return left;
  }
  rotateLeft(node) {
    const right = node.right;
    const rightLeft = right.left;
    right.left = node;
    node.right = rightLeft;
    node.height = this.getHeight(node);
    right.height = this.getHeight(right);
    node.size = this.getSize(node);
    right.size = this.getSize(right);
    return right;
  }
  rotateLeftRight(node) {
    node.left = this.rotateLeft(node.left);
    return this.rotateRight(node);
  }
  rotateRightLeft(node) {
    node.right = this.rotateRight(node.right);
    return this.rotateLeft(node);
  }
  getBalance(node) {
    return this.getHeight(node.left) - this.getHeight(node.right);
  }
  getHeight(node) {
    var _node$left$height, _node$left3, _node$right$height, _node$right3;
    if (!node) return 0;
    return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;
  }
  getSize(node) {
    var _node$left$size, _node$left4, _node$right$size, _node$right4;
    if (!node) return 0;
    return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;
  }
  createNode(val) {
    return {
      id: Math.random() * new Date().valueOf(),
      val,
      left: null,
      right: null,
      size: 1,
      height: 1,
      count: 1
    };
  }
  insert(val) {
    let cur = this.createNode(val);
    if (this.isEmpty()) {
      this.root = cur;
      this.length++;
    } else {
      [, cur] = this.insertNode(this.root, cur);
    }
    if (this.min === null || this.compare(this.min, val) > 0) {
      this.min = val;
    }
    if (this.max === null || this.compare(this.max, val) < 0) {
      this.max = val;
    }
  }
  insertNode(node, cur, parent = null) {
    node.size++;
    const compareResult = this.compare(cur.val, node.val);
    let res;
    if (compareResult === 0) {
      node.count++;
      return [false, node];
    } else if (compareResult > 0) {
      if (node.right) {
        res = this.insertNode(node.right, cur, node);
        if (!res[0]) return res;
      } else {
        node.right = cur;
        this.length++;
        res = [true, cur];
      }
    } else {
      if (node.left) {
        res = this.insertNode(node.left, cur, node);
        if (!res[0]) return res;
      } else {
        node.left = cur;
        this.length++;
        res = [true, cur];
      }
    }
    let preHeight = node.height;
    const newNode = this.balance(node);
    if (newNode === node && node.height === preHeight) {
      res = [false, res[1]];
    } else if (newNode !== node) {
      if (parent) {
        parent.left === node ? parent.left = newNode : parent.right = newNode;
      } else {
        this.root = newNode;
      }
      res = [false, res[1]];
    }
    return res;
  }
  delete(val) {
    if (!this.root) return;
    this.deleteNode(val, this.root, null);
  }
  deleteNode(val, node, parent) {
    if (!node) return null;
    let res = this.compare(val, node.val);
    if (res === 0) {
      node.count--;
      node.size--;
      if (node.count > 0) return node;
      if (!node.left || !node.right) {
        if (this.min === val) {
          this.minCache = false;
        }
        if (this.max === val) {
          this.maxCache = false;
        }
        this.length--;
        if (!parent) {
          var _node$left5;
          this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;
          return this.root;
        } else {
          var _node$left6;
          return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;
        }
      } else {
        const selectLeft = node.left.height > node.right.height;
        let replaceNode = selectLeft ? this.pre(node) : this.next(node),
            name = selectLeft ? 'left' : 'right';
        node.val = replaceNode.val;
        node.count = replaceNode.count;
        replaceNode.count = 0;
        node[name] = this.deleteNode(replaceNode.val, node[name], node);
      }
    } else if (res > 0) {
      node.right = this.deleteNode(val, node.right, node);
    } else {
      node.left = this.deleteNode(val, node.left, node);
    }
    node.size = this.getSize(node);
    node.height;
    const newNode = this.balance(node);
    if (parent) {
      parent.left === node ? parent.left = newNode : parent.right = newNode;
    } else {
      this.root = newNode;
    }
    return newNode;
  }
  next(node) {
    let next = node.right;
    while ((_next = next) !== null && _next !== void 0 && _next.left) {
      var _next;
      next = next.left;
    }
    return next;
  }
  pre(node) {
    let pre = node.left;
    while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {
      var _pre;
      pre = pre.right;
    }
    return pre;
  }
  search(val, compare) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);
    return node.val;
  }
  searchCeilingNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        return this.searchCeilingNode(node.right, val, compare, node);
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        const [p, value] = this.searchCeilingNode(node.left, val, compare, node);
        if (compare(value.val, val) < 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    }
  }
  ceiling(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, this.compare);
    return this.compare(node.val, val) >= 0 ? node.val : null;
  }
  searchFloorNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        const [p, value] = this.searchFloorNode(node.right, val, compare, node);
        if (compare(value.val, val) > 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        return this.searchFloorNode(node.left, val, compare, node);
      } else {
        return [parent, node];
      }
    }
  }
  floor(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchFloorNode(this.root, val, this.compare);
    return this.compare(node.val, val) <= 0 ? node.val : null;
  }
  searchKth(k) {
    if (this.isEmpty()) {
      return null;
    }
    if (k <= 0 || k > this.size()) {
      return null;
    }
    const node = this.searchNodeKth(this.root, k);
    return node.val;
  }
  searchNodeKth(node, k) {
    var _node$right$size2, _node$right5, _node$right$size3, _node$right6;
    const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;
    if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;
    if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);
  }
  countGreaterThanEq(val) {
    if (!this.root) return 0;
    return this.countCompare(val, (a, b) => this._compare(a, b), this.root);
  }
  countCompare(val, compare, node, pre = 0) {
    const res = compare(val, node.val);
    if (res === 0) {
      var _node$right$size4, _node$right7;
      return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;
    } else if (res > 0) {
      if (node.right) {
        return this.countCompare(val, compare, node.right, pre);
      } else {
        return pre;
      }
    } else {
      var _node$right$size5, _node$right8;
      let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;
      if (node.left) {
        return this.countCompare(val, compare, node.left, count);
      } else {
        return count;
      }
    }
  }
  toArray() {
    if (!this.root) return [];
    const res = [];
    const dfs = node => {
      if (node.left) dfs(node.left);
      res.push(node.val);
      if (node.right) dfs(node.right);
    };
    dfs(this.root);
    return res;
  }
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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


Hanh lives in a shared apartment. There are $$$n$$$ people (including Hanh) living there, each has a private fridge. $$$n$$$ fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridge can be open only if all chains connected to it are unlocked. For example, if a fridge has no chains connected to it at all, then any of $$$n$$$ people can open it.    For exampe, in the picture there are $$$n=4$$$ people and $$$5$$$ chains. The first person knows passcodes of two chains: $$$1-4$$$ and $$$1-2$$$. The fridge $$$1$$$ can be open by its owner (the person $$$1$$$), also two people $$$2$$$ and $$$4$$$ (acting together) can open it. The weights of these fridges are $$$a_1, a_2, \ldots, a_n$$$. To make a steel chain connecting fridges $$$u$$$ and $$$v$$$, you have to pay $$$a_u + a_v$$$ dollars. Note that the landlord allows you to create multiple chains connecting the same pair of fridges. Hanh's apartment landlord asks you to create exactly $$$m$$$ steel chains so that all fridges are private. A fridge is private if and only if, among $$$n$$$ people living in the apartment, only the owner can open it (i.e. no other person acting alone can do it). In other words, the fridge $$$i$$$ is not private if there exists the person $$$j$$$ ($$$i \ne j$$$) that the person $$$j$$$ can open the fridge $$$i$$$.For example, in the picture all the fridges are private. On the other hand, if there are $$$n=2$$$ fridges and only one chain (which connects them) then both fridges are not private (both fridges can be open not only by its owner but also by another person).Of course, the landlord wants to minimize the total cost of all steel chains to fulfill his request. Determine whether there exists any way to make exactly $$$m$$$ chains, and if yes, output any solution that minimizes the total cost.

Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 10$$$). Then the descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \le n \le 1000$$$, $$$1 \le m \le n$$$) — the number of people living in Hanh's apartment and the number of steel chains that the landlord requires, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$) — weights of all fridges.

For each test case:   If there is no solution, print a single integer $$$-1$$$.  Otherwise, print a single integer $$$c$$$ — the minimum total cost. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), meaning that the $$$i$$$-th steel chain connects fridges $$$u_i$$$ and $$$v_i$$$. An arbitrary number of chains can be between a pair of fridges.  If there are multiple answers, print any.

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))

  const t = parseInt(arr.shift())

  for(let j = 0; j < t; j++) {
    const arrT1 = arr[2 * j].split(' ').map(a => parseInt(a))
    const arrT2 = arr[2 * j + 1].split(' ').map((a, i) => [parseInt(a), i + 1])

    const n = arrT1[0]
    const m = arrT1[1]

    if(m < n) console.log(-1)
    else if(n == 2) console.log(-1)
    else {
      let cost = 0
      let diff = m - n
      if(diff == 0) diff ++
      for(let i = 0; i < n; i++) {
        if(diff <= n) cost += (arrT2[i][0] + arrT2[(i + 1) % n][0])
        else cost += (arrT2[i][0] + arrT2[(i + 1) % n][0]) * Math.ceil(m / n)
        if(diff != 1) diff --
      }

      console.log(cost)
      for(let i = 0; i < m; i++) {
        console.log(`${arrT2[i % n][1]} ${arrT2[(i + 1) % n][1]}`)
      }
    }
  }
})

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))

  const t = parseInt(arr.shift())

  for(let j = 0; j < t; j++) {
    const arrT1 = arr[2 * j].split(' ').map(a => parseInt(a))
    const arrT2 = arr[2 * j + 1].split(' ').map((a, i) => [parseInt(a), i + 1])

    const n = arrT1[0]
    const m = arrT1[1]

    if(m < n) console.log(-1)
    else {
      let cost = 0
      for(let i = 0; i < n; i++) {
        cost += arrT2[i][0] + arrT2[(i + 1) % n][0]
      }

      for(let i = 0; i < m - n; i++) {
        cost += arrT2[i][0] + arrT2[(i + 1) % n][0]
      }

      console.log(cost)
      for(let i = 0; i < n; i++) {
        console.log(`${arrT2[i][1]} ${arrT2[(i + 1) % n][1]}`)
      }
      for(let i = 0; i < m - n; i++) {
        console.log(`${arrT2[i][1]} ${arrT2[(i + 1) % n][1]}`)
      }
    }
  }
})


High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.

Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.

NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".

(function () {
	var line = readline().split(' ').map(function (e) {
		return parseInt(e);
	});
	var n = line[0],
		k = line[1];
	var s = readline();

	var ans1 = getAns(s,k,'a'),
		ans2 = getAns(s,k,'b');
	ans1 = ans1>ans2?ans1:ans2;
	print(ans1);

	function getAns (str, k, c) {
		var p = -1,
			nxt = 0,
			seg = [],
			l = str.length;
		do {
			nxt = str.indexOf(c, p+1);
			if(nxt<0)
				nxt = l;
			seg.push(nxt - p - 1);
			p = nxt;
		} while(p<l);
		if(seg.length<=k+1)
			return l;
		var i,
			j,
			ret,
			tmp=0;
		l = seg.length;
		for(i=0;i<=k;++i) {
			tmp += seg[i];
		}
		ret = tmp;
		for(j=0;i<l;++i,++j) {
			tmp+=seg[i]-seg[j];
			ret = tmp>ret?tmp:ret;
		}
		return ret+k;
	}

})();

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var bs_removed = {removed: 0};
var as_removed = {removed: 0};

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(new_array, letter_in_array, letter_removed, number_of_letters_removed) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    new_array[j] = 0;

		while (string[i] == letter_in_array) {
			new_array[j] += 1;
			i++;
		}

		if (string[i] == letter_removed) {
	    	number_of_letters_removed.removed += 1;
	    }

		j++;
	}

	return new_array;
};

a_arr = (rewrite_string(a_arr, a, b, bs_removed)); // removing b's
b_arr = (rewrite_string(b_arr, b, a, as_removed)); // removing a's

var max_sum_a = 0;
var max_sum_b = 0;

var summing = function(array, letters_removed) {
	var sum = 0;

	// First sum
	for (var i = 0; i <= k && i < array.length; i++) {
		sum += array[i];
	}

	var max_sum = sum;

	// Checking if other sums are bigger
	for (var i = 1; i + k <= array.length - 1; i++) {
		sum += array[i + k] - array[i - 1];
    	if (sum > max_sum) {
    		max_sum = sum;
    	}
	}

	max_sum += Math.min(k, letters_removed.removed);

	return max_sum;
};

max_sum_a = summing(a_arr, bs_removed);
max_sum_b = summing(b_arr, as_removed);

print(Math.max(max_sum_a, max_sum_b));

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var bs_removed = {removed: 0};
var as_removed = {removed: 0};

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y, z, p) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;

		while (string[i] == y) {
			x[j] += 1;
			i++;
		}

		if (string[i] == z) {
	    	p.removed += 1;
	    }

		j++;
	}

	return x;
};

a_arr = (rewrite_string(a_arr, a, b, bs_removed)); // removing b's
b_arr = (rewrite_string(b_arr, b, a, as_removed)); // removing a's

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k <= d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

// which sum is bigger? and could I remove k letters or did I not have that many to begin with?
if ((summing(sum_a, a_arr, max_sum_a) < summing(sum_b, b_arr, max_sum_b))) {
    if (as_removed.removed > k) {
	    print(summing(sum_b, b_arr, max_sum_b) + k);
    } else {
	    print(summing(sum_b, b_arr, max_sum_b) + as_removed.removed);
    }
} else {
    if (bs_removed.removed > k) {
	    print(summing(sum_a, a_arr, max_sum_a) + k);
    } else {
	    print(summing(sum_a, a_arr, max_sum_a) + bs_removed.removed);
    }
}

var nums = readline().split(" ").map(x => parseInt(x));
var n = nums[0];
var k = nums[1];
var str = readline();
print(solve(n, k, str));

function solve(n, k, str) {
    return Math.max(longest(n, k, str, "a"), longest(n, k, str, "b"));
}

function longest(n, k, str, c) {
    var max = 0;
    var p = 0;
    for (var i = 0; i < n; i++) {
        if (str[i] !== c) {
            k -= 1;
        }
        while (k < 0) {
            if (str[p] !== c) {
                k += 1;
            }
            p += 1;
        }
        max = Math.max(max, i - p + 1);
    }
    return max;
}

function main() {
  var input = readline().split(' ').map(Number);
  var n = input[0];
  var k = input[1];
  var str = readline();

  var prefixSum = [];
  for (var i = 0; i < n; ++i) {
    var value = (str.charAt(i) == "a" ? 1 : 0);
    if (i > 0) {
      value += prefixSum[i - 1];
    }
    prefixSum.push(value);
  }

  function rangeSum(prefixSum, st, ed) {
    if (st > 0) {
      return prefixSum[ed] - prefixSum[st - 1];
    } else {
      return prefixSum[ed];
    }
  }

  function check(prefixSum, n, k, m) {
    for (var i = 0; i < n; ++i) {
      var numOfA = rangeSum(prefixSum, i, i + m - 1);
      var numOfB = m - numOfA;
      if (Math.min(numOfA, numOfB) <= k) {
        return true;
      }
    }
    return false;
  }

  function binarySearch(prefixSum, n, k) {
    var lower = 1;
    var upper = n;
    while (upper - lower > 1) {
      var middle = Math.floor((lower + upper) / 2);
      if (check(prefixSum, n, k, middle)) {
        lower = middle;
      } else {
        upper = middle;
      }
    }
    return check(prefixSum, n, k, upper) ? upper : lower;
  }

  var result = binarySearch(prefixSum, n, k);
  print(result);
}

main();

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;
		while (string[i] == y) {
			x[j] += 1;
			i++;
		}
		j++;
	}

	return x;
};

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k < d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

var remove_b = summing(sum_a, a_arr, max_sum_a);
var remove_a = summing(sum_b, b_arr, max_sum_b);

print(Math.max(remove_b, remove_a) + k);

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;
		while (string[i] == y) {
			x[j] += 1;
			i++;
		}
		j++;
	}

	return x;
};

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k < d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

print(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)));

/* Sums for a_arr, not using this because I wrote a function
var sum_a = 0;

// First sum
for (var i = 0; i <= k; i++) {
	sum_a += a_arr[i];
}

var max_sum_a = sum_a;

// Checking if other sums are bigger
for (var i = 1; i < a_arr.length; i++) {
	sum_a += a_arr[i + k] - a_arr[i - 1];
	if (sum_a > max_sum_a) {
		max_sum_a = sum_a;
	}
}

print(max_sum_a);
*/

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var bs_removed = {removed: 0};
var as_removed = {removed: 0};

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y, z, p) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;

		while (string[i] == y) {
			x[j] += 1;
			i++;
		}

		if (string[i] == z) {
	    	p.removed += 1;
	    }

		j++;
	}

	return x;
};

a_arr = (rewrite_string(a_arr, a, b, bs_removed)); // removing b's
b_arr = (rewrite_string(b_arr, b, a, as_removed)); // removing a's

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k < d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

// which sum is bigger? and could I remove k letters or did I not have that many to begin with?
if ((summing(sum_a, a_arr, max_sum_a) < summing(sum_b, b_arr, max_sum_b))) {
    if (as_removed.removed > k) {
	    print(summing(sum_b, b_arr, max_sum_b) + k);
    } else {
	    print(summing(sum_b, b_arr, max_sum_b) + as_removed.removed);
    }
} else {
    if (bs_removed.removed > k) {
	    print(summing(sum_a, a_arr, max_sum_a) + k);
    } else {
	    print(summing(sum_a, a_arr, max_sum_a) + bs_removed.removed);
    }
}

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;
		while (string[i] == y) {
			x[j] += 1;
			i++;
		}
		j++;
	}

	return x;
};

a_arr = (rewrite_string(a_arr, a));
b_arr = (rewrite_string(b_arr, b));

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k < d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

if (string.length == 1) {
	print(1);
} else {
	print(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)) + k);
}

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;
		while (string[i] == y) {
			x[j] += 1;
			i++;
		}
		j++;
	}

	return x;
};

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
		c += d[i + k] - d[i - 1];
		if (c > e) {
			e = c;
		}
	}

	return e;
};

print(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)));

/* Sums for a_arr, not using this because I wrote a function
var sum_a = 0;

// First sum
for (var i = 0; i <= k; i++) {
	sum_a += a_arr[i];
}

var max_sum_a = sum_a;

// Checking if other sums are bigger
for (var i = 1; i < a_arr.length; i++) {
	sum_a += a_arr[i + k] - a_arr[i - 1];
	if (sum_a > max_sum_a) {
		max_sum_a = sum_a;
	}
}

print(max_sum_a);
*/

var nk = readline().split(' ').map(Number);
var string = readline().split('').map(String);

var n = nk[0];
var k = nk[1];

var a_arr = [];
var b_arr = [];
var a = "a";
var b = "b";

var rewrite_string = function(x, y) {
	var count = 0;
	var j = 0;

	for (var i = 0; i < n; i++) {
	    x[j] = 0;
		while (string[i] == y) {
			x[j] += 1;
			i++;
		}
		j++;
	}

	return x;
};

a_arr = (rewrite_string(a_arr, a));
b_arr = (rewrite_string(b_arr, b));

var sum_a = 0;
var max_sum_a = 0;
var sum_b = 0;
var max_sum_b = 0;

var summing = function(c, d, e) {
	c = 0;

	// First sum
	for (var i = 0; i <= k && i < d.length; i++) {
		c += d[i];
	}

	e = c;

	// Checking if other sums are bigger
	for (var i = 1; i < d.length; i++) {
	    if (i + k < d.length - 1) {
    		c += d[i + k] - d[i - 1];
    		if (c > e) {
    			e = c;
    		}
		}
	}

	return e;
};

print(Math.max(summing(sum_a, a_arr, max_sum_a), summing(sum_b, b_arr, max_sum_b)) + k);

var nums = readline().split(" ").map(x => parseInt(x));
var n = nums[0];
var k = nums[1];
var str = readline();
print(solve(n, k, str));

function solve(n, k, str) {
    return Math.max(longest(n, k, str, "a"), longest(n, k, str, "b"));
}

function longest(n, k, str, c) {
    var max = 0;
    var p = 0;
    for (var i = 0; i < n; i++) {
        if (str[i] !== c) {
            k -= 1;
        }
        while (k < 0) {
            if (str[p] !== c) {
                k += 1;
            }
            p += 1;
        }
        max = Math.max(max, i - p);
    }
    return max;
}