In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.

The first line contains the integer n (1 ≤ n ≤ 100) — the number of citizens in the kingdom. The second line contains n integers a1, a2, ..., an, where ai (0 ≤ ai ≤ 106) — the welfare of the i-th citizen.

In the only line print the integer S — the minimum number of burles which are had to spend.

NoteIn the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.In the second example it is enough to give one burle to the third citizen. In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles.

var n = readline();
var arr = readline().split(" ").map(Number).sort((a,b)=>a-b)
var count = 0
arr.forEach(i => count+=arr[n-1]-i)
print(count)

var n = readline();
var arr = readline().split(" ").map(Number).sort((a,b)=>a-b)
var count = 0
for(i=0;i<n;i++){count+=arr[n-1]-arr[i]};
print(count)

var n = parseInt(readline());
	var welfare = readline().split(" ").map(x=>+x);
	var spend=0;
	if(welfare.length === 1){
		spend = 0;
	}
	else{
		var sum = 0;
		var maximum = 0;
		for(var i = 0; i < n; i++){
			sum += welfare[i];
			maximum = Math.max(maximum, welfare[i]);
		}
		spend = n*maximum-sum;
	}
	print(spend);

var res = sol(readline(), readline());
print(res);

function sol(line1, line2) {
    var input1 = line1.split(" ").map((x) => Number(x));
    var input2 = line2.split(" ").map((x) => Number(x));

    var n = input1[0];
    var welfare = input2;

    var max = -1;
    welfare.map((x) => {
        max = Math.max(max, x)
    });

    var sum = 0;
    welfare.map((x) => {
        sum += Math.abs(max - x);
    });

    return sum;
}

(function() {
    'use strict';
    const n = readline();
    const z = readline().split(' ').map(Number);
    var x = Math.max.apply(null, z);
    var y = 0;
    for (let i = 0; i < n; ++i) {
        if (z[i] != x) {
            y += x - z[i];
        }
    }
    print(y);

}());

function main(){
  var citizens = readline();
  var welfares = readline().split(" ").map(Number);

  var max = welfares.reduce((a,b) => a > b ? a : b);

  var sum = 0;
  welfares.forEach(function(welfare){
    if(welfare < max)
      sum += (max - welfare);
  });

  print(sum);
}

main();

function readIntTabLine() {
  var l = readline().split(' ')
  for (var i = 0 ; i < l.length ; i++) {
    l[i] = parseInt(l[i])
  }
  return l
}

var n = parseInt(readline()),
    as = readIntTabLine(),
    max = as.reduce((s,v,i,a) => Math.max(s,v))

print(as.reduce((s,v,i,a) => s + max - v, 0))

'use strict';

String.prototype.getNumArray = function () {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  });
};

function getMaxMoneyAmount(array) {
  var max = array[0];
  array.map(function (value) {
    if (value > max) {
      max = value;
    }
  });
  return max;
}

function getMoneyToBalancePeople(people) {
  var maxMoneyAmount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getMaxMoneyAmount(people);
  var sum = 0;
  people.map(function (value) {
    if (value < maxMoneyAmount) {
      sum += maxMoneyAmount - value;
    }
  });
  return sum;
}

readline();
var people = readline().getNumArray();
write(getMoneyToBalancePeople(people));

'use strict'

String.prototype.getNumArray = function () {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  });
}

function getMaxMoneyAmount (array) {
  let max = array[0];
  array.map((value) => {
    if (value > max) {
      max = value
    }
  });
  return max;
}

function getMoneyToBalancePeople (people) {
  let maxMoneyAmount = getMaxMoneyAmount(people);
  let sum = 0;
  people.map((value) => {
    if (value < maxMoneyAmount) {
      sum += maxMoneyAmount - value;
    }
  });
  return sum;
}

readline();
let people = readline().getNumArray();
write(getMoneyToBalancePeople(people));

function main()
{
    var n = Number( readline() );
    var a = readline(' ').split(' ').map( Number );

    var sum = a.reduce( (p,n) => p+n , 0 );
    var mx = 0;
    a.forEach( (v) => mx = Math.max( mx , v ) );

    var ans = mx*n - sum;
    print(ans);
} main();

function main()
{
    var n = Number( readline() );
    var a = readline(' ').split(' ').map( Number );

    var sum = a.reduce( (p,n) => p+n , 0 );
    var max = a.reduce( (p,n) => Math.max(p,n) , 0 );

    var ans = max*n - sum;
    print(ans);
} main();

var n = parseInt(readline());
	var welfare = readline().split(" ").map(x=>+x);
	var totalSpend=0;
	if(welfare.length === 1){
		totalSpend = 0;
	}
	else{
		var sum = 0;
		var maximumBurle = 0;
		for(var i = 0; i < n; i++){
			sum += welfare[i];
			maximumBurle = Math.max(maximumBurle, welfare[i]);
		}
		totalSpend = n*maximumBurle-sum;
	}
    print(totalSpend);
    // console.log(spend);

var n =readline();
var str = readline().split(" ");
var res=0;
var max = Math.max.apply(this, str);
for (var i=0; i<n; i++){
	res += max-Number(str[i]);

}
print(res);

var q = readline();
if (+q < 2) {
	print("0");
}
else {
	var netWorth = readline().split(" ").map(Number);
	var max = Math.max.apply(Math, netWorth);
	print(netWorth.reduce(function (sum, next) { return sum + max - next; }, 0));
}

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

var m = 0;
for(var i=0; i<n; i++){
    m = Math.max(m, a[i]);
}
var s = 0;
for(var i=0; i<n;i++){
    s += m-a[i];
}
print(s);

"use strict";

var main = function() {
    var n = +rd();
    var A = rdAr();
    var max = Math.max(...A);
    pr(A.reduce((a, v) => a + (max - v), 0));
};

var rd = readline;
var pr = print;
var rdAr = () => { return rd().split(' ').map( v => +v); };
var cmpLt = (a, b) => a - b;
var cmpGt = (a, b) => b - a;

main();

readline()
a=readline().split(' ').map(Number)
m=Math.max.apply(null,a)
s=0
a.forEach(q => s += (m-q))
print(s)

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

var mx = 0;
for(var i = 0; i < n; i++)
    mx = Math.max(mx, a[i]);

var res = 0;
for(var i = 0; i < n; i++)
    res += mx - a[i];

print(res);

function main(){
  var citizens = readline();
  var welfares = readline().split(" ").map(Number);

  var i = 0;
  var max = -1;
  var suma = 0;
  while (i<citizens) {
    if (max<welfares[i]) {
      max = welfares[i];
    }
    suma += welfares[i];
    i++;
  }
    print((citizens*max) - suma);
}

main();

function main() {
    // write code here:
    const n = Number(stdin[0]);
    var arr = stdin[1].split(' ').map(Number);
    const max = Math.max(...arr);
    var burles = 0;
    for (let i = 0; i < n; i++) {
        burles+=(max-arr[i]);
    }
    console.log(burles);
}

const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});
var stdin = [];
rl.on('line', function (line) {
    stdin.push(line);
});
rl.on('close', main);

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

let input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
    const count = parseInt(input[0], 10)
    let maxNum = 0
    const peoples = input[1].split(' ')
    let nowNums = 0
    peoples.forEach(el => {
        const _el = parseInt(el, 10)
        if (_el > maxNum)
            maxNum = _el
        nowNums += _el
    })
    const result = (maxNum * count) - nowNums
    console.log(result)
})

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

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var list = nextIntArray();
  var max = Math.max.apply(null, list);
  var sum = 0;
  for(var i = 0; i < N; i++){
    sum += max - list[i];
  }
  myout(sum);
}

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

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

  const arr = d.split(' ').map(Number);
  const max = Math.max(...arr);
  let ans = 0;

  for (let i = 0; i < arr.length; i++) {
    ans += max - arr[i];
  }

  console.log(ans);

  c++;
});

function solve() {
	n = readline()
	a = readline().split(' ')
	v = Math.max.apply(Math, a)
	print(a.reduce((r,x) => r + v-x, 0))
}

if (typeof readline !== 'function') {
    let input = [],
            i = 0;
    function print() {
        console.log.apply(null, arguments);
    }
    function readline() {
        return input[i++];
    };

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

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

    RL.on('close', solve);
} else {
    solve();
}

const input = [];

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

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

RL.on('close', () => {
  const nums = input[1].split(' ').map(x => parseInt(x));
  const max = nums.reduce((prev, next) => next > prev ? next : prev, 0);
  let ans = 0;

  nums.forEach(x => ans += max-x);
  console.log(ans);
});

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let citizenCount = +inputs[0];
    let citizensWealth = inputs[1].split(' ');
    let max = Math.max(...citizensWealth);
    let add = 0;
    for (let row of citizensWealth) {
        add += max - row;
    }
    return add.toString();

}

'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 main() {
    let n = parseInt(readLine());
    let arr = readLine().split(' ').map(v => parseInt(v));
    arr.sort((a, b) => {
        return b - a;
    })
    let ans = arr.reduce((sum, value) => {
        return sum + Math.max(...arr) - value;
    }, 0)
    console.log(ans);
}

var n = readline();
var a = readline();

var m = 0;
for(var i=0; i<n; i++){
    m = Math.max(m, a[i]);
}
var s = 0;
for(var i=0; i<n;i++){
    s += m-a[i];
}
print(s);

var n = Number(readline());
var a = readline();

var m = 0;
for(var i=0; i<n; i++){
    m = Math.max(m, a[i]);
}
var s = 0;
for(var i=0; i<n;i++){
    s += m-a[i];
}
print(s);

function main(){
  var citizens = readline();
  var welfares = readline().split(" ").map(Number);

  var i = 0;
  var max = -1;
  var suma = 0;
  while (i>citizens) {
    if (max<welfares[i]) {
      max = welfares[i];
    }
    suma += welfares[i];
    i++;
  }
    print((citizens*max) - suma);
}

main();


Let's call an array $$$a_1, a_2, \dots, a_m$$$ of nonnegative integer numbers good if $$$a_1 + a_2 + \dots + a_m = 2\cdot(a_1 \oplus a_2 \oplus \dots \oplus a_m)$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.For example, array $$$[1, 2, 3, 6]$$$ is good, as $$$1 + 2 + 3 + 6 = 12 = 2\cdot 6 = 2\cdot (1\oplus 2 \oplus 3 \oplus 6)$$$. At the same time, array $$$[1, 2, 1, 3]$$$ isn't good, as $$$1 + 2 + 1 + 3 = 7 \neq 2\cdot 1 = 2\cdot(1\oplus 2 \oplus 1 \oplus 3)$$$.You are given an array of length $$$n$$$: $$$a_1, a_2, \dots, a_n$$$. Append at most $$$3$$$ elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don't have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n \le 10^5)$$$ — the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0\le a_i \le 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output two lines. In the first line, output a single integer $$$s$$$ ($$$0\le s\le 3$$$) — the number of elements you want to append. In the second line, output $$$s$$$ integers $$$b_1, \dots, b_s$$$ ($$$0\le b_i \le 10^{18}$$$) — the elements you want to append to the array. If there are different solutions, you are allowed to output any of them.

NoteIn the first test case of the example, the sum of all numbers is $$$12$$$, and their $$$\oplus$$$ is $$$6$$$, so the condition is already satisfied.In the second test case of the example, after adding $$$4, 4$$$, the array becomes $$$[8, 4, 4]$$$. The sum of numbers in it is $$$16$$$, $$$\oplus$$$ of numbers in it is $$$8$$$.

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let lines = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    for (let i = 0; i < lines.length; i += 2) {
        const array = lines[i + 1].split(' ').map(Number);
        const sum = array.reduce((acc, v) => acc + v, 0);
        const xorSum = array.reduce((acc, v) => acc ^ v, 0);
        // console.log(array, 'sum, xorSum', sum, xorSum);
        if (sum === 2 * xorSum) {
            console.log(0);
            console.log();
        } else {
            let first = xorSum;
            let second = (sum + first);
            console.log(2);
            console.log(first, second);
            // assert(BigInt(sum) + BigInt(first) + BigInt(second) === BigInt(n) * (BigInt(xorSum) ^ BigInt(first) ^ BigInt(second)), 'Wrong answer 1');
        }
    }
});

function assert(condition, message) {
    if (!condition) {
        throw new Error(message);
    }
}

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let lines = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    for (let i = 0; i < lines.length; i += 2) {
        const array = lines[i + 1].split(' ').map(Number);
        const sum = array.reduce((acc, v) => acc + v, 0);
        const xorSum = array.reduce((acc, v) => acc ^ v, 0);
        // console.log(array, 'sum, xorSum', sum, xorSum);
        if (sum === 2 * xorSum) {
            console.log(0);
            console.log();
        } else {
            let first = xorSum;
            if ((sum + first) % 2 === 0) {
                let second = (sum + first);
                console.log(2);
                console.log(first, second);
                // console.log('check sum + first, xorSum ^ first', sum + first, xorSum ^ first);
                // console.log('check first, second, xorSum ^ first ^ second', first, second, xorSum ^ first ^ second, (xorSum ^ first) ^ second);
                // console.log('check first, second, xorSum ^ first ^ second', first, second, xorSum ^ first ^ second, (xorSum ^ first) ^ second);
                // console.log(0 ^ 5952667316);
                // console.log('0 ^ 134523487', 0 ^ 134523487);
                // assert(sum + first + second === 2 * (xorSum ^ first ^ second), 'Wrong answer 1');
            } else {
                let second = 1;
                let third = (sum + first + second);
                console.log(3);
                console.log(first, second, third);
                // assert(sum + first + second + third === 2 * (xorSum ^ first ^ second ^ third), 'Wrong answer 2');
            }
        }
    }
});

function assert(condition, message) {
    if (!condition) {
        throw new Error(message);
    }
}

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let lines = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    for (let i = 0; i < lines.length; i += 2) {
        const array = lines[i + 1].split(' ').map(Number);
        const sum = array.reduce((acc, v) => acc + v, 0);
        const xorSum = array.reduce((acc, v) => acc ^ v, 0);
        // console.log(array, 'sum, xorSum', sum, xorSum);
        if (sum === 2 * xorSum) {
            console.log(0);
        } else {
            let first = xorSum;
            if ((sum + first) % 2 === 0) {
                let second = (sum + first);
                console.log(first, second);
                // console.log('check', sum + first + second, 2 * (xorSum ^ first ^ second));
                assert(sum + first + second === 2 * (xorSum ^ first ^ second), 'Wrong answer');
            } else {
                let second = 1;
                let third = (sum + first + second);
                console.log(first, second, third);
                assert(sum + first + second + third === 2 * (xorSum ^ first ^ second ^ third), 'Wrong answer');
            }
        }
    }
});

function assert(condition, message) {
    if (!condition) {
        throw new Error(message);
    }
}


You are given a rooted tree, consisting of $$$n$$$ vertices. The vertices are numbered from $$$1$$$ to $$$n$$$, the root is the vertex $$$1$$$.You can perform the following operation at most $$$k$$$ times:   choose an edge $$$(v, u)$$$ of the tree such that $$$v$$$ is a parent of $$$u$$$;  remove the edge $$$(v, u)$$$;  add an edge $$$(1, u)$$$ (i. e. make $$$u$$$ with its subtree a child of the root). The height of a tree is the maximum depth of its vertices, and the depth of a vertex is the number of edges on the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all its children is $$$1$$$.What's the smallest height of the tree that can be achieved?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$0 \le k \le n - 1$$$) — the number of vertices in the tree and the maximum number of operations you can perform. The second line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$) — the parent of the $$$i$$$-th vertex. Vertex $$$1$$$ is the root. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the smallest height of the tree that can achieved by performing at most $$$k$$$ operations.

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        k = rn(),
        a = rns(n - 1).map(num => num - 1);
  a.unshift(-1);
  const g = Array.from({
    length: n
  }, () => []);
  const check = m => {
    const d = new Array(n).fill(0);
    for (let i = 1; i < n; i++) {
      g[a[i]].push(i + 1);
      d[a[i]]++;
    }
    const queue = [];
    for (let i = 0; i < n; i++) if (d[i] === 0) queue.push(i);
    const h = new Array(n).fill(0);
    let ans = 0;
    for (let v of queue) {
      const u = a[v];
      if (v && u && h[v] >= m - 1) {
        h[v] = 0;
        ans++;
      } else {
        h[u] = Math.max(h[v] + 1, h[u]);
      }
      if (--d[u] === 0) queue.push(u);
    }
    return ans <= k;
  };
  let l = 1,
      r = n - 1;
  while (l < r) {
    const m = l + r >> 1;
    if (check(m)) {
      r = m;
    } else {
      l = m + 1;
    }
  }
  return l;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        k = rn(),
        a = rns(n - 1).map(num => num - 1);
  a.unshift(-1);
  const g = Array.from({
    length: n
  }, () => []);
  const check = m => {
    const d = new Array(n).fill(0);
    for (let i = 1; i < n; i++) {
      g[a[i]].push(i + 1);
      d[a[i]]++;
    }
    const queue = [];
    for (let i = 0; i < n; i++) if (d[i] === 0) queue.push(i);
    const h = new Array(n).fill(0);
    let ans = 0;
    for (let v of queue) {
      const u = a[v];
      if (v && h[v] >= m) {
        h[v] = 0;
        ans++;
      } else {
        h[u] = Math.max(h[v] + 1, h[u]);
      }
      if (--d[u] === 0) queue.push(u);
    }
    return ans <= k;
  };
  let l = 0,
      r = n - 1;
  while (l < r) {
    const m = l + r >> 1;
    if (check(m)) {
      r = m;
    } else {
      l = m + 1;
    }
  }
  return l;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        k = rn(),
        a = rns(n - 1).map(num => num - 1);
  a.unshift(-1);
  const g = Array.from({
    length: n
  }, () => []);
  const check = m => {
    const d = new Array(n).fill(0);
    for (let i = 1; i < n; i++) {
      g[a[i]].push(i + 1);
      d[a[i]]++;
    }
    const queue = [];
    for (let i = 0; i < n; i++) if (d[i] === 0) queue.push(i);
    const h = new Array(n).fill(0);
    let ans = 0;
    for (let v of queue) {
      const u = a[v];
      if (h[v] >= m) {
        h[v] = 0;
        ans++;
      } else {
        h[u] = Math.max(h[v] + 1, h[u]);
      }
      if (--d[u] === 0) queue.push(u);
    }
    return ans <= k;
  };
  let l = 0,
      r = n - 1;
  while (l < r) {
    const m = l + r >> 1;
    if (check(m)) {
      r = m;
    } else {
      l = m + 1;
    }
  }
  return l;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        k = rn(),
        a = rns(n - 1).map(num => num - 1);
  a.unshift(-1);
  const g = Array.from({
    length: n
  }, () => []);
  const check = m => {
    const d = new Array(n).fill(0);
    for (let i = 1; i < n; i++) {
      g[a[i]].push(i + 1);
      d[a[i]]++;
    }
    const queue = [];
    for (let i = 0; i < n; i++) if (d[i] === 0) queue.push(i);
    const h = new Array(n).fill(0);
    let ans = 0;
    for (let v of queue) {
      if (h[v] >= m) {
        h[v] = -1;
        ans++;
      }
      const u = a[v];
      h[u] = Math.max(h[v] + 1, h[u]);
      if (--d[u] === 0) queue.push(u);
    }
    return ans <= k;
  };
  let l = 0,
      r = n - 1;
  while (l < r) {
    const m = l + r >> 1;
    if (check(m)) {
      r = m;
    } else {
      l = m + 1;
    }
  }
  return l;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        k = rn(),
        a = rns(n - 1).map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  const check = m => {
    const d = new Array(n).fill(0);
    for (let i = 0; i < n - 1; i++) {
      g[a[i]].push(i + 1);
      d[a[i]]++;
    }
    const queue = [];
    for (let i = 0; i < n; i++) if (d[i] === 0) queue.push(i);
    const h = new Array(n).fill(0);
    let ans = 0;
    for (let v of queue) {
      if (h[v] >= m) {
        h[v] = -1;
        ans++;
      }
      const u = a[v - 1];
      h[u] = Math.max(h[v] + 1, h[u]);
      if (--d[u] === 0) queue.push(u);
    }
    return ans <= k;
  };
  let l = 0,
      r = n - 1;
  while (l < r) {
    const m = l + r >> 1;
    if (check(m)) {
      r = m;
    } else {
      l = m + 1;
    }
  }
  return l;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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


You are given two strings $$$s$$$ and $$$t$$$, both consisting of exactly $$$k$$$ lowercase Latin letters, $$$s$$$ is lexicographically less than $$$t$$$.Let's consider list of all strings consisting of exactly $$$k$$$ lowercase Latin letters, lexicographically not less than $$$s$$$ and not greater than $$$t$$$ (including $$$s$$$ and $$$t$$$) in lexicographical order. For example, for $$$k=2$$$, $$$s=$$$"az" and $$$t=$$$"bf" the list will be ["az", "ba", "bb", "bc", "bd", "be", "bf"].Your task is to print the median (the middle element) of this list. For the example above this will be "bc".It is guaranteed that there is an odd number of strings lexicographically not less than $$$s$$$ and not greater than $$$t$$$.

The first line of the input contains one integer $$$k$$$ ($$$1 \le k \le 2 \cdot 10^5$$$) — the length of strings. The second line of the input contains one string $$$s$$$ consisting of exactly $$$k$$$ lowercase Latin letters. The third line of the input contains one string $$$t$$$ consisting of exactly $$$k$$$ lowercase Latin letters. It is guaranteed that $$$s$$$ is lexicographically less than $$$t$$$. It is guaranteed that there is an odd number of strings lexicographically not less than $$$s$$$ and not greater than $$$t$$$.

Print one string consisting exactly of $$$k$$$ lowercase Latin letters — the median (the middle element) of list of strings of length $$$k$$$ lexicographically not less than $$$s$$$ and not greater than $$$t$$$.

var stdin = "";
process.stdin.resume();
process.stdin.setEncoding('ascii');
process.stdin.on('data', function (data) { stdin += data; });
process.stdin.on('end', function () { main(stdin); });

var stdin_row = 0, stdin_rows;
function readLine() { if (!stdin_rows) stdin_rows = stdin.split("\n"); return stdin_rows[stdin_row++]; } // to trim ?
function readLineVals() { return readLine().trim().split(/\s+/); }

const debug = 0
var log = console.log;
var dbg = debug ? console.log : _ => {};

/////////////// ignore above this line ////////////////////

function main(stdin) {
	var n = readLine() * 1;
	var a = readLine().trim();
	var b = readLine().trim();
	if (n!=a.length)
		throw "input parsing pb "+n+"  a="+a;
	if (n!=b.length)
		throw "input parsing pb "+n+"  b="+b;

	z = 'z'.charCodeAt(0)
	a = Array.from(a).map(x => x.charCodeAt(0))
	b = Array.from(b).map(x => x.charCodeAt(0))
	d = new Array(n).fill(0)
	e = new Array(n).fill(0)
	f = new Array(n).fill(0)

	dbg(a)
	dbg(b)

	for (var i=n-1; i>=0; i--) {
		if (b[i]>=a[i]) {
			d[i] +=  b[i]-a[i];
		} else {
			d[i] +=  (26+b[i])-a[i];
			b[i-1]--;
		}
	}
	dbg("d final ", d)

	for (var i=0; i<n; i++) {
		if (d[i]%2) {
			e[i] += (d[i]-1)/2;
			e[i+1] += 13;
		} else {
			e[i] += d[i]/2;
		}
	}

	dbg("e final ", e)

	for (var i=n-1; i>=0; i--) {
		f[i] = a[i] + e[i]
	}
	dbg("f", f)

	for (var i=n-1; i>=0; i--) {
		while (f[i]>z) {
			f[i] = f[i] - 26
			f[i-1]++
		}
	}

	dbg("f final", f)
	log(f.map(x => String.fromCharCode(x)).join(""));

}


Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:  Include a person to the chat ('Add' command).  Remove a person from the chat ('Remove' command).  Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.

Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:   +<name> for 'Add' command.  -<name> for 'Remove' command.  <sender_name>:<message_text> for 'Send' command.  <name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line. It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc. All names are case-sensitive.

Print a single number — answer to the problem.

+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate

+Mike
-Mike
+Mike
Mike:Hi   I am here
-Mike
+Kate
-Kate

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

const input = [];
let members = 0;
let traffic = 0;
rl.on('line', function (line) {
	if (line[0] === '+') {
		members++;
	} else if (line[0] === '-') {
		members--;
	} else {
		traffic += (line.length - line.indexOf(':') - 1) * members;
	}
});

rl.on('close', function (cmd) {
	console.log(traffic);
	process.exit(0);
});

const readline = require('readline');

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

var users = [], ans = 0;

rl.on('line', (input) => {
    switch(input[0]){
        case "+":
            users.push(input.substring(1));
            break;
        case "-":
            let n = users.indexOf(input.substring(1));
            users.splice(n, 1);
            break;
        default:
            //code... input = "mike:hello"
            let colonIndex = input.indexOf(":");
            let message = input.substring(colonIndex+1);
            ans += users.length * message.length;
            break;
    }
  }).on('close',()=>{
      //
      console.log(ans);
  });

const readline = require('readline');

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

var users = [];
var ans = 0;
rl.on('line', (input) => {

    //var cmd=input[0];
    var cmd = input.charAt(0);

    switch (cmd) {
        case '+': {
            users.push(input.substring(1));
            break;
        }
        case '-': {
            let index = users.indexOf(input.substring(1));
            users.splice(index, 1);
            break;
        }
        default: {
            let index = input.indexOf(':');
            let msg = input.substring(index + 1);
            ans += msg.length * users.length;

            break;
        }
    }

});

rl.on('close', function () {
    console.log(ans);
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
/**
 * while(true){
 *  string input = Console.ReadLine();
 * }
 */
/**
 *        01234
 * input="+Mike"
 *
 * .substr(fromIndex, countLen)     c++
 * .substring(fromIndex, endIndex)  python
 *        0123456789
 * var s="ABCDEFGHIJ"     => "FGH"
 *
 * s.substr(5,3)
 * s.substring(5,8)
 *
 */
/**
 *
 * default=>
 *         0123456789
 *  input="Mike:hello"
 *           01234
 *  message="hello"
 */
var users = [], ans = 0;
rl.on('line', (input) => {
    // console.log("input= %s  len= %d", input, input.length);
    switch (input[0]) {
        case '+':
            users.push(input.substr(1));
            break;
        case '-':
            let elemInd = users.indexOf(input.substr(1));
            users.splice(elemInd, 1);
            break;
        default:
            let colonInd = input.indexOf(':');
            let message = input.substr(colonInd + 1);
            ans += message.length * users.length;
            break;

    }
}).on('close', function () {
    // console.log('inside close  function');
    console.log(ans);
});

const readline = require('readline');

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

var users=[],ans=0;

rl.on('line', (input) => {

   switch (input[0]){
        case '+':
            users.push(input.substring(1));
            break;
        case '-':
            users.splice(users.indexOf(input.substring(1)),1);
            break;
        default:
            var message = input.substring(input.indexOf(':') + 1);
            ans += message.length * users.length;
            break;
   }
  }).on('close',()=>{
      console.log(ans);
  });

function solve(lns) {
  const s = new Set();
  let result = 0;
  for (const ln of lns) {
    const f = ln[0];
    const r = ln.substring(1);
    if (f === '+') {
      s.add(r);
    } else if (f === '-') {
      s.delete(r);
    } else {
      const [_, m] = ln.split(/:/);
      result = result + (m.length * s.size);
    }
  }
  return result;
}

function main(lines) {
  const trim_lines = [];
  for (const line of lines) {
    const t = line.trim();
    if (t.length > 0) {
      trim_lines.push(t);
    }
  }
  const result = solve(trim_lines);
  console.log(result);
}

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding("utf-8");
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
}

processLinesFromStream(process.stdin, main);

const readline = require('readline');

const INPUT = 'test.in';
const LOCAL = process.env.ENABLE_LOCAL_ENV === 'true';
const log = (...args) => {
    LOCAL && console.log(...args)
};
let rl;
let lineNr = 0;

/**
 * MAIN
 */
(async () => {
    const promises = await setup(INPUT);
    await Promise.all(promises);
    process.stdout.write(res.toString());
})();

function setup() {
    const promises = []
    rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false,
    });

    rl.on('line', (line) => {
        promises.push(work(line, lineNr));
        lineNr++;
    });

    rl.on('error', (err) => {
        log('Error:', err);
    });

    return new Promise(res => {
        rl.on('close', () => {
            res(promises)
            log('Done!');
        });
    });
}

let people = 0;
let res = 0;
async function work(line, lineNr) {
    if (line.startsWith('+')) {
        people++;
    } else if (line.startsWith('-')) {
        people--;
    } else {
        // console.log(line, line.trim().split(':')[1].length);
        res += (people * (line.trim().split(':')[1].length));
    }
}

/**
 *
 * Solution goes below
 *
 */
function solve(line) {

}

const readline = require('readline');

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

var users=[], ans=0;
rl.on('line', (input) => {
    switch(input[0]){
      case '+':
          // here we want to add user in our users array/list
          // for example when input ="+mike" we add only mike without + sign
          users.push(input.substr(1));
          break;
      case '-':
          //here we want to remove this user from our users array/list
          // for examle if input = "-mike" we remove "mike"
          // to remove an element from array we should use splice built in method in javascript
          //so goole that and find out by yourself
          let ind = users.indexOf(input.substr(1));
          users.splice(ind, 1);
          break;
       default:
          // here you decide what you do...
          //good luck......
          let colonInd = input.indexOf(':');
          let msg = input.substr(colonInd+1);
          ans+=msg.length*users.length;

          break;
    }//end of switch loop
}).on('close',()=>{
    //output your answer here when you push ctrl + c
    console.log(ans);
});

const readline = require('readline');

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

var Users = [],ans = 0;

rl.on('line', (input) => {
       switch(input[0]){
           case '+':
               Users.push(input.substring(1));
               break;
           case '-':
               let ind = Users.indexOf(input.substring(1));
               Users.splice(ind,1);
               break;
            default :
               let indx = input.indexOf(':') + 1;
               let message = input.substring(indx);
               ans += message.length * Users.length;
               break;
       }

}).on('close',()=>{
    console.log(ans);
});

const readline = require("readline");

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

var cont = [];
var ans = 0;

rl.on("line", input => {

  switch (input[0]) {
    case "+":
      cont.push(input.substr(1));
      break;
    case "-":
      var ind = cont.indexOf(input.substr(1));
      cont.splice(ind, 1);
      break;
    default:
      var ind = input.indexOf(":");
      var msg = input.substr(ind + 1);
      ans += cont.length * msg.length;
      break;
  }
}).on("close", () => {
  console.log(ans);
});

/* rl.on('close' ,()=>{

    console.log("test")

});*/

const readline = require('readline');

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

var users = [];
var ans = 0;
rl.on('line', (input) => {
    // console.log("input = %s",input);
    switch (input[0]) {
        case '+':
            users.push(input.substring(1));
            break;
        case '-':
            users.splice(users.indexOf(input.substring(1)), 1);
            break;
        default:
            var colonIndex = input.indexOf(':');
            var msg = input.substring(colonIndex + 1);
            ans += msg.length * users.length;
            break;
    };

}).on('close', () => {
    console.log(ans);
});

/*
rl.on('close', () => {
    console.log(ans);
});
*/

var line;
var c=0;
var ret=0;
while(line = readline()){
	if(line[0] == '+'){
		c++;
	}else if(line[0] == '-'){
		c--;
	}else{
		ret += line.split(':')[1].length * c;
	}
}
print(ret);

var counter = 0;
var users = [];
var cmd = "";
while (cmd != undefined) {
    cmd = readline();

    if (!cmd) { break; }

    switch (cmd.charAt(0)) {
        case "+":
            var commer = cmd.slice(1);
            users.push(commer);
            break
        case "-":
            var leaver = cmd.slice(1);
            users = users.filter(function (e) { return e != leaver });
            break
        default:
            var msg = cmd.slice(cmd.indexOf(":") + 1);
            counter += users.length * msg.length;
    }
}
print(counter);

var line
var inch = 0
var s = 0
while (line = readline()) {
	if (line[0] == '-') {inch--; continue}
	if (line[0] == '+') {inch++; continue}
	var m = line.split(':')[1]
	s += m.length * inch
}
print(s)

var count = 0;
var com;
var m = '-'.charCodeAt(0);
var p = '+'.charCodeAt(0);
var pattern = /:(\w| )*/;
var res = 0;
while((com = readline())) {
  if(com.charCodeAt(0) === m) {
    count--;
  }
  if(com.charCodeAt(0) === p) {
    count++;
  }
  if((com = com.match(pattern))) {
    res += (com[0].length - 1) * count;
  }
}
print(res);

// Generated by CoffeeScript 1.4.0
(function() {
  var line, n, t;

  n = 0;

  t = 0;

  while (line = readline()) {
    switch (line[0]) {
      case '+':
        n++;
        break;
      case '-':
        n--;
        break;
      default:
        t += n * (line.length - line.indexOf(':') - 1);
    }
  }

  print(t);

}).call(this);

var count = 0
var attendees = 0
while (line = readline()) {
    if (line[0] == "+") {
        attendees++
    }
    if (line[0] == "-") {
        attendees--
    }
    if (line[0] != "+" && line[0] != "-") {
        message = line.substr(line.indexOf(":") + 1)
        count += message.length*attendees
    }
}

print(count)

function userAdd(user){
    if (userList.indexOf(user) === -1) userList.push(user);
}

function userRemove(user){
    var id = userList.indexOf(user);
    if (id !== -1) userList.splice(id, 1);
}

function send(msg){
    traffic += msg.length * userList.length;
}

var i, input, cmd, temp, userList = [], traffic = 0;

while (true){
    input = readline();
    if (typeof input === 'undefined') break;

    cmd = input.substr(0,1);
    if (cmd === '+') {
        userAdd(input.substr(1));
    } else if (cmd === '-') {
        userRemove(input.substr(1));
    } else {
        send(input.split(':')[1]);
    }
}

print(traffic);

var users = 0;
var mes = 0;
var result = 0;
var mass = [];
while (line = readline()) {
    line = line.split(":")
    if (line[0][0]=="+") {
        users++;
    }
    if (line[0][0]=="-") {
        users--;
    }
    if (line[1]!=undefined) {
        mes = line[1].length;
        result += mes*users;
    }
}

write(result);

const readline = require('readline');

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

var users = [];
 var ans=0;
rl.on('line', (input) => {
    if (input != "" && input != null) {

        //var cmd=input[0];
        var cmd = input.charAt(0);

        switch(cmd){
            case '+':{
                users.push(input.substring(1));
                 break;
            }
            case '-':{
                let index = users.indexOf(input.substring(1));
                users.splice(index,1);
                break;
            }
            default:{
                  let index=input.indexOf(':');
                  let msg=input.substring(index+1);
                  ans+=msg.length*users.length;

                break;
            }
        }
    }
    else{
        console.log(ans);
         rl.close();
    }

});

const readline = require("readline");

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

var cont = [];
var ans = 0;

rl.on("line", input => {
  console.log(`Received: ${input}`);

  switch (input[0]) {
    case "+":
      cont.push(input.substr(1));
      break;
    case "-":
      var ind = cont.indexOf(input.substr(1));
      cont.splice(ind, 1);
      break;
    default:
      var ind = input.indexOf(":");
      var msg = input.substr(ind + 1);
      ans += cont.length * msg.length;
      break;
  }
}).on("close", () => {
  console.log(ans);
});

/* rl.on('close' ,()=>{

    console.log("test")

});*/

t=0;
n=0;
while (c=readline(),c!=null) {
	if (c[0]==="+") n++;
	else if (c[0]==="-") n--;
	else {
		print(c.length,c.search(":"),n);
		t+=(c.length-c.search(":")-1)*n;
	}
}
print(t);


Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:   The product of all numbers in the first set is less than zero ( < 0).  The product of all numbers in the second set is greater than zero ( > 0).  The product of all numbers in the third set is equal to zero.  Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.

The first line of the input contains integer n (3 ≤ n ≤ 100). The second line contains n space-separated distinct integers a1, a2, ..., an (|ai| ≤ 103) — the array elements.

In the first line print integer n1 (n1 > 0) — the number of elements in the first set. Then print n1 numbers — the elements that got to the first set. In the next line print integer n2 (n2 > 0) — the number of elements in the second set. Then print n2 numbers — the elements that got to the second set. In the next line print integer n3 (n3 > 0) — the number of elements in the third set. Then print n3 numbers — the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.

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

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}

function main() {
  const len = +readLine();
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));

  const [plusArr, minusArr, zeroArr] = [[], [], []];
  for (let i = 0; i < len; i++) {
    if (arr[i] > 0) plusArr.push(arr[i]);
    else if (arr[i] < 0) minusArr.push(arr[i]);
    else zeroArr.push(arr[i]);
  }

  if (plusArr.length === 0) {
    plusArr.push(minusArr.pop());
    plusArr.push(minusArr.pop());
  }
  if (minusArr.length % 2 === 0) {
    zeroArr.push(minusArr.pop());
  }

  console.log(`${minusArr.length} ${minusArr.join(" ")}`);
  console.log(`${plusArr.length} ${plusArr.join(" ")}`);
  console.log(`${zeroArr.length} ${zeroArr.join(" ")}`);
}

let input = ''

// Input
process.stdin.on('data', line => {
	input += line
})

// Process
process.stdin.on('end', () => {
	const { EOL } = require('os')
	const lines = input.split(EOL).filter(data => data)

	const n = +lines[0]
	const numList = lines[1].split(' ').map(num => +num).sort((prev, cur) => prev - cur)
	console.log(`1 ${numList[0]}`)
	if (numList[n - 1] === 0) {
		console.log(`2 ${numList[1]} ${numList[2]}`)
		console.log(`${n - 3} ${numList.slice(3).join(' ')}`)
	}
	else {
		console.log(`1 ${numList[n - 1]}`)
		console.log(`${n - 2} ${numList.slice(1).slice(0, -1).join(' ')}`)
	}
})

var n=+readline(),
a=readline().split(' ').map(Number),
n1=a.filter(function(v){return v<0;}),
n2=a.filter(function(v){return v>0;}),
n3=a.filter(function(v){return v===0;});
if(n2.length===0){
	n2.push(n1.pop());
	n2.push(n1.pop());
}
if(n1.length%2===0){
	n3.push(n1.pop());
}
print(n1.length+' '+n1.join(' '));
print(n2.length+' '+n2.join(' '));
print(n3.length+' '+n3.join(' '));

;(function () {
	var n = +readline();
	var c = readline().split(' ').map(Number);

	print(1, c.splice(c.indexOf(Math.min.apply(null, c)), 1));
	var m = c.splice(c.indexOf(Math.max.apply(null, c)), 1);
	if ( m > 0 ) {
		print(1, m);
		print(n - 2, c.join(' '));
	} else if ( m == 0 ) {
		print(2, c.splice(c.indexOf(Math.min.apply(null, c)), 1), c.splice(c.indexOf(Math.min.apply(null, c)), 1));
		print(n - 3, c.join(' '), m);
	} else {
		print(2, m, c.splice(c.indexOf(Math.max.apply(null, c)), 1));
		print(n - 3, c.join(' '));
	}
}).call(this);

var a = [], b = [], c = [], r = [];
readline();
readline().split( ' ' ).forEach( function(item) {
    item = item - '';
    if (item < 0 && r.length < 2) {
        r.push( item );
    } else if (item < 0 && !a.length) {
        a.push( item );
    } else if (item < 0) {
        c.push( item );
    } else if (item > 0) {
        b.push( item );
    } else {
        c.push( item );
    }
} );

if (!b.length) {
    b.push( r.shift() );
    b.push( r.shift() );
}

if (!a.length) {
    a.push( r.shift() );
}

c.push.apply( c, r );

printArr( a );
printArr( b );
printArr( c );

function printArr(arr) {
    print( arr.length + ' ' + arr.join( ' ' ) );
}

let input = ''

// Input
process.stdin.on('data', line => {
	input += line
})

// Process
process.stdin.on('end', () => {
	const { EOL } = require('os')
	const lines = input.split(EOL).filter(data => data)
	console.log(lines)
})

let input = ''

// Input
process.stdin.on('data', line => {
	input += line
})

// Process
process.stdin.on('end', () => {
	const lines = input.split('\n')
	console.log(lines)
})

let input = ''

// Input
process.stdin.on('data', line => {
	input += line
})

// Process
process.stdin.on('end', () => {
	const { EOL } = require('os')
	const lines = input.split(EOL)
	console.log(lines)
})

var a = [], b = [], c = [], r = [];
readline();
readline().split( ' ' ).forEach( function(item) {
    item = item - '';
    if (item < 0 && r.length < 2) {
        r.push( item );
    } if (item < 0 && !a.length) {
        a.push( item );
    } else if (item < 0) {
        c.push( item );
    } else if (item > 0) {
        b.push( item );
    } else {
        c.push( item );
    }
} );

if (!b.length) {
    b.push( r.shift() );
    b.push( r.shift() );
}

if (!a.length) {
    a.push( r.shift() );
}

c.push.apply( c, r );

printArr( a );
printArr( b );
printArr( c );

function printArr(arr) {
    print( arr.length + ' ' + arr.join( ' ' ) );
}

var a = [], b = [], c = [], r = [];
readline();
readline().split( ' ' ).forEach( function(item) {
    item = item - '';
    if (item < 0 && r.length < 2) {
        r.push( item );
    } if (item < 0 && !a.length) {
        a.push( item );
    } else if (item < 0) {
        c.push( item );
    } else if (item > 0) {
        b.push( item );
    } else {
        c.push( item );
    }
} );

if (!b.length) {
    b.push.apply( b, r ); r = [];
} else if (!a.length) {
    a.push( r.shift() );
}

c.push.apply( c, r );

printArr( a );
printArr( b );
printArr( c );

function printArr(arr) {
    print( arr.length + ' ' + arr.join( ' ' ) );
}


Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers.Sonya has drawn $$$n$$$ numbers in a row, $$$a_i$$$ is located in the $$$i$$$-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will give a number to each robot (they can be either same or different) and run them. When a robot is running, it is moving toward to another robot, reading numbers in the row. When a robot is reading a number that is equal to the number that was given to that robot, it will turn off and stay in the same position.Sonya does not want robots to break, so she will give such numbers that robots will stop before they meet. That is, the girl wants them to stop at different positions so that the first robot is to the left of the second one.For example, if the numbers $$$[1, 5, 4, 1, 3]$$$ are written, and Sonya gives the number $$$1$$$ to the first robot and the number $$$4$$$ to the second one, the first robot will stop in the $$$1$$$-st position while the second one in the $$$3$$$-rd position. In that case, robots will not meet each other. As a result, robots will not be broken. But if Sonya gives the number $$$4$$$ to the first robot and the number $$$5$$$ to the second one, they will meet since the first robot will stop in the $$$3$$$-rd position while the second one is in the $$$2$$$-nd position.Sonya understands that it does not make sense to give a number that is not written in the row because a robot will not find this number and will meet the other robot.Sonya is now interested in finding the number of different pairs that she can give to robots so that they will not meet. In other words, she wants to know the number of pairs ($$$p$$$, $$$q$$$), where she will give $$$p$$$ to the first robot and $$$q$$$ to the second one. Pairs ($$$p_i$$$, $$$q_i$$$) and ($$$p_j$$$, $$$q_j$$$) are different if $$$p_i\neq p_j$$$ or $$$q_i\neq q_j$$$.Unfortunately, Sonya is busy fixing robots that broke after a failed launch. That is why she is asking you to find the number of pairs that she can give to robots so that they will not meet.

The first line contains a single integer $$$n$$$ ($$$1\leq n\leq 10^5$$$) — the number of numbers in a row. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1\leq a_i\leq 10^5$$$) — the numbers in a row.

Print one number — the number of possible pairs that Sonya can give to robots so that they will not meet.


Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:  Walk up or down one unit on a tree.  Eat a nut on the top of the current tree.  Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h > hi + 1. Compute the minimal time (in seconds) required to eat all nuts.

The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.

Print a single integer — the minimal time required to eat all nuts in seconds.

var n=+readline();
var ans=0;
var prev=0;
while(n--){
  h=+readline();
  ans+=Math.abs(h-prev)+2;
  prev=h;
}
print(ans-1);

;(function () {

	print((function (n) {
		var p = -1, h = 0;
		while (n--) {
			var s = +readline();
			p += 2 + Math.abs(s-h);
			h = s;
		}
		return p;
	})(+readline()));

}).call(this);


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 given number $$$n$$$ you need to make a permutation $$$p$$$ such that two requirements are satisfied at the same time:  For each element $$$p_i$$$, at least one of its neighbors has a value that differs from the value of $$$p_i$$$ by one. That is, for each element $$$p_i$$$ ($$$1 \le i \le n$$$), at least one of its neighboring elements (standing to the left or right of $$$p_i$$$) must be $$$p_i + 1$$$, or $$$p_i - 1$$$.  the permutation must have no fixed points. That is, for every $$$i$$$ ($$$1 \le i \le n$$$), $$$p_i \neq i$$$ must be satisfied. Let's call the permutation that satisfies these requirements funny.For example, let $$$n = 4$$$. Then [$$$4, 3, 1, 2$$$] is a funny permutation, since:   to the right of $$$p_1=4$$$ is $$$p_2=p_1-1=4-1=3$$$;  to the left of $$$p_2=3$$$ is $$$p_1=p_2+1=3+1=4$$$;  to the right of $$$p_3=1$$$ is $$$p_4=p_3+1=1+1=2$$$;  to the left of $$$p_4=2$$$ is $$$p_3=p_4-1=2-1=1$$$.  for all $$$i$$$ is $$$p_i \ne i$$$. For a given positive integer $$$n$$$, output any funny permutation of length $$$n$$$, or output -1 if funny permutation of length $$$n$$$ does not exist.

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. Each test case consists of f single line containing one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print on a separate line:    any funny permutation $$$p$$$ of length $$$n$$$;  or the number -1 if the permutation you are looking for does not exist.

NoteThe first test case is explained in the problem statement.In the second test case, it is not possible to make the required permutation: permutations $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[3, 2, 1]$$$ have fixed points, and in $$$[2, 3, 1]$$$ and $$$[3, 1, 2]$$$ the first condition is met not for all positions.

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();
  });
  solve();
});
function readline() {
  return inputString[currentLine++];
}

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var p = parseInt(readline().trim());
    var o = [], popped = [];
    if (p == 3) {
      process.stdout.write('-1\n');
      continue;
    }
    if (p % 2 === 0) {
      for (var i = p; i > 0; i--) {
        o.push(i);
        if (i - 0 == 1) {
          o = o.join(' ')
          process.stdout.write(o + '\n');
        }
      }
    } else {
      o = [];
      for (var i = p; i > 0; i--) {
        o.push(i);
        if (i - 0 == 1) {
          o.reverse()
          popped.push(o.pop())
          popped.push(o.pop())
          o.unshift(popped[1].toString(), popped[0].toString())
          process.stdout.write(o.join(' ') + '\n')
        }
      }
    }
  }
}

'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() {
    const testCases = Number(readline());
    for (let i = 0; i < testCases; i++) {
        let n = Number(readline());
        let ans = generateFunnyPermutation(n);
        console.log(ans === -1 ? -1 : ans.join(" "))
    }
}

function generateFunnyPermutation(n) {
    if (n === 2) return [2,1];
    if (n === 3) return -1;
    let arr = Array(n);
    for (let i = 0; i < n; i++) {
        arr[i] = i+1;
    }
    let mid = Math.floor((n-1)/2);
    rotateArr(arr, 0, n-1);
    rotateArr(arr, 0, mid);
    rotateArr(arr, mid+1, n-1);

    return arr;
}

function rotateArr(arr, s, e) {
    let start = s, end = e;

    while (start < end) {
        let tmp = arr[start];
        arr[start] = arr[end];
        arr[end] = tmp;
        start++;
        end--;
    }
}

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++]
        output[i] = solve(n)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n) {
    if (n === 3) return -1
    if (n === 5) return '5 4 1 2 3'
    const arr = Array(n)
    if (n & 1) {
        for (let i = 0; i < n; i++) {
            arr[i] = (i & 1) ? i : i + 2
            arr[i] += 3
        }
        arr[n - 3] = 3
        arr[n - 2] = 2
        arr[n - 1] = 1
    } else {
        for (let i = 0; i < n; i++) {
            arr[i] = (i & 1) ? i : i + 2
        }
    }
    return arr.join(' ')
}

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

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

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    if (n === 3) console.log(-1);
    else if (n % 2 === 0)
      console.log(
        new Array(n)
          .fill(0)
          .map((a, i) => n - i)
          .join(" ")
      );
    else {
      let k = Math.ceil(n / 2);
      let arr = new Array(k).fill(0).map((a, i) => k + i);
      for (let i = k - 1; i >= 1; i--) arr.push(i);
      console.log(arr.join(" "));
    }
  }
};
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();
    });

    mufin();
});

function readLine() {
    return inputString[currentLine++];
}
/* let arr = readLine().split(" ").map((x) => {return parseInt(x)});
let test = readLine();
while(test--)
{

}
*/
const y = [];
const z = [];
let ptr;
var gcd = function(a, b) {
    if (!b) {
    return a;
    }
    return gcd(b, a % b);
}

function add(x1, y1, z1)
{
    y1 = y1 / x1; z1 = z1 / x1;
    for(let i = 0; i < ptr; i++)
        if ((Math.abs(y1 - y[i]) < 0.000001) && (Math.abs(z1 - z[i]) < 0.000001))
        return 0;
    y[ptr] = y1; z[ptr] = z1;
    return ++ptr;
    }
    function sort(a, b) {
        if (a < b) {
        return -1;
        }
        if (a > b) {
        return 1;
        }
        return 0;
    }
function triangle(a, b, c)
{
    let temp = [a,b,c];
    sort(temp,temp+3);
    if(!add(temp[0],temp[1],temp[2])) return;
    let m = Math.sqrt(2*temp[0]*temp[0] + 2*temp[1]*temp[1] - temp[2]*temp[2]) / 2;
    triangle(temp[0],m,temp[2]/2);
    triangle(temp[1],m,temp[2]/2);
}
function f(n,a,b){
    let i;
    a[1] = 0; a[2] = 3;
    b[1] = 3; b[2] = 6;
    for(i = 3; i <= n; i++){
        a[i] = a[i-1] + b[i-1];
        b[i] = 2 * a[i-1] + b[i-1];
    }
    return a[n] + b[n];

}

function ff(n, k) {
    if (!n){
        return 0;
    }
    let tmp = 1 << (n - 1);
    if (k < tmp) return ff(n - 1, k);
    return tmp + ff(n - 1, (1 << n) - 1 - k);
}

function div(val, by){
    return (val - val % by) / by;
}
function PowMod(x, y, n)
{
    console.log(x * x % n)
	if (y === 0) {
        return 1;
    }
	if (y&1){
        return x * PowMod(x * x % n, div(y,2), n) % n;
    }
	return PowMod(x * x % n, div(y,2), n);
}
function binomial(n, k) {
    if ((typeof n !== 'number') || (typeof k !== 'number'))
    return false;
    var coeff = 1;
   for (var x = n-k+1; x <= n; x++) coeff *= x;
    for (x = 1; x <= k; x++) coeff /= x;
    return coeff;
}
function factorial(x) {

    if (x == 0) {
        return 1;
    }
    else {
        return x * factorial(x - 1);
    }
}
const fact = (a, b, c, x, y, z) => {
    return Math.sqrt(( x - a )*( x - a ) + ( y - b )*( y - b ) + ( z - c )*( z - c ));
}
function app(a,n1,n2,n3)
{
    if (a == 0){
        return 0;
    }
    app(a - 1, n1, n3, n2);
    if ((n1 + ' ' + n2) === undefined) {
        return 0;
    }
    console.log(n1 + ' ' + n2);
    app(a - 1, n3,n2,n1);
}

const diffDays = (day1, day2) => {
        if ((day1[6] !== day2[6] || day1[5] !== day2[5]) || (day1[8] !== day2[8] || day1[9] !== day2[9])) {
            return 1;
        }
        else{
            return 0;
        }
}

// 2022-03-19T06:06:00.000Z
// 2022-03-19T04:04:00.000Z
let pi = 3.14159265359;

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}
//Set.prototype.getByIndex = function(index) { return [...this][index]; }
//let mySet = new Set();
function mufin() {
    let k = readLine();
    while(k--){
        let n = readLine();
        if(n == 3)
            console.log(-1);
        else
        {
            if(n % 2 == 0){
                for(let i = 1; i <= n; i+=2)
                {
                    process.stdout.write(`${i+1} ${i} `);
                }
                process.stdout.write(`\n`);
            } else
            {
                process.stdout.write(`${n} ${n-1} `);
                for(let i = 1; i <= n-2; i++)
                    process.stdout.write(`${i} `);
                process.stdout.write(`\n`);
            }

        }

    }
}
function Fibonacci(n){
    if (n == 1) {
        return 1;
      }
      if (n == 2) {
        return 1;
      }
      if (n == 3) {
        return 1;
      }
      if (a[n] != -1) {
        return a[n];
      }
      if (n % 2 == 1) {
        return a[n] = Fibonacci(n - 1) + Fibonacci(n - 3);
      }
      return a[n] = Fibonacci(n - 1);

}
function io(x, y){
    if (x <= 0 || y <= 0) {
        return 0;
    }
    if (x < y) {
        return io(x-1, y-2) +  io(x-2, y-1);
    }
    if (x > y) {
        return io(x-2, y-2) + 1;
    }
}
function ctl(a)
{
    if(a==1){
        return 2;
    }
    if(a==2){
        return 4;
    }
    return ctl(a-1)+ctl(a-2);
}

/*
** Template
*/

// Common Template Starts //
//*
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = "";
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Common Template Ends //

// Driver Function Starts //
const main = () => {
    console.clear()
    let t = parseInt(readline())
    while (t--) {
        let n = parseInt(readline())
        console.log(solve(n))
    }
}
// Driver Function Ends //

// MAIN LOGIC
const solve = (n) => {

    if (n == 1) return "1"
    else if (n == 2) return "2 1"
    else if (n == 3) return "-1"
    else if (n == 4) return "4 3 1 2"
    else {
        let lim = Math.floor(n / 2) + 1
        let res = ''
        for (let i = n; i > lim; i--) res += i + ' '
        for (let i = 1; i <= lim; i++) res += i + ' '
        return res
    }
}

const isOdd = (num) => num & 1
const isEven = (num) => !(num & 1)
const minOfArray = (arr) => Math.min.apply(null, arr)
const maxOfArray = (arr) => Math.max.apply(null, arr)
const uniqueArray = (arr) => [...new Set(arr)]
const sortArray = (arr) => arr.sort((a, b) => a - b)
const sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)

'use strict';

var fs = require('fs');

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

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

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

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

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		if(N == 3){
			myout(-1);
			continue;
		}else if(N == 2){
			myout("2 1");
			continue;
		}
		var output = new Array(N);
		output[0] = N - 1;
		output[1] = N;
		for(var i = 2; i < N; i++){
			output[i] = i - 1;
		}
		myout(myconv(output, 8));
	}
}

var tcn = readline()

for(var tc = 0; tc < tcn; tc++) {
    var n = readline()
    var result = []

    if (n == 3 || n == 1) {
        print('-1')
    }
    else if (n % 2 == 0) {
        for(var j = 0; j < n/2; j++) {
            result.push(2*j + 2)
            result.push(2*j + 1)
        }
    }
    else {
        for(var j = (n - 1) / 2; j > 1; j--) {
            result.push(2*j)
            result.push(2*j + 1)
        }
        result.push(1)
        result.push(2)
        result.push(3)
    }

    result.forEach(x => write(`${x} `))
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var value = parseInt(readline());
    var result = "";
    if (value === 3)
    {
        result = -1;
    }
    else
    {
        result += `${value} ${value-1} `;
        for (var j = 1; j < value-1; j++)
        {
            result += `${j} `;
        }
    }
    print(result);
}

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();
  });
  solve();
});
function readline() {
  return inputString[currentLine++];
}

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var p = parseInt(readline().trim());
    var o = [], popped = [];
    if (p == 3) {
      process.stdout.write('-1\n');
      continue;
    }
    if (p % 2 === 0) {
      for (var i = p; i > 0; i--) {
        o.push(i);
        if (i - 0 == 1) {
          o = o.reverse().join(' ')
          process.stdout.write(o + '\n');
        }
      }
    } else {
      o = [];
      for (var i = p; i > 0; i--) {
        o.push(i);
        if (i - 0 == 1) {
          o.reverse()
          popped.push(o.pop())
          popped.push(o.pop())
          o.unshift(popped[1].toString(), popped[0].toString())
          process.stdout.write(o.join(' ') + '\n')
        }
      }
    }
  }
}

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();
  });
  solve();
});
function readline() {
  return inputString[currentLine++];
}

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var p = parseInt(readline().trim());
    if (p == 3) {
      process.stdout.write('-1\n');
      continue;
    }
    if (p % 2 === 0) {
      var o = [];
      for (var i = p; i > 0; i--) {
        o.push(i);
        if (i - 0 == 1) {
          o = o.reverse().join(' ')
          process.stdout.write(o + '\n');
        }
      }
    } else {
      var o = [], popped = [];
      for (var i = p; i > 0; i--) {
        o.push(i);
        if (i - 0 == 1) {
          popped.push(o.pop())
          popped.push(o.pop())
          popped = popped.reverse();
          o.unshift(popped[0], popped[1])
          process.stdout.write(o + '\n')
        }
      }
    }
  }
}

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();
  });
  solve();
});
function readline() {
  return inputString[currentLine++];
}

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var p = parseInt(readline().trim());
     var o = [], popped = [];
    if (p % 2 === 0) {
      for (var i = p; i > 0; i--) {
        o.push(i);
        if (i - 0 == 1) {
          o = o.join(' ')
          process.stdout.write(o + '\n');
        }
      }
    } else {
      o = [];
      for (var i = p; i > 0; i--) {
        o.push(i);
        if (i - 0 == 1) {
          o.reverse()
          popped.push(o.pop())
          popped.push(o.pop())
          o.unshift(popped[1].toString(), popped[0].toString())
          process.stdout.write(o.join(' ') + '\n')
        }
      }
    }
  }
}

'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() {
    const testCases = Number(readline());
    for (let i = 0; i < testCases; i++) {
        let n = Number(readline());
        let ans = generateFunnyPermutation(n);
        console.log(ans === -1 ? -1 : ans.join(" "))
    }
}

function generateFunnyPermutation(n) {
    if (n === 2) return [2,1];
    if (n === 3) return -1;
    let arr = Array(n);
    for (let i = 0; i < n; i++) {
        arr[i] = i+1;
    }
    let mid = Math.floor(n/2);
    rotateArr(arr, 0, n-1);
    rotateArr(arr, 0, mid);
    rotateArr(arr, mid+1, n-1);

    return arr;
}

function rotateArr(arr, s, e) {
    let start = s, end = e;

    while (start < end) {
        let tmp = arr[start];
        arr[start] = arr[end];
        arr[end] = tmp;
        start++;
        end--;
    }
}

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++]
        output[i] = solve(n)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n) {
    if (n === 3) return -1
    const arr = Array(n)
    if (n & 1) {
        for (let i = 0; i < n; i++) {
            arr[i] = (i & 1) ? i : i + 2
            arr[i] += 3
        }
        arr[n - 3] = 3
        arr[n - 2] = 2
        arr[n - 1] = 1
    } else {
        for (let i = 0; i < n; i++) {
            arr[i] = (i & 1) ? i : i + 2
        }
    }
    return arr.join(' ')
}

var tcn = readline()

for(var tc = 0; tc < tcn; tc++) {
    var n = readline()
    var result = []

    if (n == 3 || n == 1) {
        print('-1')
    }
    else if (n % 2 == 0) {
        for(var j = 0; j < n/2; j++) {
            result.push(2*j + 2)
            result.push(2*j + 1)
        }
    }
    else {
        for(var j = (n - 1) / 2; j > 1; j--) {
            result.push(2*j)
            result.push(2*j + 1)
        }
        result.push(1)
        result.push(2)
        result.push(3)
    }
}

result.forEach(x => write(`${x} `))

var tcn = readline()

for(var tc = 0; tc < tcn; tc++) {
    var n = readline()
    var result = []

    if (n == 3 || n == 1) {
        print('-1')
    }
    else if (n % 2 == 0) {
        for(var j = 0; j < n/2; j++) {
            result.push(2*j + 2)
            result.push(2*j + 1)
        }
    }
    else {
        for(var j = (n - 1) / 2; j > 1; j--) {
            result.push(2*j)
            result.push(2*j + 1)
        }
        result.push(1)
        result.push(2)
        result.push(3)
    }
}

result.forEach(x => print(`${x} `))