This is the easy version of the problem. The only difference is the constraints on $$$n$$$ and $$$k$$$. You can make hacks only if all versions of the problem are solved.You have a string $$$s$$$, and you can do two types of operations on it:   Delete the last character of the string.  Duplicate the string: $$$s:=s+s$$$, where $$$+$$$ denotes concatenation. You can use each operation any number of times (possibly none).Your task is to find the lexicographically smallest string of length exactly $$$k$$$ that can be obtained by doing these operations on string $$$s$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:  $$$a$$$ is a prefix of $$$b$$$, but $$$a\ne b$$$;  In the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 5000$$$) — the length of the original string $$$s$$$ and the length of the desired string. The second line contains the string $$$s$$$, consisting of $$$n$$$ lowercase English letters.

Print the lexicographically smallest string of length $$$k$$$ that can be obtained by doing the operations on string $$$s$$$.

NoteIn the first test, it is optimal to make one duplication: "dbcadabc" $$$\to$$$ "dbcadabcdbcadabc".In the second test it is optimal to delete the last $$$3$$$ characters, then duplicate the string $$$3$$$ times, then delete the last $$$3$$$ characters to make the string have length $$$k$$$."abcd" $$$\to$$$ "abc" $$$\to$$$ "ab" $$$\to$$$ "a" $$$\to$$$ "aa" $$$\to$$$ "aaaa" $$$\to$$$ "aaaaaaaa" $$$\to$$$ "aaaaaaa" $$$\to$$$ "aaaaaa" $$$\to$$$ "aaaaa".

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

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

function main () {
	const [n, k] = rna();
	let s = rl();

	let i = 1, p = 0;
	for (; i < s.length; i++) {
		if (s[i] < s[p]) {
			p = 0;
		} else if (s[i] == s[p]) {
			p++;
		} else {
			break;
		}
	}
	i = i - p;

	s = s.slice(0, i);
	s = s.repeat(Math.ceil(k/i));
	const ans = s.slice(0, k);

	console.log(ans);
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    let n, k;
    [n,k] = ((await getLine())).split(' ').map(num => parseInt(num));
    let s = await getLine();
    const output = function(l) {
        for(let i = 0; i<k; i++) {
            rl.output.write(s.charAt(i%l));
        }
    }
    for(let i = 1; i < s.length && i < k; i++) {
        let j;
        for(j = 0; i + j < s.length && s.charAt(j) === s.charAt(i+j); j++);
        if (i + j < s.length && s.charAt(j) < s.charAt(i + j) || i + j >= s.length){
            output(i);
            return;
        }
    }
    output(s.length);

}

solve();

function solve() {
   var nk = readArray(Number);
   var n = nk[0];
   var k = nk[1];
   var str = read();
   var current = 1;
   var savepoint;
   var check;
   while(true) {
      if (current >= n) {
         break;
      }
      if (str[current] > str[0]) {
         str = str.substr(0, current);
         break;
      }
      if (str[current] < str[check]) {
         current++;
         continue;
      }
      savepoint = current;
      check = 0;
      while (current < 3 * n && str[current % n] === str[check]) {
         current++;
         check++;
         if (check >= savepoint) {
            check = 0;
         }
      }
      if (current !== 3 * n && str[current % n] > str[check]) {
         str = str.substr(0, savepoint);
         break;
      }
   }
   while(str.length < k) {
      str = str + str;
   }
   write(str.substr(0, k));
}

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

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

function readArray(mapF) {
   var res = read().split(' ');
   if (mapF) {
      res = res.map(mapF);
   }
   return res;
}

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

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
   MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\r\n');
}
init();

function write(value) {
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   if (isNode) {
      return MEMORY;
   }
   var res = [];
   var x;
   while (x = read()) {
      res.push(x);
   }
   return res;
}

var readline = require('readline');

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

function solve(n, k, str) {
    if (n > k) return solve(k, k, str.slice(0, k))

    let min
    for (var i = 0; i < n; i++) {
        const after = fill(str.slice(0, n - i), k)
        if (!min || after < min) {
            min = after
        }
        // console.log(after, min)
    }
    return min

    // str = min
    // // console.log('1', str)
    // let end = -1
    // for (var i = str.length - 1; i >= 0; i--) {
    //     if (str[i] === str[0]) {
    //         // skip
    //     } else {
    //         end = i
    //         break
    //     }
    // }
    // if (end >= 0) {
    //     str = str.slice(0, end + 1)
    // }
    // console.log('2', str)

    // return fill(str, k)
}

function fill(min, k) {
    let r = min
    while (r.length < k) {
        r += min
    }
    return r.slice(0, k)
}

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

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

function main () {
	const [n, k] = rna();
	let s = rl();

	let i = 1, p = 0;
	for (; i < s.length; i++) {
		if (s[i] < s[p]) {
			p = 0;
		} else if (s[i] == s[p]) {
			p++;
		} else {
			i = i - p;
			break;
		}
	}

	s = s.slice(0, i);
	s = s.repeat(Math.ceil(k/i));
	const ans = s.slice(0, k);

	console.log(ans);
}

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

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

function main () {
	const [n, k] = rna();
	let s = rl();

	let i = 1, p = 0;
	for (; i < s.length; i++) {
		if (s[i] < s[p]) {
			p = 0;
		} else if (s[i] == s[p]) {
			p++;
		} else {
			break;
		}
	}

	s = s.slice(0, i);
	s = s.repeat(Math.ceil(k/i));
	const ans = s.slice(0, k);

	console.log(ans);
}

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

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

function main () {
	const [n, k] = rna();
	let s = rl();

	let i = 0;
	while (i < s.length && s[i] <= s[0]) i++;

	s = s.slice(0, i).repeat(Math.ceil(k/i));
	const ans = s.slice(0, k);

	console.log(ans);
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    let n, k;
    [n,k] = ((await getLine())).split(' ').map(num => parseInt(num));
    let s = await getLine();
    const output = function(l) {
        for(let i = 0; i<k; i++) {
            rl.output.write(s.charAt(i%l));
        }
    }
    for(let i = 1; i < s.length && i < k; i++) {
        let j;
        for(j = 0; i + j < s.length && s.charAt(j) === s.charAt(i+j); j++);
        if (i + j < s.length && s.charAt(j) < s.charAt(i + j)){
            output(i);
            return;
        }
    }
    output(s.length);

}

solve();

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    let n, k;
    [n,k] = ((await getLine())).split(' ').map(num => parseInt(num));
    let s = await getLine();
    const output = function(l) {
        for(let i = 0; i<k; i++) {
            rl.output.write(s[i%l]);
        }
    }
    for(let i = 1; i < s.length && i < k; i++) {
        let j;
        for(j = 0; i + j < s.length && s[j] === [i+j]; j++);
        if (i + j < s.length && s[j] < s[i + j]){
            output(i);
            return;
        }
    }
    output(Math.min(s.length,k));

}

solve();

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    let n, k;
    [n,k] = ((await getLine())).split(' ').map(num => parseInt(num));
    let s = await getLine();
    if (s.length >= k) {
        console.log(s.substr(0, k))
        return;
    } else {
        const output = function(l) {
            for(let i = 0; i<k; i++) {
                rl.output.write(s[i%l]);
            }
        }
        for(let i = 1; i < s.length; i++) {
            let j;
            for(j = 0; i + j < s.length && s[j] === [i+j]; j++);
            if (i + j < s.length && s[j] < s[i + j]){
                output(i);
                return;
            }
        }
        output(s.length);
    }

}

solve();

var matr = 'haha';

function create(str) {
   var hahaIndexArr = [];
   for (var i = 0; i < str.length; i++) {
      var hasWrong = false;
      for (var j = 0; j < matr.length; j++) {
         if (str[i + j] !== matr[j]) {
            hasWrong = true;
            break;
         }
      }
      if (!hasWrong) {
         hahaIndexArr.push(i);
      }
   }
   if (hahaIndexArr.length === 0) {
      if (str.length < 8) {
         return [str, -1, str];
      }
      return [str.substr(0, 4), 0, str.substr(str.length - 4, 0)];
   }
   var preff = str.substr(0, Math.min(4, hahaIndexArr[0])) || 'ha';
   var suff = str.substr(Math.max(hahaIndexArr[hahaIndexArr.length - 1] + 4, str.length - 4)) || 'ha';
   return [preff, hahaIndexArr.length, suff];
}
function summ(a, b) {
   var createMiddle = create(a[2] + b[0]);
   if (a[1] === -1 && b[1] === -1) {
      return createMiddle;
   }
   var preff = a[1] === -1 ? createMiddle[0] : a[0];
   var suff = b[1] === -1 ? createMiddle[2] : b[2];
   var asum = a[1] === -1 ? 0 : a[1];
   var bsum = b[1] === -1 ? 0 : b[1];
   var midSum = createMiddle[1] === -1 ? 0 : createMiddle[1];
   return [preff, asum + bsum + midSum, suff];
}

function solve() {
   var nk = readArray(Number);
   var n = nk[0];
   var k = nk[1];
   var str = read();
   var current = 1;
   var savepoint;
   var check;
   while(true) {
      if (current >= n) {
         break;
      }
      if (str[current] > str[0]) {
         str = str.substr(0, current);
         break;
      }
      if (str[current] < str[check]) {
         current++;
         continue;
      }
      savepoint = current;
      check = 0;
      while (current < n && str[current] === str[check]) {
         current++;
         check++;
         if (check >= savepoint) {
            check = 0;
         }
      }
      if (current !== n && str[current] > str[check]) {
         str = str.substr(0, savepoint);
         break;
      }
   }
   while(str.length < k) {
      str = str + str;
   }
   write(str.substr(0, k));

}

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

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

function readArray(mapF) {
   var res = read().split(' ');
   if (mapF) {
      res = res.map(mapF);
   }
   return res;
}

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

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
   MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\r\n');
}
init();

function write(value) {
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   if (isNode) {
      return MEMORY;
   }
   var res = [];
   var x;
   while (x = read()) {
      res.push(x);
   }
   return res;
}

var readline = require('readline');

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

function solve(n, k, str) {
    if (n > k) return solve(k, k, str.slice(0, k))

    let min
    for (var i = 0; i < n; i++) {
        const after = fill(str.slice(0, n - i), n)
        if (!min || after < min) {
            min = after
        }
    }

    return fill(min, k)
}

function fill(min, k) {
    let r = min
    while (r.length < k) {
        r += min
    }
    return r.slice(0, k)
}


Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $$$1$$$ to $$$n$$$. For every edge $$$e$$$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $$$e$$$ (and only this edge) is erased from the tree.Monocarp has given you a list of $$$n - 1$$$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ each ($$$1 \le a_i < b_i \le n$$$) — the maximal indices of vertices in the components formed if the $$$i$$$-th edge is removed.

If there is no such tree that can produce the given list of pairs, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $$$n - 1$$$ lines. Each of the last $$$n - 1$$$ lines should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — vertices connected by an edge. Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.

NotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.

queue_el = function(value) {
  this.prev = null;
  this.next = null;
  this.value = value;
}

queue = function() {
  this.first = null;
  this.last = null;
  this.sz = 0;

  this.size = function() {
    return this.sz;
  }

  this.empty = function() {
    return this.sz==0;
  }

  this.front = function() {
    return this.first.value;
  }

  this.push = function(value) {
    var curr = new queue_el(value);

    if(this.sz==0) {
      this.first = curr;
      this.last = curr;
    }
    else {
      curr.prev = this.last;
      this.last.next = curr;
      this.last = curr;
    }

    ++this.sz;
  }

  this.pop = function() {
    if(this.sz==0) return;

    if(this.sz==1) {
      this.sz = 0;
      this.first = null;
      this.last = null;
    }
    else {
      this.first.next.prev = null;
      this.first = this.first.next;
      --this.sz;
    }
  }
}

const N = 1007;

var bad = false, token, n, cnt, pos, ans, e;

var i, j, x, y;

cnt = new Array(N);
ans = new Array(N);

for(i=0;i<N;i++) {
  cnt[i] = 0;
  ans[i] = 0;
}

e = new queue();

n = parseInt(readline());
for(i=1;i<n;i++) {
  token = readline().split(' ');

  x = parseInt(token[0]);
  y = parseInt(token[1]);

  if(x>y) {
    var tmp = x;
    x = y;
    y = tmp;
  }

  if(y!=n || x==y) {
    print("NO");
    bad = true;
    break;
  }

  ++cnt[x];
}

if(bad==false) {
  ans[1] = n;
  pos = 1;

  for(i=n-1;i>=1;i--) {
    if(cnt[i]==0) {
      if(e.empty()) {
        print("NO");
        bad = true;
        break;
      }

      ans[e.front()] = i;
      e.pop();

      continue;
    }

    if(bad==false) {
      for(j=pos+1;j<pos+cnt[i];j++) {
        e.push(j);
      }

      pos+=cnt[i];
      ans[pos] = i;
    }
  }

  if(bad==false) {
    print("YES");

    for(i=2;i<=n;i++) {
      print(ans[i-1] + " " + ans[i]);
    }
  }
}


Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him.Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of Andrey's friends. The second line contains n real numbers pi (0.0 ≤ pi ≤ 1.0) — the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point.

Print a single real number — the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10 - 9.

NoteIn the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one.In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1·0.8 + 0.9·0.2 = 0.26.

var main = function () {
    var n = parseInt(readline());
    var p = [];
    readline().split(/\s+/).forEach(function (t) {
        p.push(parseFloat(t));
    });

    p.sort();

    if (p[p.length - 1] === 1) {
        print(1);
        return;
    }

    var addP = function (cur, pr, v) {
        return cur + v * pr / (1 - v)
    }

    var ans = 0;

    for (var pref = 0; pref <= p.length; ++pref) {
        for (var suff = 0; pref + suff <= p.length; suff++) {
            var cur = 0;
            var pr = 1;

            for (var i = 0; i < pref; ++i)
                pr *= 1 - p[i];
            for (var i = p.length - suff; i < p.length; ++i)
                pr *= 1 - p[i];

            for (var i = 0; i < pref; ++i)
                cur = addP(cur, pr, p[i]);
            for (var i = p.length - suff; i < p.length; ++i)
                cur = addP(cur, pr, p[i]);

            ans = Math.max(ans, cur);
        }
    }

    print(ans);
};

main();

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

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

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

function main() {
	var n = parseInt(readline()),
		probs = tokenizeFloats(readline());
	probs.sort(function (a, b) {
		return a - b;
	});
	var best = 0.0;
	for (var i = n-1; i >= 0; --i) {
		var total = 0.0;
		for (var j = i; j < n; ++j) {
			var p = 1.0;
			for (var k = i; k < n; ++k) {
				if (k == j) {
					p *= probs[k];
				} else {
					p *= (1-probs[k]);
				}
			}
			total += p;
		}
		best = Math.max(best, total);
	}
	print(best);
}

main();

var main = function () {
    var n = parseInt(readline());
    var p = [];
    readline().split(/\s+/).forEach(function (t) {
        p.push(parseFloat(t));
    });

    p.sort();

    var addP = function (cur, pr, v) {
        return cur + v * pr / (1 - v)
    }

    var ans = 0;

    for (var pref = 0; pref <= p.length; ++pref) {
        for (var suff = 0; pref + suff <= p.length; suff++) {
            var cur = 0;
            var pr = 1;

            for (var i = 0; i < pref; ++i)
                pr *= 1 - p[i];
            for (var i = p.length - suff; i < p.length; ++i)
                pr *= 1 - p[i];

            for (var i = 0; i < pref; ++i)
                cur = addP(cur, pr, p[i]);
            for (var i = p.length - suff; i < p.length; ++i)
                cur = addP(cur, pr, p[i]);

            ans = Math.max(ans, cur);
        }
    }

    print(ans);
};

main();


Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score.Codeforces scores are computed as follows: If the maximum point value of a problem is x, and Kevin submitted correctly at minute m but made w wrong submissions, then his score on that problem is . His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack.All arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.

The first line of the input contains five space-separated integers m1, m2, m3, m4, m5, where mi (0 ≤ mi ≤ 119) is the time of Kevin's last submission for problem i. His last submission is always correct and gets accepted. The second line contains five space-separated integers w1, w2, w3, w4, w5, where wi (0 ≤ wi ≤ 10) is Kevin's number of wrong submissions on problem i. The last line contains two space-separated integers hs and hu (0 ≤ hs, hu ≤ 20), denoting the Kevin's numbers of successful and unsuccessful hacks, respectively.

Print a single integer, the value of Kevin's final score.

NoteIn the second sample, Kevin takes 119 minutes on all of the problems. Therefore, he gets  of the points on each problem. So his score from solving problems is . Adding in 10·100 = 1000 points from hacks, his total score becomes 3930 + 1000 = 4930.


Polycarp was presented with some sequence of integers $$$a$$$ of length $$$n$$$ ($$$1 \le a_i \le n$$$). A sequence can make Polycarp happy only if it consists of different numbers (i.e. distinct numbers).In order to make his sequence like this, Polycarp is going to make some (possibly zero) number of moves.In one move, he can:   remove the first (leftmost) element of the sequence. For example, in one move, the sequence $$$[3, 1, 4, 3]$$$ will produce the sequence $$$[1, 4, 3]$$$, which consists of different numbers.Determine the minimum number of moves he needs to make so that in the remaining sequence all elements are different. In other words, find the length of the smallest prefix of the given sequence $$$a$$$, after removing which all values in the sequence will be unique.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the given sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the given sequence $$$a$$$. 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 your answer on a separate line — the minimum number of elements that must be removed from the beginning of the sequence so that all remaining elements are different.

NoteThe following are the sequences that will remain after the removal of prefixes:  $$$[1, 4, 3]$$$;  $$$[1]$$$;  $$$[1]$$$;  $$$[6, 5, 4, 3, 2, 1]$$$;  $$$[2, 1]$$$. It is easy to see that all the remaining sequences contain only distinct elements. In each test case, the shortest matching prefix was removed.

var t = readline().split(" ").map((x) => parseInt(x));
for(var i = 0; i < t ; i++) {
  var n = readline().split(" ").map((x) => parseInt(x));
  var nums = readline().split(" ").map((x) => parseInt(x));
  var dict = {};
  var move = 0;

  nums.map((item, key) => {
    if(dict[item] !== undefined) {
      move = Math.max(dict[item] + 1, move);
    }
    dict[item] = key;
  })
  print(move);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var caseMap = new Map();
    var sequence = 0;
    for (var j = caseLength-1; j >= 0; j--)
    {
        if (caseMap.has(caseArray[j]))
        {
            break;
        }
        else
        {
            sequence++;
            caseMap.set(caseArray[j], 1);
        }
    }
    print(caseLength-sequence);
}

var t = readline();
for(var i=0;i<t;i++){
    var n = readline();
    var arr = readline().split(' ').map(x=>parseInt(x));
    var map={};
    var ans=0;
    for(var j=arr.length;j>=0;j--){
        if(map[arr[j]]){
            ans=j+1;
            break;
        }
        else{
            map[arr[j]]=1;
        }
    }
    print(ans);
}

var tests = parseInt(readline());
    var n;
    var arr;
    for (var t=0; t < tests; t++) {
        n = parseInt(readline());
        arr = readline().split(' ').map(x=>parseInt(x));
        var set = new Set();
        var index = 0;
        for (var i = n-1; i >= 0; i--) {
            if (set.has(arr[i])) {
                index = i+1;
                break;
            }
            set.add(arr[i]);
        }
        print(index);
    }

var t = +readline();

for(var i = 0; i< t; i ++) {

      var nums = [];
    var t1 = +readline();
    var list = readline().split(' ').map((t) => +t);
    print(removePrefix(list));

}

function removePrefix(arr){

  var set = new Set();
  for(var i = arr.length; i>=0; i--){
    if (set.has(arr[i])){
      return i + 1
    }
    set.add(arr[i])
  }

  return 0;

}

const rdline = require('readline');

const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = readline();
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const a = readline().split(" ").map(Number);
        var A = {};
        var w = false;
        for (let j = a.length - 1; j >= 0; j--) {
            if (!A[a[j]]) {
                A[a[j]] = true;
            } else {
                console.log(j + 1);
                w = true;
                break;
            }
        }
        if (!w) {
            console.log(0);
        }
    }
}

function solve() {
  const n = Number(cl());
  const arr = cl().split(' ').map((item) => Number(item));

  const set = new Set();
  for (let i = n - 1; i >= 0; i--) {
    if (set.has(arr[i])) {
      return co(i + 1);
    }
    set.add(arr[i]);
  }
  co(0);
}

function Solution() {
  let n = Number(cl());
  while (n--) solve();
}

let i = 0;
const lines = []

function cl() { return lines[i++] }
function co(str) { console.log(str)}
const readline = require('readline')
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
rl.on('line', (input) => lines.push(input));
rl.on('close', Solution);

'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 output(x) {
    if (typeof x !== 'string')
    {
        x = x.toString();
    }
    console.log(x);
}

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

    for (let test = 0; test < N; test++)
    {
        const n = Number(readline());
        const arr = readline().split(' ').map(Number);
        const hash = {};
        for (let i = arr.length - 1; i >= 0; i--)
        {
            if (hash[arr[i]])
            {
                output(i + 1);
                break;
            }
            else
            {
                hash[arr[i]] = true;
            }
            if (i === 0)
            {
                output(0);
            }
        }
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '', currentLine = 0;
process.stdin.on('data', inputStdin => { inputString += inputStdin; });
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => string.trim());
    main();
});
function readLine() {
    return inputString[currentLine++];
}

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

function myFunc(n, arr){
    let map = [];
    let resp = 0;

    for(let i = n-1; i >=0; i--){
        if(map[arr[i]] != undefined){
            break;
        }
        else{
            map[arr[i]] = 1;
            resp++;
        }
    }

    return n-resp;
}

// cls; cat .\input.txt | node .\script.js
// codium --diff file1.js file2.js
'use strict';
let data = ''; // raw
let inputs = ''; // iterator
function read() { return inputs.next().value.trim(); };

async function solve() {
    let length = parseInt(await read())
    let value = (await read()).split(' ').map(Number)
    let counter = 0
    let map = {}
    for (let i = value.length - 1; i >= 0; i--) {
        const element = value[i];
        if (element in map) {
            break
        } else {
            map[element] = true
            counter++
        }
    }
    return length - counter
}

async function main() {
    let tasks_amount = parseInt(await read())
    for (let i = 0; i < tasks_amount; i++) {
        let result = await solve()
        console.log(result)
    }
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => data += input);
process.stdin.on('end', async () => {
    let splitted = data.split('\r\n')
    inputs = await splitted.values();
    await main();
});

'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 output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

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

    for (let test = 0; test < N; test++) {
        const n = Number(readline());
        const arr = readline().split(' ').map(Number);
        const hash = {};
        for (let i = arr.length - 1; i >= 0; i--) {
            if (hash[arr[i]]) {
                output(i + 1);
                break;
            } else {
                hash[arr[i]] = true;
            }
            if (i === 0) {
                output(0);
            }
        }
    }
}

'use strict';

function solve(n, a) {
  const set = new Set();
  for (let i = n - 1; i >= 0; i--) {
    if (set.has(a[i])) return i + 1;
    set.add(a[i]);
  }
  return 0;
}

async function main(r) {
  const rn = async () => Number(await r());
  const rns = async () => {
    return (await r()).split(' ').filter(s => s !== '').map(Number);
  };
  try {
    let t = Number(await r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = await rn();
      const a = await rns();
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

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 solve(n, arr) {
    const m = {}
    for (let i = arr.length - 1; i >= 0; i--) {
        const x = arr[i]
        if (m[x]) {
            return i + 1
        }
        m[x] = 1
    }
    return 0
}

//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();
		var list = nextIntArray(N);
		var set = new Set();
		var output = N;
		for(var i = N - 1; i >= 0; i--){
			if(!set.has(list[i])){
				set.add(list[i]);
				output--;
			}else{
				break;
			}
		}
		myout(output);
	}
}

var t = readline().split(" ").map((x) => parseInt(x));
for(var i = 0; i < t ; i++) {
  var n = readline().split(" ").map((x) => parseInt(x));
  var nums = readline().split(" ").map((x) => parseInt(x));
  var dict = {};
  var move = 0;

  nums.map((item, key) => {
    if(dict[item] !== undefined) {
      move = dict[item] + 1;
    }
    dict[item] = key;
  })
  print(move);
}

const rdline = require('readline');

const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = readline();
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const a = readline().split(" ").map(Number);
        var A = {};
        for (let j = a.length - 1; j >= 0; j--) {
            if (!A[a[j]]) {
                A[a[j]] = true;
            } else {
                d = a.length - Object.keys(A).length;
                break;
            }
            if (n === 1) {
                d = 0;
            }
        }
        console.log(d)
    }

}

const rdline = require('readline');

const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = readline();
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const a = readline().split(" ").map(Number);
        var A = {};
        for (let j = a.length - 1; j >= 0; j--) {
            if (A[a[j]]) {
                d = j + 1;
                break;
            } else {
                A[a[j]] = true;
            }
            if (n === 1) {
                d = 0;
            }
        }
        console.log(d)
    }

}

const rdline = require('readline');

const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];
/**
 * План подзадачи:
 * - создаем пустой обьект А
 * - идем по элементам с конца массива
 *   - проверяем есть ли элемент в объекте А
 *   - если элемента нет, то добавляем в объект А свойство значение элемента
 *   - если элемент есть , то мы останавливаем итерацию и выводим в качестве ответа длину всего массива минус число пройденных элементов
 * - если мы еще не вышли, то ответ 0
 */

solve = () => {
    const t = readline();
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const a = readline().split(" ").map(Number);
        var A = {};
        for (let j = a.length - 1; j >= 0; j--) {
            if (A[a[j]]) {
                d = i + 1;
                break;
            } else {
                A[a[j]] = true;
            }
            if (j === 1) {
                d = 0;
            }
        }
        console.log(d)
    }

}

const rdline = require('readline');

const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];
solve = () => {
    const t = readline();
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const a = readline().split(" ").map(Number);
        var A = {};
        for (let j = a.length - 1; j >= 0; j--) {
            if (A[a[j]]) {
                d = i + 1;
                break;
            } else {
                A[a[j]] = true;
            }
            if (j === 1) {
                d = 0;
            }
        }
        console.log(d)
    }

}


The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.

The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 100). Then follow n lines describing instructions. The i-th line contains m integers: xi1, xi2, ..., xim (0 ≤ xij ≤ k), where xij is the instruction that must be executed by the i-th core at the j-th cycle. If xij equals 0, then the corresponding instruction is «do nothing». But if xij is a number from 1 to k, then the corresponding instruction is «write information to the memory cell number xij». We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from 1 to k.

Print n lines. In the i-th line print integer ti. This number should be equal to 0 if the i-th core won't be locked, or it should be equal to the number of the cycle when this core will be locked.

print(function(n, m, k){

	var a = [];
	for(var i=0; i<n; i++)
		a.push(readline().split(' ').map(Number));

	var core=[];
	var mem=[];
	for(var i = 0; i < n; i++)
		core[i] = 1;
	for(var i = 0; i < k; i++)
		mem[i] = 1;

	var ans=[];
	for(var i=0; i<n; i++)
		ans[i] = 0;
	for(var i = 0; i < m; i++){
		for(var j = 0; j < n; j++){
			if(a[j][i] === 0 || core[j] === 0){
				continue;
			}
			if(mem[a[j][i]] === 0){
				core[j] = 0;
				ans[j] = i+1;
				continue;
			}
			for(var x = 0; x < n; x++){
				if(x !== j
					&&core[x]
					&& a[j][i] === a[x][i]
					){
					ans[j] = i + 1;
					core[j] = 0;
					ans[x] = i + 1;
					core[x] = 0;
					mem[a[j][i]] = 0;
				}
			}
		}
	}
	return ans.join('\n');

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


At first, there was a legend related to the name of the problem, but now it's just a formal statement.You are given $$$n$$$ points $$$a_1, a_2, \dots, a_n$$$ on the $$$OX$$$ axis. Now you are asked to find such an integer point $$$x$$$ on $$$OX$$$ axis that $$$f_k(x)$$$ is minimal possible.The function $$$f_k(x)$$$ can be described in the following way:   form a list of distances $$$d_1, d_2, \dots, d_n$$$ where $$$d_i = |a_i - x|$$$ (distance between $$$a_i$$$ and $$$x$$$);  sort list $$$d$$$ in non-descending order;  take $$$d_{k + 1}$$$ as a result. If there are multiple optimal answers you can print any of them.

The first line contains single integer $$$T$$$ ($$$ 1 \le T \le 2 \cdot 10^5$$$) — number of queries. Next $$$2 \cdot T$$$ lines contain descriptions of queries. All queries are independent.  The first line of each query contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k < n$$$) — the number of points and constant $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_1 < a_2 < \dots < a_n \le 10^9$$$) — points in ascending order. It's guaranteed that $$$\sum{n}$$$ doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$T$$$ integers — corresponding points $$$x$$$ which have minimal possible value of $$$f_k(x)$$$. If there are multiple answers you can print any of them.

process.stdin.resume();
process.stdin.setEncoding('utf8');

var input = ``;

function cacheInput(data) {
  input += data;
}

function main() {
    let lines = input.split('\n');
    let t = parseInt(lines[0]);
    for(let _t = 0; _t < t; ++_t) {
        let [n, k] = lines[2*_t+1].split(' ').map(s => parseInt(s))
        let xArray = lines[2*_t+2].split(' ').map(s => parseInt(s))

        let [res, dist] = [undefined, 1e9]
        for(let i = k; i < n; ++i) {
            let tmp = Math.ceil((xArray[i] - xArray[i-k])/2)
            if(dist > tmp) [res, dist] = [Math.floor((xArray[i] + xArray[i-k])/2), tmp]
        }

        console.log(res)
  }
}

process.stdin.on('data', cacheInput).on('end', main);

process.stdin.resume();
process.stdin.setEncoding('utf8');

var input = ``;

function cacheInput(data) {
  input += data;
}

function main() {
    let lines = input.split('\n');
    let t = parseInt(lines[0]);
    for(let _t = 0; _t < t; ++_t) {
        let [n, k] = lines[2*_t+1].split(' ').map(s => parseInt(s))
        let xArray = lines[2*_t+2].split(' ').map(s => parseInt(s))
        console.log((k => {
            if(k) {
                let [res, dist] = [undefined, 1e9]
                for(let i = k; i < n; ++i) {
                    let tmp = Math.ceil((xArray[i] - xArray[i-k] + 1)/2)
                    if(dist > tmp) [res, dist] = [Math.floor((xArray[i] + xArray[i-k])/2), tmp]
                }
                return res
            }

            return xArray[0]
        })(k))
  }
}

process.stdin.on('data', cacheInput).on('end', main);


You play a computer game. In this game, you lead a party of $$$m$$$ heroes, and you have to clear a dungeon with $$$n$$$ monsters. Each monster is characterized by its power $$$a_i$$$. Each hero is characterized by his power $$$p_i$$$ and endurance $$$s_i$$$.The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero (exactly one) who is going to enter the dungeon this day.When the hero enters the dungeon, he is challenged by the first monster which was not defeated during the previous days (so, if the heroes have already defeated $$$k$$$ monsters, the hero fights with the monster $$$k + 1$$$). When the hero fights the monster, there are two possible outcomes:  if the monster's power is strictly greater than the hero's power, the hero retreats from the dungeon. The current day ends;  otherwise, the monster is defeated. After defeating a monster, the hero either continues fighting with the next monster or leaves the dungeon. He leaves the dungeon either if he has already defeated the number of monsters equal to his endurance during this day (so, the $$$i$$$-th hero cannot defeat more than $$$s_i$$$ monsters during each day), or if all monsters are defeated — otherwise, he fights with the next monster. When the hero leaves the dungeon, the current day ends.Your goal is to defeat the last monster. What is the minimum number of days that you need to achieve your goal? Each day you have to use exactly one hero; it is possible that some heroes don't fight the monsters at all. Each hero can be used arbitrary number of times.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then the test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of monsters in the dungeon. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the power of the $$$i$$$-th monster. The third line contains one integer $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the number of heroes in your party. Then $$$m$$$ lines follow, each describing a hero. Each line contains two integers $$$p_i$$$ and $$$s_i$$$ ($$$1 \le p_i \le 10^9$$$, $$$1 \le s_i \le n$$$) — the power and the endurance of the $$$i$$$-th hero. It is guaranteed that the sum of $$$n + m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print one integer — the minimum number of days you have to spend to defeat all of the monsters (or $$$-1$$$ if it is impossible).

const Fs = require('fs')

const content = Fs.readFileSync(0).toString()

const parse = (a) => {
  a = a.split('\n')
  let j = 1
  const test = []
  for (let i = 0; i < a[0]; i++) {
    const number_of_monster = a[j]
    j++
    const monsters = a[j].split(' ').map(Number)
    j++
    const number_of_hero = a[j]
    j++
    const heros = []
    for (let k = 0; k < number_of_hero; k++) {
      heros.push(a[j].split(' ').map(Number))
      j++
    }
    // test.push([monsters, heros])
    console.log(betterMinDay([monsters, heros]))
  }

  return test
}

// const betterMinDay = ([monsters, heros]) => {
//   const total_mons = monsters.length

//   // MonsterIndex -> MonsterIndex -> [[NumDays, HeroStart, HeroEnd]]
//   const rec = (m_start, m_stop) => {
//     if (m_start === m_stop) {
//       const ans = []

//       heros.forEach(([power, endu]) => {
//         if (1 <= endu && monsters[m_start] <= power) {
//           ans.push([1, [power, endu - 1], [power, endu - 1]])
//         }
//       })

//       if (ans.length === 0) {
//         return [[Infinity, undefined, undefined]]
//       } else {
//         return ans
//       }
//     } else {
//       const m_mid = Math.floor((m_end - m_start) / 2)

//       const [low_day, low_heros_start, low_heros_end] = rec(m_start, m_mid)
//       const [upp_day, upp_heros_start, upp_heros_end] = rec(m_mid + 1, m_end)

//       mid_heros

//       const day

//       return [day, low_heros_start, upp_heros_end]
//     }
//   }
// }

const randomInt = (min, max) => {
  return Math.floor(min + Math.random() * (max - min))
}

const random = () => {
  const max = 2 * Math.pow(10, 5)
  const max_power = Math.pow(10, 9)
  const monsters = Array(randomInt(1, max)).fill().map(() => randomInt(1, max_power))
  const heros = Array(randomInt(1, max)).fill().map(() => {
    return [randomInt(1, max_power), randomInt(1, max)]
  })
  return [monsters, heros]
}

const createNode = (power, endu, children) => {
  return {
    power,
    endu,
    children,
  }
}

const compareNumber = (a, b) => {
  if (a < b) {
    return -1
  } else if (a === b) {
    return 0
  } else {
    return 1
  }
}
const comparePower = (a, b) => compareNumber(a[0], b[0])
const compareEndu = (a, b) => compareNumber(a[1], b[1])

const binarySearchSortedList = (compareValueTo, list) => {
  const rec = (start, end) => {
    if (start === end) {
      const c = compareValueTo(list[start])
      if (c <= 0) {
        return start
      } else {
        return -1
      }
    }

    const mid = Math.floor((end - start) / 2) + start
    const c = compareValueTo(list[mid])

    if (c === 0) {
      return mid
    } else if (c === -1) {
      return rec(start, mid)
    } else {
      return rec(mid + 1, end)
    }
  }
  return rec(0, list.length - 1)
}

const createQuadNode = (val, x, y) => {
  return {
    val,
    x,
    y,
  }
}

const insert = (node, tree) => {
  let prop
  if (tree.x <= node.x) {
    if (tree.y <= node.y) {
      prop = 'c1'
    } else {
      prop = 'c4'
    }
  } else {
    if (tree.y <= node.y) {
      prop = 'c2'
    } else {
      prop = 'c3'
    }
  }

  if (tree[prop] === undefined) {
    tree[prop] = node
  } else {
    if (node.val && tree[prop].val) {
      if (tree[prop].x <= node.x && tree[prop].y <= node.y) {
        node.c1 = tree[prop].c1
        node.c2 = tree[prop].c2
        node.c3 = tree[prop].c3
        node.c4 = tree[prop].c4
        tree[prop] = node
        return
      } else if (node.x <= tree[prop].x && node.y <= tree[prop].y) {
        return
      }
    } else if (node.val === false && tree.val === false) {
      if (node.x <= tree[prop].x && node.y <= tree[prop].y) {
        node.c1 = tree[prop].c1
        node.c2 = tree[prop].c2
        node.c3 = tree[prop].c3
        node.c4 = tree[prop].c4
        tree[prop] = node
        return
      } else if (tree[prop].x <= node.x && tree[prop].y <= node.y) {
        return
      }
    }
    insert(node, tree[prop])
  }
}

const getVal = (x, y, tree) => {
  if (tree === undefined) {
    return undefined
  }

  if (
    tree.x <= x &&
    tree.y <= y &&
    tree.val === false
  ) {
    return false
  } else if (
    x <= tree.x &&
    y <= tree.y &&
    tree.val === true
  ) {
    return true
  } else if (
    tree.x <= x &&
    y < tree.y
  ) {
    return getVal(x, y, tree.c4)
  } else {
    return getVal(x, y, tree.c2)
  }
}

const enduMax = (i, heros) => {
  const ans = []
  for (let i = heros.length - 1; i >= 0; i--) {
    if (ans.length === 0) {
      ans.push(heros[i][1])
    } else {
      const a = Math.max(ans[ans.length - 1], heros[i][1])
      ans.push(a)
    }
  }
  return ans.reverse()
}

const betterMinDay = ([monsters, heros]) => {
  heros.sort((a, b) => {
    const ans = comparePower(a, b)
    if (ans === 0) {
      return compareEndu(a, b)
    } else {
      return ans
    }
  })

  let num_day = 0
  let min_hero_stats = [0, 1]

  // let mem
  // const setAns = (power, endu, ans) => {
  //   if (mem === undefined) {
  //     mem = createQuadNode(ans, power, endu)
  //   } else {
  //     insert(createQuadNode(ans, power, endu), mem)
  //   }
  // }
  // const getAns = (power, endu) => {
  //   return getVal(power, endu, mem)
  // }

  let endu_max = enduMax(0, heros)

  const aHeroHasStat = ([power, endu]) => {
    // const already_ans = getAns(power, endu)
    // if (already_ans !== undefined) {
    //   return already_ans
    // }

    const compareValueTo = ([hero_power, hero_endu]) => {
      if (power < hero_power) {
        return -1
      } else if (power === hero_power) {
        return 0
      } else {
        return 1
      }
    }

    const ans = binarySearchSortedList(compareValueTo, heros)

    let return_val
    if (ans === -1) {
      return_val = false
    } else {
      return_val = endu <= endu_max[ans]
      // return_val = false
      // for (let i = ans; i < heros.length; i++) {
      //   if (endu <= heros[i][1]) {
      //     return_val = true
      //     break
      //   }
      // }
    }
    // setAns(power, endu, return_val)
    return return_val
  }

  let i = 0
  let must_move = true
  while (true) {
    if (i === monsters.length) {
      num_day++
      break
    }

    const monster = monsters[i]
    min_hero_stats[0] = Math.max(min_hero_stats[0], monster)

    if (aHeroHasStat(min_hero_stats)) {
      min_hero_stats[1] = min_hero_stats[1] + 1

      i++
      must_move = false
    } else {
      num_day++
      min_hero_stats = [0, 1]

      if (must_move) {
        num_day = -1
        break
      } else {
        must_move = true
      }
    }
  }

  // const iter = (must_move, i) => {
  //   if (i === monsters.length) {
  //     num_day++
  //     return
  //   }

  //   const monster = monsters[i]
  //   min_hero_stats[0] = Math.max(min_hero_stats[0], monster)

  //   if (aHeroHasStat(min_hero_stats)) {
  //     min_hero_stats[1] = min_hero_stats[1] + 1

  //     iter(false, i + 1)
  //   } else {
  //     num_day++
  //     min_hero_stats = [0, 1]

  //     if (must_move) {
  //       num_day = -1
  //       return
  //     } else {
  //       iter(true, i)
  //     }
  //   }
  // }

  // iter(true, 0)

  return num_day
}

// const minDay = ([monsters, heros]) => {
//   heros.sort((a,b)=>{
//     a = a[0]
//     b = b[0]
//     if (a < b) {
//       return 1
//     } else if (a === b) {
//       return 0
//     } else {
//       return -1
//     }
//   })

//   const total_mons = monsters.length

//   // Index -> Int -> Int -> Index
//   const battle = (curr_monster, hero_power, hero_endu) => {
//     if (
//       curr_monster === total_mons ||
//       hero_power < monsters[curr_monster] ||
//       hero_endu === 0
//     ) {
//       return curr_monster
//     } else {
//       return battle(curr_monster+1, hero_power, hero_endu-1)
//     }
//   }

//   const memo = {}
//   const getMemo = (prev_monster, curr_monster) => {
//     return memo[prev_monster+':'+curr_monster]
//   }
//   const setMemo = (val, prev_monster, curr_monster) => {
//     memo[prev_monster+':'+curr_monster] = val
//   }

//   // Index -> NumberOfDay
//   const rec = (prev_monster, curr_monster) => {
//     const already_ans = getMemo(prev_monster, curr_monster)
//     if (already_ans !== undefined) {
//       return already_ans
//     }

//     if (prev_monster === curr_monster) {
//       return Infinity
//     }

//     if (curr_monster === total_mons) {
//       return 0
//     }

//     // const ans = heros
//     //   .map(hero=>rec(curr_monster, battle(curr_monster, hero[0], hero[1])))
//     //   .reduce((acc, val) => Math.min(acc, val), Infinity) + 1

//     // const index = []
//     // for (let i = 0; i < heros.length; i++) {
//     //   const a = battle(curr_monster, heros[i][0], heros[i][1])
//     //   if (a === curr_monster) {
//     //     break
//     //   }
//     //   index.push(a)
//     // }
//     // const ans = index.map(a=>rec(curr_monster, a))
//     //   .reduce((acc, val) => Math.min(acc, val), Infinity) + 1

//     // let ans = Infinity
//     // for (let i = 0; i < index.length; i++) {
//     // }
//     // ans++

//     let ans = Infinity
//     for (let i = 0; i < heros.length; i++) {
//       const a = battle(curr_monster, heros[i][0], heros[i][1])
//       if (a === curr_monster) {
//         break
//       }
//       ans = Math.min(ans, rec(curr_monster, a))
//     }
//     ans++

//     setMemo(ans, prev_monster, curr_monster)

//     return ans
//   }

//   const ans = rec(-1, 0)
//   if (ans === Infinity) {
//     return -1
//   } else {
//     return ans
//   }
// }

const array = parse(content)
// array.forEach(a=>console.log(betterMinDay(a)))

// const a = random()
// console.log(a)
// console.time('min day')
// console.log(betterMinDay(a))
// console.timeEnd('min day')

const Fs = require('fs')

const content = Fs.readFileSync(0).toString()

const parse = (a) => {
  a = a.split('\n')
  let j = 1
  const test = []
  for (let i = 0; i < a[0]; i++) {
    const number_of_monster = a[j]
    j++
    const monsters = a[j].split(' ').map(Number)
    j++
    const number_of_hero = a[j]
    j++
    const heros = []
    for (let k = 0; k < number_of_hero; k++) {
      heros.push(a[j].split(' ').map(Number))
      j++
    }
    // test.push([monsters, heros])
    console.log(betterMinDay([monsters, heros]))
  }

  return test
}

// const betterMinDay = ([monsters, heros]) => {
//   const total_mons = monsters.length

//   // MonsterIndex -> MonsterIndex -> [[NumDays, HeroStart, HeroEnd]]
//   const rec = (m_start, m_stop) => {
//     if (m_start === m_stop) {
//       const ans = []

//       heros.forEach(([power, endu]) => {
//         if (1 <= endu && monsters[m_start] <= power) {
//           ans.push([1, [power, endu - 1], [power, endu - 1]])
//         }
//       })

//       if (ans.length === 0) {
//         return [[Infinity, undefined, undefined]]
//       } else {
//         return ans
//       }
//     } else {
//       const m_mid = Math.floor((m_end - m_start) / 2)

//       const [low_day, low_heros_start, low_heros_end] = rec(m_start, m_mid)
//       const [upp_day, upp_heros_start, upp_heros_end] = rec(m_mid + 1, m_end)

//       mid_heros

//       const day

//       return [day, low_heros_start, upp_heros_end]
//     }
//   }
// }

const randomInt = (min, max) => {
  return Math.floor(min + Math.random() * (max - min))
}

const random = () => {
  const max = 2 * Math.pow(10, 5)
  const max_power = Math.pow(10, 9)
  const monsters = Array(randomInt(1, max)).fill().map(() => randomInt(1, max_power))
  const heros = Array(randomInt(1, max)).fill().map(() => {
    return [randomInt(1, max_power), randomInt(1, max)]
  })
  return [monsters, heros]
}

const createNode = (power, endu, children) => {
  return {
    power,
    endu,
    children,
  }
}

const compareNumber = (a, b) => {
  if (a < b) {
    return -1
  } else if (a === b) {
    return 0
  } else {
    return 1
  }
}
const comparePower = (a, b) => compareNumber(a[0], b[0])
const compareEndu = (a, b) => compareNumber(a[1], b[1])

const binarySearchSortedList = (compareValueTo, list) => {
  const rec = (start, end) => {
    if (start === end) {
      const c = compareValueTo(list[start])
      if (c <= 0) {
        return start
      } else {
        return -1
      }
    }

    const mid = Math.floor((end - start) / 2) + start
    const c = compareValueTo(list[mid])

    if (c === 0) {
      return mid
    } else if (c === -1) {
      return rec(start, mid)
    } else {
      return rec(mid + 1, end)
    }
  }
  return rec(0, list.length - 1)
}

const createQuadNode = (val, x, y) => {
  return {
    val,
    x,
    y,
  }
}

const insert = (node, tree) => {
  let prop
  if (tree.x <= node.x) {
    if (tree.y <= node.y) {
      prop = 'c1'
    } else {
      prop = 'c4'
    }
  } else {
    if (tree.y <= node.y) {
      prop = 'c2'
    } else {
      prop = 'c3'
    }
  }

  if (tree[prop] === undefined) {
    tree[prop] = node
  } else {
    if (node.val && tree[prop].val) {
      if (tree[prop].x <= node.x && tree[prop].y <= node.y) {
        node.c1 = tree[prop].c1
        node.c2 = tree[prop].c2
        node.c3 = tree[prop].c3
        node.c4 = tree[prop].c4
        tree[prop] = node
        return
      } else if (node.x <= tree[prop].x && node.y <= tree[prop].y) {
        return
      }
    } else if (node.val === false && tree.val === false) {
      if (node.x <= tree[prop].x && node.y <= tree[prop].y) {
        node.c1 = tree[prop].c1
        node.c2 = tree[prop].c2
        node.c3 = tree[prop].c3
        node.c4 = tree[prop].c4
        tree[prop] = node
        return
      } else if (tree[prop].x <= node.x && tree[prop].y <= node.y) {
        return
      }
    }
    insert(node, tree[prop])
  }
}

const getVal = (x, y, tree) => {
  if (tree === undefined) {
    return undefined
  }

  if (
    tree.x <= x &&
    tree.y <= y &&
    tree.val === false
  ) {
    return false
  } else if (
    x <= tree.x &&
    y <= tree.y &&
    tree.val === true
  ) {
    return true
  } else if (
    tree.x <= x &&
    y < tree.y
  ) {
    return getVal(x, y, tree.c4)
  } else {
    return getVal(x, y, tree.c2)
  }
}

const betterMinDay = ([monsters, heros]) => {
  heros.sort((a, b) => {
    const ans = comparePower(a, b)
    if (ans === 0) {
      return -compareEndu(a, b)
    } else {
      return ans
    }
  })

  let num_day = 0
  let min_hero_stats = [0, 1]

  let mem
  const setAns = (power, endu, ans) => {
    if (mem === undefined) {
      mem = createQuadNode(ans, power, endu)
    } else {
      insert(createQuadNode(ans, power, endu), mem)
    }
  }
  const getAns = (power, endu) => {
    return getVal(power, endu, mem)
  }

  const aHeroHasStat = ([power, endu]) => {
    const already_ans = getAns(power, endu)
    if (already_ans !== undefined) {
      return already_ans
    }

    const compareValueTo = ([hero_power, hero_endu]) => {
      if (power < hero_power) {
        return -1
      } else if (power === hero_power) {
        return 0
      } else {
        return 1
      }
    }

    const ans = binarySearchSortedList(compareValueTo, heros)

    let return_val
    if (ans === -1) {
      return_val = false
    } else {
      return_val = false
      for (let i = ans; i < heros.length; i++) {
        if (endu <= heros[i][1]) {
          return_val = true
          break
        }
      }
    }
    setAns(power, endu, return_val)
    return return_val
  }

  let i = 0
  let must_move = true
  while (true) {
    if (i === monsters.length) {
      num_day++
      break
    }

    const monster = monsters[i]
    min_hero_stats[0] = Math.max(min_hero_stats[0], monster)

    if (aHeroHasStat(min_hero_stats)) {
      min_hero_stats[1] = min_hero_stats[1] + 1

      i++
      must_move = false
    } else {
      num_day++
      min_hero_stats = [0, 1]

      if (must_move) {
        num_day = -1
        break
      } else {
        must_move = true
      }
    }
  }

  // const iter = (must_move, i) => {
  //   if (i === monsters.length) {
  //     num_day++
  //     return
  //   }

  //   const monster = monsters[i]
  //   min_hero_stats[0] = Math.max(min_hero_stats[0], monster)

  //   if (aHeroHasStat(min_hero_stats)) {
  //     min_hero_stats[1] = min_hero_stats[1] + 1

  //     iter(false, i + 1)
  //   } else {
  //     num_day++
  //     min_hero_stats = [0, 1]

  //     if (must_move) {
  //       num_day = -1
  //       return
  //     } else {
  //       iter(true, i)
  //     }
  //   }
  // }

  // iter(true, 0)

  return num_day
}

// const minDay = ([monsters, heros]) => {
//   heros.sort((a,b)=>{
//     a = a[0]
//     b = b[0]
//     if (a < b) {
//       return 1
//     } else if (a === b) {
//       return 0
//     } else {
//       return -1
//     }
//   })

//   const total_mons = monsters.length

//   // Index -> Int -> Int -> Index
//   const battle = (curr_monster, hero_power, hero_endu) => {
//     if (
//       curr_monster === total_mons ||
//       hero_power < monsters[curr_monster] ||
//       hero_endu === 0
//     ) {
//       return curr_monster
//     } else {
//       return battle(curr_monster+1, hero_power, hero_endu-1)
//     }
//   }

//   const memo = {}
//   const getMemo = (prev_monster, curr_monster) => {
//     return memo[prev_monster+':'+curr_monster]
//   }
//   const setMemo = (val, prev_monster, curr_monster) => {
//     memo[prev_monster+':'+curr_monster] = val
//   }

//   // Index -> NumberOfDay
//   const rec = (prev_monster, curr_monster) => {
//     const already_ans = getMemo(prev_monster, curr_monster)
//     if (already_ans !== undefined) {
//       return already_ans
//     }

//     if (prev_monster === curr_monster) {
//       return Infinity
//     }

//     if (curr_monster === total_mons) {
//       return 0
//     }

//     // const ans = heros
//     //   .map(hero=>rec(curr_monster, battle(curr_monster, hero[0], hero[1])))
//     //   .reduce((acc, val) => Math.min(acc, val), Infinity) + 1

//     // const index = []
//     // for (let i = 0; i < heros.length; i++) {
//     //   const a = battle(curr_monster, heros[i][0], heros[i][1])
//     //   if (a === curr_monster) {
//     //     break
//     //   }
//     //   index.push(a)
//     // }
//     // const ans = index.map(a=>rec(curr_monster, a))
//     //   .reduce((acc, val) => Math.min(acc, val), Infinity) + 1

//     // let ans = Infinity
//     // for (let i = 0; i < index.length; i++) {
//     // }
//     // ans++

//     let ans = Infinity
//     for (let i = 0; i < heros.length; i++) {
//       const a = battle(curr_monster, heros[i][0], heros[i][1])
//       if (a === curr_monster) {
//         break
//       }
//       ans = Math.min(ans, rec(curr_monster, a))
//     }
//     ans++

//     setMemo(ans, prev_monster, curr_monster)

//     return ans
//   }

//   const ans = rec(-1, 0)
//   if (ans === Infinity) {
//     return -1
//   } else {
//     return ans
//   }
// }

const array = parse(content)
// array.forEach(a=>console.log(betterMinDay(a)))

// const a = random()
// console.log(a)
// console.time('min day')
// console.log(betterMinDay(a))
// console.timeEnd('min day')

const Fs = require('fs')

const content = Fs.readFileSync(0).toString()

const parse = (a) => {
  a = a.split('\n')
  let j = 1
  const test = []
  for (let i = 0; i < a[0]; i++) {
    const number_of_monster = a[j]
    j++
    const monsters = a[j].split(' ').map(Number)
    j++
    const number_of_hero = a[j]
    j++
    const heros = []
    for (let k = 0; k < number_of_hero; k++) {
      heros.push(a[j].split(' ').map(Number))
      j++
    }
    // test.push([monsters, heros])
    console.log(betterMinDay([monsters, heros]))
  }

  return test
}

// const betterMinDay = ([monsters, heros]) => {
//   const total_mons = monsters.length

//   // MonsterIndex -> MonsterIndex -> [[NumDays, HeroStart, HeroEnd]]
//   const rec = (m_start, m_stop) => {
//     if (m_start === m_stop) {
//       const ans = []

//       heros.forEach(([power, endu]) => {
//         if (1 <= endu && monsters[m_start] <= power) {
//           ans.push([1, [power, endu - 1], [power, endu - 1]])
//         }
//       })

//       if (ans.length === 0) {
//         return [[Infinity, undefined, undefined]]
//       } else {
//         return ans
//       }
//     } else {
//       const m_mid = Math.floor((m_end - m_start) / 2)

//       const [low_day, low_heros_start, low_heros_end] = rec(m_start, m_mid)
//       const [upp_day, upp_heros_start, upp_heros_end] = rec(m_mid + 1, m_end)

//       mid_heros

//       const day

//       return [day, low_heros_start, upp_heros_end]
//     }
//   }
// }

const randomInt = (min, max) => {
  return Math.floor(min + Math.random() * (max - min))
}

const random = () => {
  const max = 2 * Math.pow(10, 5)
  const max_power = Math.pow(10, 9)
  const monsters = Array(randomInt(1, max)).fill().map(() => randomInt(1, max_power))
  const heros = Array(randomInt(1, max)).fill().map(() => {
    return [randomInt(1, max_power), randomInt(1, max)]
  })
  return [monsters, heros]
}

const createNode = (power, endu, children) => {
  return {
    power,
    endu,
    children,
  }
}

const compareNumber = (a, b) => {
  if (a < b) {
    return -1
  } else if (a === b) {
    return 0
  } else {
    return 1
  }
}
const comparePower = (a, b) => compareNumber(a[0], b[0])
const compareEndu = (a, b) => compareNumber(a[1], b[1])

const binarySearchSortedList = (compareValueTo, list) => {
  const rec = (start, end) => {
    if (start === end) {
      const c = compareValueTo(list[start])
      if (c <= 0) {
        return start
      } else {
        return -1
      }
    }

    const mid = Math.floor((end - start) / 2) + start
    const c = compareValueTo(list[mid])

    if (c === 0) {
      return mid
    } else if (c === -1) {
      return rec(start, mid)
    } else {
      return rec(mid + 1, end)
    }
  }
  return rec(0, list.length - 1)
}

const createQuadNode = (val, x, y) => {
  return {
    val,
    x,
    y,
  }
}

const insert = (node, tree) => {
  let prop
  if (tree.x <= node.x) {
    if (tree.y <= node.y) {
      prop = 'c1'
    } else {
      prop = 'c4'
    }
  } else {
    if (tree.y <= node.y) {
      prop = 'c2'
    } else {
      prop = 'c3'
    }
  }

  if (tree[prop] === undefined) {
    tree[prop] = node
  } else {
    if (node.val && tree[prop].val) {
      if (tree[prop].x <= node.x && tree[prop].y <= node.y) {
        node.c1 = tree[prop].c1
        node.c2 = tree[prop].c2
        node.c3 = tree[prop].c3
        node.c4 = tree[prop].c4
        tree[prop] = node
        return
      } else if (node.x <= tree[prop].x && node.y <= tree[prop].y) {
        return
      }
    } else if (node.val === false && tree.val === false) {
      if (node.x <= tree[prop].x && node.y <= tree[prop].y) {
        node.c1 = tree[prop].c1
        node.c2 = tree[prop].c2
        node.c3 = tree[prop].c3
        node.c4 = tree[prop].c4
        tree[prop] = node
        return
      } else if (tree[prop].x <= node.x && tree[prop].y <= node.y) {
        return
      }
    }
    insert(node, tree[prop])
  }
}

const getVal = (x, y, tree) => {
  if (tree === undefined) {
    return undefined
  }

  if (
    tree.x <= x &&
    tree.y <= y &&
    tree.val === false
  ) {
    return false
  } else if (
    x <= tree.x &&
    y <= tree.y &&
    tree.val === true
  ) {
    return true
  } else if (
    tree.x <= x &&
    y < tree.y
  ) {
    return getVal(x, y, tree.c4)
  } else {
    return getVal(x, y, tree.c2)
  }
}

const betterMinDay = ([monsters, heros]) => {
  heros.sort((a, b) => {
    const ans = comparePower(a, b)
    if (ans === 0) {
      return -compareEndu(a, b)
    } else {
      return ans
    }
  })

  let num_day = 0
  let min_hero_stats = [0, 1]

  let mem
  const setAns = (power, endu, ans) => {
    if (mem === undefined) {
      mem = createQuadNode(ans, power, endu)
    } else {
      insert(createQuadNode(ans, power, endu), mem)
    }
  }
  const getAns = (power, endu) => {
    return getVal(power, endu, mem)
  }

  const aHeroHasStat = ([power, endu]) => {
    const already_ans = getAns(power, endu)
    if (already_ans !== undefined) {
      return already_ans
    }

    const compareValueTo = ([hero_power, hero_endu]) => {
      if (power < hero_power) {
        return -1
      } else if (power === hero_power) {
        return 0
      } else {
        return 1
      }
    }

    const ans = binarySearchSortedList(compareValueTo, heros)

    let return_val
    if (ans === -1) {
      return_val = false
    } else {
      return_val = false
      for (let i = ans; i < heros.length; i++) {
        if (endu <= heros[i][1]) {
          return_val = true
          break
        }
      }
    }
    setAns(power, endu, return_val)
    return return_val
  }

  let i = 0
  let must_move = true
  while (true) {
    if (i === monsters.length) {
      num_day++
      break
    }

    const monster = monsters[i]
    min_hero_stats[0] = Math.max(min_hero_stats[0], monster)

    if (aHeroHasStat(min_hero_stats)) {
      min_hero_stats[1] = min_hero_stats[1] + 1

      i++
      must_move = false
    } else {
      num_day++
      min_hero_stats = [0, 1]

      if (must_move) {
        num_day = -1
        break
      } else {
        must_move = true
      }
    }
  }

  // const iter = (must_move, i) => {
  //   if (i === monsters.length) {
  //     num_day++
  //     return
  //   }

  //   const monster = monsters[i]
  //   min_hero_stats[0] = Math.max(min_hero_stats[0], monster)

  //   if (aHeroHasStat(min_hero_stats)) {
  //     min_hero_stats[1] = min_hero_stats[1] + 1

  //     iter(false, i + 1)
  //   } else {
  //     num_day++
  //     min_hero_stats = [0, 1]

  //     if (must_move) {
  //       num_day = -1
  //       return
  //     } else {
  //       iter(true, i)
  //     }
  //   }
  // }

  // iter(true, 0)

  return num_day
}

// const minDay = ([monsters, heros]) => {
//   heros.sort((a,b)=>{
//     a = a[0]
//     b = b[0]
//     if (a < b) {
//       return 1
//     } else if (a === b) {
//       return 0
//     } else {
//       return -1
//     }
//   })

//   const total_mons = monsters.length

//   // Index -> Int -> Int -> Index
//   const battle = (curr_monster, hero_power, hero_endu) => {
//     if (
//       curr_monster === total_mons ||
//       hero_power < monsters[curr_monster] ||
//       hero_endu === 0
//     ) {
//       return curr_monster
//     } else {
//       return battle(curr_monster+1, hero_power, hero_endu-1)
//     }
//   }

//   const memo = {}
//   const getMemo = (prev_monster, curr_monster) => {
//     return memo[prev_monster+':'+curr_monster]
//   }
//   const setMemo = (val, prev_monster, curr_monster) => {
//     memo[prev_monster+':'+curr_monster] = val
//   }

//   // Index -> NumberOfDay
//   const rec = (prev_monster, curr_monster) => {
//     const already_ans = getMemo(prev_monster, curr_monster)
//     if (already_ans !== undefined) {
//       return already_ans
//     }

//     if (prev_monster === curr_monster) {
//       return Infinity
//     }

//     if (curr_monster === total_mons) {
//       return 0
//     }

//     // const ans = heros
//     //   .map(hero=>rec(curr_monster, battle(curr_monster, hero[0], hero[1])))
//     //   .reduce((acc, val) => Math.min(acc, val), Infinity) + 1

//     // const index = []
//     // for (let i = 0; i < heros.length; i++) {
//     //   const a = battle(curr_monster, heros[i][0], heros[i][1])
//     //   if (a === curr_monster) {
//     //     break
//     //   }
//     //   index.push(a)
//     // }
//     // const ans = index.map(a=>rec(curr_monster, a))
//     //   .reduce((acc, val) => Math.min(acc, val), Infinity) + 1

//     // let ans = Infinity
//     // for (let i = 0; i < index.length; i++) {
//     // }
//     // ans++

//     let ans = Infinity
//     for (let i = 0; i < heros.length; i++) {
//       const a = battle(curr_monster, heros[i][0], heros[i][1])
//       if (a === curr_monster) {
//         break
//       }
//       ans = Math.min(ans, rec(curr_monster, a))
//     }
//     ans++

//     setMemo(ans, prev_monster, curr_monster)

//     return ans
//   }

//   const ans = rec(-1, 0)
//   if (ans === Infinity) {
//     return -1
//   } else {
//     return ans
//   }
// }

const array = parse(content)
// array.forEach(a=>console.log(betterMinDay(a)))

const a = random()
console.log(a)
console.time('min day')
console.log(betterMinDay(a))
console.timeEnd('min day')


Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.The park is a rectangular table with $$$n$$$ rows and $$$m$$$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $$$1$$$. For example, park with $$$n=m=2$$$ has $$$12$$$ streets.You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park).    The park sizes are: $$$n=4$$$, $$$m=5$$$. The lighted squares are marked yellow. Please note that all streets have length $$$1$$$. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit. Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$n$$$, $$$m$$$ ($$$1 \le n, m \le 10^4$$$) — park sizes.

Print $$$t$$$ answers to the test cases. Each answer must be a single integer — the minimum number of lanterns that are required to light all the squares.

NotePossible optimal arrangement of the lanterns for the $$$2$$$-nd test case of input data example: Possible optimal arrangement of the lanterns for the $$$3$$$-rd test case of input data example:

function solve(a,b) {
    var p = a*b;
    var h = Math.floor(p/2);
    return (p % 2 == 0) ? h : ++h;
}
var t = Number(readline());
while (t--) {
    var arr = readline().split(' ').map(Number);
    var a = arr[0];
    var b = arr[1];
    print(solve(a,b));
}

//↓見なくていいよ！ここから--------------------------------------------------
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);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var N = one[0];
		var M = one[1];
		output[i] = Math.ceil(N * M / 2);
	}
	myout(myconv(output,9));
}

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

let stdinInput = '';

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

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

function main(data) {
  data = data.split('\n');
  const testCases = data.shift();
  for (let i = 0; i < testCases; i += 1) {
    let park = data[i].split(' ');
    let lantern = 0;
    const row = +park[0];
    const column = +park[1];
    if (row % 2 === 0) lantern = row / 2 * column;
    else {
      lantern = (row - 1) / 2 * column;
      lantern += Math.ceil(column / 2);
    }
    console.log(lantern);
  }
}

'use strict';

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

let inputString = [];
let currentLine = 0;

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

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

    //withTiming(main);
    main();
});

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

const withTiming = callback => {
    const start = new Date();
    callback();
    console.log(`Took ${new Date() - start} ms`);
}

function main() {
    const n = Math.floor(readline());
    const inputs = [];

    for (let i = 0; i < n; i++) {
        const [a, b] = readline().split(' ').map(a => parseInt(a));

        let sum = Math.floor(a / 2) * Math.floor(b / 2) * 2;
        sum += (a % 2) * Math.ceil(b / 2) + (b % 2) * Math.ceil(a / 2) - ((a % 2) && (b % 2));
        console.log(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 [a, b] = d.split(' ').map(Number);

  if (Number.isInteger(a) && Number.isInteger(b)) {
    console.log(Math.ceil(a*b/2));
  }

  c++;
});

const processData = (lines) => {
  const n = +lines[0]
  for (let i=0; i<n; i++) {
    const [m, n] = lines[i+1].split(' ').map(x => +x)
    const max = Math.max(m, n)
    const min = Math.min(m, n)

    if (max > 2) {
      if (max % 2 === 0) {
        console.log(max/2 *min)
      } else {
        console.log( (max-1)/2*min + Math.ceil(min/2))
      }
    } else {
      console.log(Math.ceil(m*n/2))
    }
  }
}

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';
// node.js
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() {
    var testCases = parseInt(readLine());

    function minNumberOfLanterns(row, column) {
        return Math.ceil((row * column / 2));
    }

    for (var i = 0; i < testCases; i++) {
        var numbers = readLine()
            .split(" ")
            .map(num => parseInt(num));

        var row = numbers[0];
        var column = numbers[1];

        console.log(minNumberOfLanterns(row, column));
    }
}

let outFd = null;
let fs = null;
let promisify = null;

function stdinStdout() {
    process.stdin.resume();
    process.stdin.setEncoding('utf8');

    let lingeringLine = "";
    process.stdin.on('data', function(chunk) {
        lines = chunk.split("\n");

        lines[0] = lingeringLine + lines[0];
        lingeringLine = lines.pop();

        lines.map(s => s.trim()).forEach(line => {
            processLine(line.trim());
        });
    });

    process.stdin.on('end', function() {
        processLine(lingeringLine.trim());
    });
}

function inOutFiles(fin, fout) {
    fs = require('fs');
    outFd = fs.openSync(fout, 'w');
    data = fs.readFileSync(fin);
    data.toString().split('\n').map(line => line.trim()).forEach(processLine);
    fs.closeSync(outFd);
}

function output(s) {
    if(outFd) {
        fs.writeSync(outFd, s.toString() + '\n');
    } else {
        console.log(s);
    }
}

let t = -1;
let n;
let m;

function processLine(line) {
    if(t == -1) {
        t = parseInt(line);
    } else if(t > 0) {
        t--;
        [n, m] = line.split(/\s+/).slice(0, 2).map(s => parseInt(s));
        if(n < m) {
            [n, m] = [m, n];
        }
        solve();
    }
}

function solve() {
    output((n - n % 2) / 2 * m + (n % 2) * ((m - m % 2) / 2 + m % 2));
}

stdinStdout();
// inOutFiles('amusing.in', 'amusing.out');

function lamps(n, m) {
    if (m % 2 != 0) {
        if (n % 2 == 0) {
            return ((Math.floor(n/2) * m));
        }
        else {
            return ((Math.floor(m/2) * n) + Math.floor(n / 2) + 1);
        }
    }
    else {
        return (Math.floor(m/2) * n);
    }
}

function processData(input) {
    const inputArr = input.split("\n");
    const n = inputArr[0];
    for (let i = 1; i <= parseInt(n); i ++) {
        const n_m = inputArr[i].split(' ');
        console.log(lamps(parseInt(n_m[0]), parseInt(n_m[1])));
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

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 [a, b] = d.split(' ').map(Number);

  console.log(Math.ceil(a*b/2));

  c++;
});

function lamps(n, m) {
    if (m % 2 != 0) {
        if (n % 2 == 0) {
            return ((Math.floor(m/2) * n));
        }
        else {
            return ((Math.floor(m/2) * n) + Math.floor(n / 2) + 1);
        }
    }
    else {
        return (Math.floor(m/2) * n);
    }
}

function processData(input) {
    const inputArr = input.split("\n");
    const n = inputArr[0];
    for (let i = 1; i <= parseInt(n); i ++) {
        const n_m = inputArr[i].split(' ');
        console.log(lamps(parseInt(n_m[0]), parseInt(n_m[1])));
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

function lamps(n, m) {
    if (m % 2 != 0) {
        if (n % 2 == 0) {
            return ((Math.floor(m/2) * n) + Math.floor(n / 2));
        }
        else {
            return ((Math.floor(m/2) * n) + Math.floor(n / 2) + 1);
        }
    }
    else {
        let temp = n;
        n = m;
        m = temp;

        if (n % 2 == 0) {
            return ((Math.floor(m/2) * n));
        }
        else {
            return ((Math.floor(m/2) * n));
        }
    }
}

function processData(input) {
    const inputArr = input.split("\n");
    const n = inputArr[0];
    for (let i = 1; i <= parseInt(n); i ++) {
        const n_m = inputArr[i].split(' ');
        console.log(lamps(parseInt(n_m[0]), parseInt(n_m[1])));
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});


Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence pi. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.While Gennady treats the teeth of the i-th child, the child is crying with the volume of vi. At that the confidence of the first child in the line is reduced by the amount of vi, the second one — by value vi - 1, and so on. The children in the queue after the vi-th child almost do not hear the crying, so their confidence remains unchanged.If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of dj and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of dj.All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.

The first line of the input contains a positive integer n (1 ≤ n ≤ 4000) — the number of kids in the line.  Next n lines contain three integers each vi, di, pi (1 ≤ vi, di, pi ≤ 106) — the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child.

In the first line print number k — the number of children whose teeth Gennady will cure. In the second line print k integers — the numbers of the children who will make it to the end of the line in the increasing order.

NoteIn the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to  - 2, 1, 3, 1, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0, 2, 0. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit.In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5,  - 1, 6, 8. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5, 5, 7. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0, 3. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last.

function toi(x){return parseInt(x);}
var n=+readline();
var v=[];
var d=[];
var p=[];
var res=[];
for(var i=0;i<n;i++){
    t=readline().split(" ").map(toi);
    v.push(t[0]);
    d.push(t[1]);
    p.push(t[2]);
}
for(var i=0;i<n;i++){
    if(p[i]>=0){
	res.push(i+1);
	var tv=v[i];
	var td=0;
	for(var j=i+1;j<n;j++){
	    if(p[j]>=0){
		if(tv>0){
		    p[j]=Math.max(p[j]-tv,-1);
		    tv-=1
		    if(p[j]<0){
			td+=d[j];
		    }else{
			p[j]=Math.max(p[j]-td,-1);
			if(p[j] < 0){
			    td+=d[j];
			}
		    }
		}else{
		    p[j]=Math.max(p[j]-td,-1);
		    if(p[j] < 0){
			td+=d[j];
		    }
		}
	    }
	}
    }
}
print(res.length);
print(res.join(" "));

n = +readline();
v = [], d = [], p = [];
line = [];
for (var i = 0; i < n; i++) {
	input = readline().split(" ").map(Number);
	v[i] = input[0];
	d[i] = input[1];
	p[i] = input[2];
	line.push({v:v[i],d:d[i],p:p[i],i:i+1});
}

answer = [];
while (line.length > 0) {
	//write(line + "\n");

	var patient = line[0];
	//write(patient.v + "\n");
	answer.push(patient.i);
	line.splice(0,1);

	//
	var cry = -1;
	for (var i = 0; i < line.length && i < patient.v; i++) {
		line[i].p -= patient.v-i;
		if (cry == -1 && line[i].p < 0)
			cry = i;
	}

	//for (var i = 0; i < line.length; i++) write(line[i].p + " ");

	while (cry >= 0) {
		var j = cry;
		cry = -1;
		for (var i = j; i < line.length; i++) {
			line[i].p -= line[j].d;
			if (cry == -1 && i > j && line[i].p < 0) {
				cry = i;
			}
		}
	}

	for (var i = line.length-1; i >= 0; --i) {
		if (line[i].p < 0) {
			line.splice(i,1);
		}
	}

}
write(answer.length + "\n");
for (var i = 0; i < answer.length; i++) {
	write(answer[i] + " ");
}


There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≤ i, j ≤ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.

The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.

Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.

var str = readline().split('').sort();
var sum = 0;
var num = 1;

for(var i = 0; i<str.length; i++) {
	if (str[i] == str[i+1]) {
		num++;
	} else {
		sum += num * num;
		num = 1;
	}
}

print(sum);

function result(str) {
  var ret = 0;
  var values = {};
  for (var i=0;i<str.length;i++) {
    values[str.charCodeAt(i)] = (values[str.charCodeAt(i)] || 0) + 1;
  }
  for (var k in values) {
    ret += values[k] * values[k];
  }
  return ret;
}

print(result(readline()));

print(function(s) {
	var cnt = new Int32Array(256);
	for (var i = 0; i < 256; i++)
		cnt[i] = 1;
	var ans = 0;
	for (var i = 0; i < s.length; i++) {
		ans += cnt[s.charCodeAt(i)];
		cnt[s.charCodeAt(i)] += 2;
	}
	return ans;
}(readline()));

'use strict'

let S = readline()

let ls = {}

for (let i = 0; i < S.length; i++) {
  let l = S[i]
  ls[l] = ls[l] || 0
  ls[l]++
}

let c = 0
Object.keys(ls).forEach(l => {
  c += ls[l] * ls[l]
})

print(c)