Alice and Bob are playing a game. They are given an array $$$A$$$ of length $$$N$$$. The array consists of integers. They are building a sequence together. In the beginning, the sequence is empty. In one turn a player can remove a number from the left or right side of the array and append it to the sequence. The rule is that the sequence they are building must be strictly increasing. The winner is the player that makes the last move. Alice is playing first. Given the starting array, under the assumption that they both play optimally, who wins the game?

The first line contains one integer $$$N$$$ ($$$1 \leq N \leq 2*10^5$$$) - the length of the array $$$A$$$. The second line contains $$$N$$$ integers $$$A_1$$$, $$$A_2$$$,...,$$$A_N$$$ ($$$0 \leq A_i \leq 10^9$$$)

The first and only line of output consists of one string, the name of the winner. If Alice won, print "Alice", otherwise, print "Bob".

let s = []
process.stdin.on('data', l => s+=l)
process.stdin.on('end', () => {
    var rows=s.split("\n")
    var n=1*rows[0];
    a=rows[1].split(" ").map(x=>+x);

    var L=0,R=a.length-1;
    var e=winner(-1,L,R,0);
    console.log(["Alice","Bob"][e]);
})

var a;

function winner(min,L,R,player){
  while (1){
    if (R==L) return (a[L]>min?player:1-player);
    if (a[L]>min){
      if (a[R]>min){
         if (R==L+1) return player;
         if (R==L+2) return ((a[L+1]<=a[L])||(a[L+1]<=a[R])?player:1-player);
         if ((a[L+1]<=a[L])&&(a[R]<=a[L])) return player;
         if ((a[R-1]<=a[R])&&(a[L]<=a[R])) return player;
         if (a[L]>a[R]){
          if (winner(a[L],L+1,R,1-player)==player) return player;
          min=a[R--];player=1-player;
         } else {
          if (winner(a[R],L,R-1,1-player)==player) return player;
          min=a[L++];player=1-player;
         }
      } else { // forzato L
        var i=L+1;
        while (a[i]>a[i-1]) i++;
        return ((i-L)%2)?player:1-player;
      }
    } else {
      if (a[R]>min){ // forzato R
        var i=R-1;
        while (a[i]>a[i+1]) i--;
        return ((R-i)%2)?player:1-player;
      } else return 1-player;
    }
  }
}

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        nums = new Array(n);
  for (let i = 0; i < n; i++) nums[i] = rn();
  const l = new Array(n).fill(-1),
        r = new Array(n).fill(n);
  {
    let pre = -1;
    for (let i = 0; i < n; i++) {
      var _nums;
      if (nums[i] >= ((_nums = nums[i - 1]) !== null && _nums !== void 0 ? _nums : Infinity)) pre = i;
      l[i] = pre;
    }
    pre = n;
    for (let i = n - 1; i >= 0; i--) {
      var _nums2;
      if (nums[i] >= ((_nums2 = nums[i + 1]) !== null && _nums2 !== void 0 ? _nums2 : Infinity)) pre = i;
      r[i] = pre;
    }
  }
  const cache = Array.from({
    length: n
  }, () => ({}));
  const dfs = RTI((i, j, p) => {
    var _cache$i$j2;
    if (i > j) return [() => [], () => false];
    if (nums[i] <= p && nums[j] <= p) return [() => [], () => false];
    if (nums[i] >= nums[i + 1] && nums[i] >= nums[j]) return [() => [], () => true];
    if (nums[j] >= nums[i] && nums[j] >= nums[j - 1]) return [() => [], () => true];
    if (((_cache$i$j2 = cache[i][j]) === null || _cache$i$j2 === void 0 ? void 0 : _cache$i$j2[p]) !== undefined) return [() => [], () => cache[i][j][p]];
    if (cache[i][j] === undefined) cache[i][j] = {};
    const inside = () => {
      let res = [];
      if (nums[i] > p && nums[j] > p) {
        if (nums[i] > nums[j]) {
          if (r[i] - i + 1 & 1) {
            cache[i][j][p] = true;
            return [];
          }
          res.push([i, j - 1, nums[j]]);
        } else if (nums[i] < nums[j]) {
          if (j - l[j] + 1 & 1) {
            cache[i][j][p] = true;
            return [];
          }
          res.push([i + 1, j, nums[i]]);
        } else {
          res.push([i, j - 1, nums[j]]);
          res.push([i + 1, j, nums[i]]);
        }
      } else if (nums[i] > p) {
        res.push([i + 1, j, nums[i]]);
      } else if (nums[j] > p) {
        res.push([i, j - 1, nums[j]]);
      }
      return res;
    };
    const after = (args, childResult) => {
      const [a, b] = childResult;
      let res = true;
      if (b === undefined) {
        if (a) res = false;
      } else if (a && b) res = false;
      if (!cache[i][j][p]) cache[i][j][p] = res;
      return !!cache[i][j][p];
    };
    return [inside, after];
  });
  if (dfs(0, n - 1, -1)) return 'Alice';
  return 'Bob';
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = ([args], [result]) => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, curCall.args, curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        nums = new Array(n);
  for (let i = 0; i < n; i++) nums[i] = rn();
  const l = new Array(n).fill(-1),
        r = new Array(n).fill(n);
  {
    let pre = -1;
    for (let i = 0; i < n; i++) {
      var _nums;
      if (nums[i] >= ((_nums = nums[i - 1]) !== null && _nums !== void 0 ? _nums : Infinity)) pre = i;
      l[i] = pre;
    }
    pre = n;
    for (let i = n - 1; i >= 0; i--) {
      var _nums2;
      if (nums[i] >= ((_nums2 = nums[i + 1]) !== null && _nums2 !== void 0 ? _nums2 : Infinity)) pre = i;
      r[i] = pre;
    }
  }
  const h = new Map(),
        e = [],
        ne = [],
        d = new Map(),
        dp = new Map();
  const add = (i, j) => {
    if (!h.has(i)) {
      h.set(i, -1);
      d.set(i, 0);
      dp.set(i, 0);
    }
    if (!h.has(j)) {
      h.set(j, -1);
      d.set(j, 0);
      dp.set(j, 0);
    }
    e.push(j);
    ne.push(h.get(i));
    d.set(j, d.get(j) + 1);
    h.set(i, ne.length - 1);
  };
  const queue = [[n - 1, -1]];
  for (let [u, pre] of queue) {
    const i = Math.floor(u / n),
          j = u % n;
    if (nums[i] >= nums[i + 1] && nums[i] >= nums[j] || nums[j] >= nums[i] && nums[j] >= nums[j - 1] || i === j) {
      dp.set(u, 1);
    } else {
      if (nums[i] > pre && nums[j] > pre) {
        if (nums[i] < nums[j]) {
          const v = (i + 1) * n + j;
          add(v, u);
          queue.push([v, nums[i]]);
          if (j - l[j] + 1 & 1) dp.set(u, 1);
        } else if (nums[i] > nums[j]) {
          const v = i * n + j - 1;
          add(v, u);
          queue.push([v, nums[j]]);
          if (r[i] - i + 1 & 1) dp.set(u, 1);
        } else {
          let v = (i + 1) * n + j;
          add(v, u);
          queue.push([v, nums[i]]);
          v = i * n + j - 1;
          add(v, u);
          queue.push([v, nums[j]]);
        }
      } else if (nums[i] > pre) {
        const v = (i + 1) * n + j;
        add(v, u);
        queue.push([v, nums[i]]);
      } else if (nums[j] > pre) {
        const v = i * n + j - 1;
        add(v, u);
        queue.push([v, nums[j]]);
      }
    }
  }
  {
    const q = [];
    for (let [i, cnt] of d) {
      if (!cnt) q.push(i);
    }
    for (let u of q) {
      for (let i = h.get(u); ~i; i = ne[i]) {
        const v = e[i];
        dp.set(v, dp.get(v) | dp.get(u) ^ 1);
        if (d.get(v) === 1) {
          q.push(v);
        }
        d.set(v, d.get(v) - 1);
      }
    }
    if (dp.get(n - 1)) return 'Alice';
    return 'Bob';
  }
}

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

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

let s = []
process.stdin.on('data', l => s+=l)
process.stdin.on('end', () => {
    var rows=s.split("\n")
    var n=1*rows[0];
    a=rows[1].split(" ").map(x=>+x);

    var L=0,R=a.length-1;
    var e=winner(-1,L,R,0);
    console.log(["Alice","Bob"][e]);
})

var a;

function winner(min,L,R,player){
  while (1){
    if (R==L) return (a[L]>min?player:1-player);
    if (a[L]>min){
      if (a[R]>min){
         if (R==L+1) return player;
         if (R==L+2) return ((a[L+1]<=a[L])||(a[L+1]<=a[R])?player:1-player);
         if ((a[L+1]<=a[L])&&(a[R]<=a[L])) return player;
         if ((a[R-1]<=a[R])&&(a[L]<=a[R])) return player;
         if (a[L]>a[R]){
          if (winner(a[L],L+1,R,1-player)==player) return player;
          min=a[R--];player=1-player;
         } else {
          if (winner(a[R],L,R-1,1-player)==player) return player;
          min=a[L++];player=1-player;
         }
      } else { // forzato L
        var i=L+1;
        while (a[i]>a[L]) i++;
        return (i-L)%2?player:1-player;
      }
    } else {
      if (a[R]>min){ // forzato R
        var i=R-1;
        while (a[i]>a[R]) i--;
        return (R-i)%2?player:1-player;
      } else return 1-player;
    }
  }
}

let s = []
process.stdin.on('data', l => s+=l)
process.stdin.on('end', () => {
    var rows=s.split("\n")
    var n=1*rows[0];
    var a=rows[1].split(" ").map(x=>1*x);

    var lastSeq=-1;
    var L=0,R=a.length-1;
    var turn=0; //0=alice 1=bob turn
    while (R-L>=0){
        //console.log("choices:"+a[L]+","+a[R])
        if (a[L]>lastSeq){
            if (a[R]>lastSeq){ // scelta
                lastSeq=a[L++];
            } else lastSeq=a[L++]; //forzata
        } else {
            if (a[R]>lastSeq) lastSeq=a[R--]; // forzata
            else break; // nessuna possibilità
        }
        //console.log(turn+" plays "+lastSeq)
        turn=1-turn;
    }
    console.log(["Alice","Bob"][1-turn]);
})

let s = []
process.stdin.on('data', l => s+=l)
process.stdin.on('end', () => {
    var rows=s.split("\n")
    var n=1*rows[0];
    var a=rows[1].split(" ").map(x=>1*x);

    var lastSeq=-1;
    var L=0,R=a.length-1;
    var turn=0; //0=alice 1=bob turn
    while (R-L>=0){
        //console.log("choices:"+a[L]+","+a[R])
        if (a[L]>lastSeq){
            lastSeq=a[L++]
        } else if (a[R]>lastSeq){
            lastSeq=a[R--]
        } else break;
        //console.log(turn+" plays "+lastSeq)
        turn=1-turn;
    }
    console.log(["Alice","Bob"][1-turn]);
})

let s = []
process.stdin.on('data', l => s+=l)
process.stdin.on('end', () => {
    var rows=s.split("\n")
    var n=1*rows[0];
    var a=rows[1].split(" ").map(x=>1*x);

    var lastSeq=-1;
    var L=0,R=a.length-1;
    var turn=0; //0=alice 1=bob turn
    while (R-L>=0){
        console.log("choices:"+a[L]+","+a[R])
        if (a[L]>lastSeq){
            lastSeq=a[L++]
        } else if (a[R]>lastSeq){
            lastSeq=a[R--]
        } else break;
        console.log(turn+" plays "+lastSeq)
        turn=1-turn;
    }
    console.log(["Alice","Bob"][1-turn]);
})

let s = []
process.stdin.on('data', l => s+=l)
process.stdin.on('end', () => {
    var rows=s.split("\n")
    var n=1*rows[0];
    var a=rows[1].split(" ");

    var lastSeq=-1;
    var L=0,R=a.length-1;
    var turn=0; //0=alice 1=bob turn
    while (R-L>0){
        if (a[L]>lastSeq){
            lastSeq=a[L++]
        } else if (a[R]>lastSeq){
            lastSeq=a[R--]
        } else break;
        turn=1-turn;
    }
    console.log(["Alice","Bob"][1-turn]);
})

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        nums = new Array(n);
  for (let i = 0; i < n; i++) nums[i] = rn();
  const l = new Array(n).fill(-1),
        r = new Array(n).fill(n);
  {
    let pre = -1;
    for (let i = 0; i < n; i++) {
      var _nums;
      if (nums[i] >= ((_nums = nums[i - 1]) !== null && _nums !== void 0 ? _nums : Infinity)) pre = i;
      l[i] = pre;
    }
    pre = n;
    for (let i = n - 1; i >= 0; i--) {
      var _nums2;
      if (nums[i] >= ((_nums2 = nums[i + 1]) !== null && _nums2 !== void 0 ? _nums2 : Infinity)) pre = i;
      r[i] = pre;
    }
  }
  const cache = Array.from({
    length: n
  }, () => ({}));
  const dfs = RTI((i, j, p) => {
    var _cache$i$j2;
    if (i > j) return [() => [], () => false];
    if (nums[i] <= p && nums[j] <= p) return [() => [], () => false];
    if (nums[i] >= nums[i + 1] && nums[i] >= nums[j]) return [() => [], () => true];
    if (nums[j] >= nums[i] && nums[j] >= nums[j - 1]) return [() => [], () => true];
    if (((_cache$i$j2 = cache[i][j]) === null || _cache$i$j2 === void 0 ? void 0 : _cache$i$j2[p]) !== undefined) return [() => [], () => cache[i][j][p]];
    if (cache[i][j] === undefined) cache[i][j] = {};
    const inside = () => {
      let res = [];
      if (nums[i] > p && nums[j] > p) {
        if (nums[i] > nums[j]) {
          if (r[i] - i + 1 & 1) {
            cache[i][j][p] = true;
          }
          res.push([i, j - 1, nums[j]]);
        } else if (nums[i] < nums[j]) {
          if (i - l[i] + 1 & 1) {
            cache[i][j][p] = true;
          }
          res.push([i + 1, j, nums[i]]);
        } else {
          res.push([i, j - 1, nums[j]]);
          res.push([i + 1, j, nums[i]]);
        }
      } else if (nums[i] > p) {
        res.push([i + 1, j, nums[i]]);
      } else if (nums[j] > p) {
        res.push([i, j - 1, nums[j]]);
      }
      return res;
    };
    const after = (args, childResult) => {
      const [a, b] = childResult;
      let res = true;
      if (b === undefined) {
        if (a) res = false;
      } else if (a && b) res = false;
      if (!cache[i][j][p]) cache[i][j][p] = res;
      return !!cache[i][j][p];
    };
    return [inside, after];
  });
  if (dfs(0, n - 1, -1)) return 'Alice';
  return 'Bob';
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = ([args], [result]) => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, curCall.args, curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        nums = new Array(n);
  for (let i = 0; i < n; i++) nums[i] = rn();
  const l = new Array(n).fill(-1),
        r = new Array(n).fill(n);
  {
    let pre = -1;
    for (let i = 0; i < n; i++) {
      var _nums;
      if (nums[i] >= ((_nums = nums[i - 1]) !== null && _nums !== void 0 ? _nums : Infinity)) pre = i;
      l[i] = pre;
    }
    pre = n;
    for (let i = n - 1; i >= 0; i--) {
      var _nums2;
      if (nums[i] >= ((_nums2 = nums[i + 1]) !== null && _nums2 !== void 0 ? _nums2 : Infinity)) pre = i;
      r[i] = pre;
    }
  }
  const cache = Array.from({
    length: n
  }, () => ({}));
  const dfs = RTI((i, j, p) => {
    var _cache$i$j2;
    if (i > j) return [() => [], () => false];
    if (nums[i] <= p && nums[j] <= p) return [() => [], () => false];
    if (nums[i] >= nums[i + 1] && nums[i] >= nums[j]) return [() => [], () => true];
    if (nums[j] >= nums[i] && nums[j] >= nums[j - 1]) return [() => [], () => true];
    if (((_cache$i$j2 = cache[i][j]) === null || _cache$i$j2 === void 0 ? void 0 : _cache$i$j2[p]) !== undefined) return [() => [], () => cache[i][j][p]];
    if (cache[i][j] === undefined) cache[i][j] = {};
    const inside = () => {
      let res = [];
      if (nums[i] > p && nums[j] > p) {
        if (nums[i] > nums[j]) {
          if (r[i] - i + 1 & 1) {
            cache[i][j][p] = true;
            return [];
          }
          res.push([i, j - 1, nums[j]]);
        } else if (nums[i] < nums[j]) {
          if (i - l[i] + 1 & 1) {
            cache[i][j][p] = true;
            return [];
          }
          res.push([i + 1, j, nums[i]]);
        } else {
          res.push([i, j - 1, nums[j]]);
          res.push([i + 1, j, nums[i]]);
        }
      } else if (nums[i] > p) {
        res.push([i + 1, j, nums[i]]);
      } else if (nums[j] > p) {
        res.push([i, j - 1, nums[j]]);
      }
      return res;
    };
    const after = (args, childResult) => {
      const [a, b] = childResult;
      let res = true;
      if (b === undefined) {
        if (a) res = false;
      } else if (a && b) res = false;
      if (!cache[i][j][p]) cache[i][j][p] = res;
      return !!cache[i][j][p];
    };
    return [inside, after];
  });
  if (dfs(0, n - 1, -1)) return 'Alice';
  return 'Bob';
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = ([args], [result]) => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, curCall.args, curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        nums = new Array(n);
  for (let i = 0; i < n; i++) nums[i] = rn();
  const l = new Array(n).fill(-1),
        r = new Array(n).fill(n);
  {
    let pre = -1;
    for (let i = 0; i < n; i++) {
      var _nums;
      if (nums[i] >= ((_nums = nums[i - 1]) !== null && _nums !== void 0 ? _nums : Infinity)) pre = i;
      l[i] = pre;
    }
    pre = n;
    for (let i = n - 1; i >= 0; i--) {
      var _nums2;
      if (nums[i] >= ((_nums2 = nums[i + 1]) !== null && _nums2 !== void 0 ? _nums2 : Infinity)) pre = i;
      r[i] = pre;
    }
  }
  const cache = Array.from({
    length: n
  }, () => ({}));
  const dfs = RTI((i, j, p) => {
    var _cache$i$j2;
    if (i > j) return [() => [], () => false];
    if (nums[i] <= p && nums[j] <= p) return [() => [], () => false];
    if (nums[i] >= nums[i + 1] && nums[i] >= nums[j]) return [() => [], () => true];
    if (nums[j] >= nums[i] && nums[j] >= nums[j - 1]) return [() => [], () => true];
    if (((_cache$i$j2 = cache[i][j]) === null || _cache$i$j2 === void 0 ? void 0 : _cache$i$j2[p]) !== undefined) return [() => [], () => cache[i][j][p]];
    if (cache[i][j] === undefined) cache[i][j] = {};
    const inside = () => {
      let res = [];
      if (nums[i] > p && nums[j] > p) {
        if (nums[i] > nums[j]) {
          if (r[i] - i + 1 & 1) {
            cache[i][j][p] = true;
            return [];
          }
          res.push([i, j - 1, nums[j]]);
        } else if (nums[i] < nums[j]) {
          if (i - l[i] + 1 & 1) {
            cache[i][j][p] = true;
            return [];
          }
          res.push([i + 1, j, nums[i]]);
        } else {
          res.push([i, j - 1, nums[j]]);
          res.push([i + 1, j, nums[i]]);
        }
      } else if (nums[i] > p) {
        res.push([i + 1, j, nums[i]]);
      } else if (nums[j] > p) {
        res.push([i, j - 1, nums[j]]);
      }
      return res;
    };
    const after = (args, childResult) => {
      const [a, b] = childResult;
      let res = true;
      if (b === undefined) {
        if (a) res = false;
      } else if (a && b) res = false;
      if (!cache[i][j][p]) cache[i][j][p] = res;
      return cache[i][j][p];
    };
    return [inside, after];
  });
  if (dfs(0, n - 1, -1)) return 'Alice';
  return 'Bob';
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = ([args], [result]) => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, curCall.args, curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        nums = new Array(n);
  for (let i = 0; i < n; i++) nums[i] = rn();
  const l = new Array(n).fill(-1),
        r = new Array(n).fill(n);
  {
    let pre = -1;
    for (let i = 0; i < n; i++) {
      var _nums;
      if (nums[i] >= ((_nums = nums[i - 1]) !== null && _nums !== void 0 ? _nums : Infinity)) pre = i;
      l[i] = pre;
    }
    pre = n;
    for (let i = n - 1; i >= 0; i--) {
      var _nums2;
      if (nums[i] >= ((_nums2 = nums[i + 1]) !== null && _nums2 !== void 0 ? _nums2 : Infinity)) pre = i;
      r[i] = pre;
    }
  }
  const cache = Array.from({
    length: n
  }, () => ({}));
  const dfs = RTI((i, j, p) => {
    var _cache$i$j2;
    if (i > j) return [() => [], () => false];
    if (nums[i] <= p && nums[j] <= p) return [() => [], () => false];
    if (nums[i] >= nums[i + 1] && nums[i] >= nums[j]) return [() => [], () => true];
    if (nums[j] >= nums[i] && nums[j] >= nums[j - 1]) return [() => [], () => true];
    if (((_cache$i$j2 = cache[i][j]) === null || _cache$i$j2 === void 0 ? void 0 : _cache$i$j2[p]) !== undefined) return [() => [], () => cache[i][j][p]];
    if (cache[i][j] === undefined) cache[i][j] = {};
    const inside = () => {
      let res = [];
      if (nums[i] > p && nums[j] > p) {
        if (nums[i] > nums[j]) {
          if (r[i] - i + 1 & 1) {
            cache[i][j][p] = true;
            return [];
          }
          res.push([i, j - 1, nums[j]]);
        } else if (nums[i] < nums[j]) {
          if (i - l[i] + 1 & 1) {
            cache[i][j][p] = true;
            return [];
          }
          res.push([i + 1, j, nums[i]]);
        } else {
          res.push([i, j - 1, nums[j]]);
          res.push([i + 1, j, nums[i]]);
        }
      } else if (nums[i] > p) {
        res.push([i + 1, j, nums[i]]);
      } else if (nums[j] > p) {
        res.push([i, j - 1, nums[j]]);
      }
      return res;
    };
    const after = (args, childResult) => {
      const [a, b] = childResult;
      let res = true;
      if (b === undefined) {
        if (a) res = false;
      } else if (a && b) res = false;
      if (!cache[i][j][p]) cache[i][j][p] = res;
      return res;
    };
    return [inside, after];
  });
  if (dfs(0, n - 1, -1)) return 'Alice';
  return 'Bob';
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = ([args], [result]) => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, curCall.args, curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        nums = new Array(n);
  for (let i = 0; i < n; i++) nums[i] = rn();
  const cache = Array.from({
    length: n
  }, () => ({}));
  const dfs = RTI((i, j, p) => {
    var _cache$i$j2;
    if (i > j) return [() => [], () => false];
    if (nums[i] <= p && nums[j] <= p) return [() => [], () => false];
    if (nums[i] >= nums[i + 1] && nums[i] >= nums[j]) return [() => [], () => true];
    if (nums[j] >= nums[i] && nums[j] >= nums[j - 1]) return [() => [], () => true];
    if (((_cache$i$j2 = cache[i][j]) === null || _cache$i$j2 === void 0 ? void 0 : _cache$i$j2[p]) !== undefined) return [() => [], () => cache[i][j][p]];
    const inside = () => {
      let res = [];
      if (nums[i] > p) {
        res.push([i + 1, j, nums[i]]);
      }
      if (nums[j] > p) {
        res.push([i, j - 1, nums[j]]);
      }
      return res;
    };
    const after = (args, childResult) => {
      const [a, b] = childResult;
      let res = true;
      if (b === undefined) {
        res = !a;
      }
      res = !a && !b;
      if (cache[i][j] === undefined) cache[i][j] = {};
      cache[i][j][p] = res;
      return res;
    };
    return [inside, after];
  });
  if (dfs(0, n - 1, -1)) return 'Alice';
  return 'Bob';
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = ([args], [result]) => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, curCall.args, curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        nums = new Array(n);
  for (let i = 0; i < n; i++) nums[i] = rn();
  const l = new Array(n).fill(-1),
        r = new Array(n).fill(n);
  {
    let pre = -1;
    for (let i = 0; i < n; i++) {
      var _nums;
      if (nums[i] >= ((_nums = nums[i - 1]) !== null && _nums !== void 0 ? _nums : Infinity)) pre = i;
      l[i] = pre;
    }
    pre = n;
    for (let i = n - 1; i >= 0; i--) {
      var _nums2;
      if (nums[i] >= ((_nums2 = nums[i + 1]) !== null && _nums2 !== void 0 ? _nums2 : Infinity)) pre = i;
      r[i] = pre;
    }
  }
  const cache = Array.from({
    length: n
  }, () => ({}));
  const dfs = RTI((i, j, p) => {
    var _cache$i$j2;
    if (i > j || nums[i] <= p && nums[j] <= p) return [() => [], () => false];
    if (((_cache$i$j2 = cache[i][j]) === null || _cache$i$j2 === void 0 ? void 0 : _cache$i$j2[p]) !== undefined) return [() => [], () => cache[i][j][p]];
    const inside = () => {
      let res = [];
      if (nums[i] > p) {
        res.push([i + 1, j, nums[i]]);
      }
      if (nums[j] > p) {
        res.push([i, j - 1, nums[j]]);
      }
      return res;
    };
    const after = (args, childResult) => {
      const [a, b] = childResult;
      let res = true;
      if (b === undefined) {
        res = !a;
      }
      res = !a && !b;
      if (cache[i][j] === undefined) cache[i][j] = {};
      cache[i][j][p] = res;
      return res;
    };
    return [inside, after];
  });
  if (dfs(0, n - 1, -1)) return 'Alice';
  return 'Bob';
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = ([args], [result]) => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, curCall.args, curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        nums = new Array(n);
  for (let i = 0; i < n; i++) nums[i] = rn();
  const h = new Map(),
        e = [],
        ne = [],
        d = new Map();
  const add = (i, j) => {
    if (!h.has(i)) {
      h.set(i, -1);
      d.set(i, 0);
    }
    if (!h.has(j)) {
      h.set(j, -1);
      d.set(j, 0);
    }
    e.push(j);
    ne.push(h.get(i));
    d.set(j, d.get(j) + 1);
    h.set(i, ne.length - 1);
  };
  const queue = [[n - 1, -1]],
        dp = new Map();
  for (let [u, pre] of queue) {
    const i = Math.floor(u / n),
          j = u % n;
    if (nums[i] >= nums[i + 1] && nums[i] >= nums[j] || nums[j] >= nums[i] && nums[j] >= nums[j - 1] || i === j) {
      dp.set(u, 1);
    } else {
      if (nums[i] > pre) {
        const v = (i + 1) * n + j;
        add(v, u);
        queue.push([v, nums[i]]);
      }
      if (nums[j] > pre) {
        const v = i * n + j - 1;
        add(v, u);
        queue.push([v, nums[j]]);
      }
    }
  }
  {
    const q = [];
    for (let [i, cnt] of d) {
      if (!cnt) q.push(i);
    }
    for (let u of q) {
      for (let i = h.get(u); ~i; i = ne[i]) {
        const v = e[i];
        if (dp.has(v)) {
          dp.set(v, dp.get(v) | ~dp.get(u));
        } else {
          dp.set(v, dp.get(u) ^ 1);
        }
        if (d.get(v) === 1) {
          q.push(v);
        }
        d.set(v, d.get(v) - 1);
      }
    }
    if (dp.get(n - 1)) return 'Alice';
    return 'Bob';
  }
}

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

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


You are given $$$n$$$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String $$$a$$$ is a substring of string $$$b$$$ if it is possible to choose several consecutive letters in $$$b$$$ in such a way that they form $$$a$$$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of strings. The next $$$n$$$ lines contain the given strings. The number of letters in each string is from $$$1$$$ to $$$100$$$, inclusive. Each string consists of lowercase English letters. Some strings might be equal.

If it is impossible to reorder $$$n$$$ given strings in required order, print "NO" (without quotes). Otherwise print "YES" (without quotes) and $$$n$$$ given strings in required order.

NoteIn the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba".

var n = parseInt(readline());

input = [];

for(var i = 0; i < n; i++){
    input.push(readline());
}

input.sort(function(a, b) {
    return a.length - b.length;
});

solve(input);

function solve(input) {
    for(var i = 0; i < input.length - 1; i++) {
        if(input[i+1].search(input[i]) == -1) {
            print("NO");
            return;
        }
    }

    print("YES");
    for(var i = 0 ;i < input.length;i ++) {
        print(input[i]);
    }
}

var g = readline();
var strs = [];
for(var i =0;i<g;i++){
    strs.push(readline());
}

strs = strs.sort(function(a, b){
    return a.length - b.length;
})

var flag = true;
for(i=0;i<strs.length;i++){
    var searchFlag =true;
    if(!searchFlag) break;
    for(b=i+1;b<strs.length;b++){
        if(strs[b].indexOf(strs[i]) == -1){
            flag =false;
            searchFlag = false;
            break;
        }
    }
}

if(flag){
    print("YES");
    for(var i=0;i<strs.length;i++){
        print(strs[i]);
    }
}else
print("NO");

  var n = parseInt(readline());
  var s = [];
  for(var i = 0; i < n; i += 1) {
    s[i] = readline();
  }
  var g = [];
  for(var i = 0; i < n; i += 1) {
    g[i] = [];
  }
  for(var i = 0; i < n; i += 1) {
    for(var j = i; j < n; j += 1) {
      if(s[i].includes(s[j]) && s[i] !== s[j]) {
        g[i][j] = 1;
      } else {
        g[i][j] = 0;
      }
      if(s[j].includes(s[i]) && s[i] !== s[j]) {
        g[j][i] = 1;
      } else {
        g[j][i] = 0;
      }
    }
    g[i][i] = 0;
  }
  var d = [];
  var q = [];
  for(var i = 0; i < n; i += 1) {
    d[i] = 0;
    for(var j = 0; j < n; j += 1) {
      if(g[j][i] === 1) {
        d[i] += 1;
      }
    }
    if(d[i] === 0) {
      q.push(i);
    }
  }
  var res = [];
  while(q.length > 0) {
    var v = q.pop();
    res.push(v);
    for(var i = 0; i < n; i += 1) {
      if(g[v][i] === 1) {
        g[v][i] = 0;
        d[i] -= 1;
        if(d[i] === 0) {
          q.push(i);
        }
      }
    }
  }
  var flag = true;
  for(var i = 0; i < n && flag; i += 1) {
    for(var j = 0; j < n && flag; j += 1) {
      if(g[i][j] === 1) {
        flag = false;
      }
    }
  }

  for(var i = 0; i < n && flag; i += 1) {
    for(var j = i; j < n && flag; j += 1) {
      if(!s[res[i]].includes(s[res[j]])) {
        flag = false;
      }
    }
  }

  if(flag) {
    print('YES');
    print(res.reverse().map(function(x) { return s[x]; }).join('\n'));
  } else {
    print('NO');
  }

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString='';
let currentLine=0;
process.stdin.on('data',inputStdin=>{
    inputString+=inputStdin;
});
process.stdin.on('end',_=>{
    inputString=inputString.trim().split("\n").map(string=>{
        return string.trim();
    });
    main();
});
function readLine()
{
    return inputString[currentLine++];
}
function main()
{
    const N=parseInt(readLine());
    let s=[];
    for(let i=0;i<N;++i)
    {
        s.push(readLine().trim());
    }
    s.sort((a,b)=>a.length-b.length);
    let prev=s[0];
    for(let i=1;i<N;++i)
    {
        if(prev.length==s[i].length)
        {
            if(prev!=s[i])
            {
                console.log("NO");
                return;
            }
        }
        else
        {
            if(!s[i].includes(prev))
            {
                console.log("NO");
                return;
            }
        }
        prev=s[i];
    }
    console.log("YES");
    for(let i=0;i<N;++i)
    {
        console.log(s[i]);
    }
}


Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.

The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).

If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).

NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 > ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.

function gao()
{
    var all = 'abcdefghijklmnopqrstuvwxyz';
    var numbers = readline().split(' ');
	var str = readline();
	var n = parseInt(numbers[0]);
	var m = parseInt(numbers[1]);

	var aNum = new Array();
	for(var i=0;i<str.length;i++)
	{
	    aNum[i] = all.indexOf(str.charAt(i));
	}

//	for(var i=0;i<str.length;i++){ print(aNum[i]);}

	var result = 'NO';
	var ok = 0;

	for(var i=n-1;i>=0;i--)
	{
	    while(aNum[i]<m-1)
		{
			aNum[i]++;
			if(aNum[i]!=aNum[i-1] && aNum[i]!=aNum[i-2])
			{
				ok = 1;
				break;
			}
		}

		if(ok == 1)
		{
		    for(var j = i+1; j<n; j++)
			{
			    for(var k=0;k<m;k++)
				{
				    if(k!=aNum[j-1]&&k!=aNum[j-2])
					{
					    aNum[j] = k;
						break;
					}
				}
			}
		    break;
		}
	}
	if(ok == 1)
	{
	    var result = "";
		for(var i=0;i<n;i++)
		{
		    result = result+all.charAt(aNum[i]);
		}
	}
	print(result);

}

gao();


You are given an array $$$a$$$ of length $$$n$$$ and array $$$b$$$ of length $$$m$$$ both consisting of only integers $$$0$$$ and $$$1$$$. Consider a matrix $$$c$$$ of size $$$n \times m$$$ formed by following rule: $$$c_{i, j} = a_i \cdot b_j$$$ (i.e. $$$a_i$$$ multiplied by $$$b_j$$$). It's easy to see that $$$c$$$ consists of only zeroes and ones too.How many subrectangles of size (area) $$$k$$$ consisting only of ones are there in $$$c$$$?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers $$$x_1, x_2, y_1, y_2$$$ ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le m$$$) a subrectangle $$$c[x_1 \dots x_2][y_1 \dots y_2]$$$ is an intersection of the rows $$$x_1, x_1+1, x_1+2, \dots, x_2$$$ and the columns $$$y_1, y_1+1, y_1+2, \dots, y_2$$$.The size (area) of a subrectangle is the total number of cells in it.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 40\,000, 1 \leq k \leq n \cdot m$$$), length of array $$$a$$$, length of array $$$b$$$ and required size of subrectangles. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 1$$$), elements of $$$a$$$. The third line contains $$$m$$$ integers $$$b_1, b_2, \ldots, b_m$$$ ($$$0 \leq b_i \leq 1$$$), elements of $$$b$$$.

Output single integer — the number of subrectangles of $$$c$$$ with size (area) $$$k$$$ consisting only of ones.

NoteIn first example matrix $$$c$$$ is:  There are $$$4$$$ subrectangles of size $$$2$$$ consisting of only ones in it:  In second example matrix $$$c$$$ is:

function solv() {
    var ip = readline().split(' ').map(x => parseInt(x))

    var x = ip[0]
    var y = ip[1]
    var pp = ip[2]

    var s = readline().split(' ').map(x => parseInt(x))
    var z = readline().split(' ').map(x => parseInt(x))

    var precZ = {}
    var ct = 0
    for (n = 0; n < y; n++) {
        if (z[n]) ct++;
        else {
            if (precZ[ct] == null) precZ[ct] = 1;
            else precZ[ct] += 1;
            ct = 0;
        }
    }
    if (ct) {
        if (precZ[ct] == null) precZ[ct] = 1;
        else precZ[ct] += 1;
    }

    ct = 0
    var segsZ = JSON.parse(JSON.stringify(precZ))
    var propz = []
    for (var n in precZ) {
        propz.push([n * 1, precZ[n]])
    }
    propz.sort((a, b) => {
        return b[0] - a[0]
    })

    for (var n = 0; n < propz.length; n++) {
        for (var k = propz[n][0] - 1; k >= 1; k--) {
            segsZ[k] = segsZ[k] == null ? (propz[n][0] - k + 1) * propz[n][1] : segsZ[k] + (propz[n][0] - k + 1) * propz[n][1];
        }
    }

    var precS = {}
    ct = 0
    for (var n = 0; n < x; n++) {
        if (s[n]) ct++;
        else {
            if (precS[ct] == null) precS[ct] = 1;
            else precS[ct] += 1;
            ct = 0;
        }
    }
    if (ct) {
        if (precS[ct] == null) precS[ct] = 1;
        else precS[ct] += 1;
    }

    ct = 0
    var segsS = JSON.parse(JSON.stringify(precS))
    var props = []
    for (var n in precS) {
        props.push([n * 1, precS[n]])
    }
    props.sort((a, b) => {
        return b[0] - a[0]
    })

    for (var n = 0; n < props.length; n++) {
        for (var k = props[n][0] - 1; k >= 1; k--) {
            segsS[k] = segsS[k] == null ? (props[n][0] - k + 1) * props[n][1] : segsS[k] + (props[n][0] - k + 1) * props[n][1];
        }
    }

    var res = 0;

    for (var n = 1; n * n <= pp; n++) {
        if (pp % n == 0 && n * n != pp) {
            res += (segsS[n] == null ? 0 : segsS[n]) * (segsZ[pp / n] == null ? 0 : segsZ[pp / n])
            res += (segsZ[n] == null ? 0 : segsZ[n]) * (segsS[pp / n] == null ? 0 : segsS[pp / n])
        }
        else res += (segsS[n] == null ? 0 : segsS[n]) * (segsZ[pp / n] == null ? 0 : segsZ[pp / n])
    }

    print(res)
}

var tc = 1;
//tc = parseInt(readline());
while (tc--) solv()

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

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

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

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a) {
  return parseInt(a[ptr++])
}

function readString(a) {
  return a[ptr++]
}

function readStrings(a) {
  return a[ptr++].split(' ')
}

function readInts(a) {
  return a[ptr++].split(' ').map(a => parseInt(a))
}

function main(input) {
  const [n, m, k] = readInts(input)
  const a = readInts(input)
  const b = readInts(input)
  const aS = seg(a)
  const bS = seg(b)
  let ans = 0
  for(let i = 1, len = aS.length; i < len; i++) {
    if(k % i === 0 && k / i <= m) {
      ans += aS[i] * bS[k / i]
    }
  }
  wr(ans)
}

function seg(a) {
  let i = 0
  const n = a.length
  const map = new Array(n + 1).fill(0)
  while(i < n) {
    if(a[i] === 0) {
      i++
      continue
    }
    let j = i
    while(j < n && a[j] === 1) j++
    for(let k = j - i; k >= 1; k--) map[k] += j - i - k + 1
    i = j
  }
  return map
}

const factors = (A) => {
  var output = [];

  for (var i=1; i <= Math.sqrt(A); i++) {
    if (A % i === 0) {
      output.push(i);

      if (i !== Math.sqrt(A)) output.push(A/i);
    }
  }

  if (output.indexOf(A) === -1) output.push(A);

  return output;
}

const processData = (lines) => {
  const [n, m, k] = lines[0].split(' ').map(x => +x)
  const a = lines[1].split(' ').map(x => +x)
  const b = lines[2].split(' ').map(x => +x)

  const aNums = []
  let acc = 0
  for (const num of a) {
    if (num === 0) {
      if (acc > 0) {
        aNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }

  if (acc>0) {
    aNums.push(acc)
  }

  // console.log(a)
  // console.log(aNums)

  const bNums = []
  acc = 0
  for (const num of b) {
    if (num === 0) {
      if (acc > 0) {
        bNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }
  if (acc>0) {
    bNums.push(acc)
  }

  let sum = 0

  const aRed = aNums.sort((a, b) => a - b).reduce((r, x) => {
    const last = r[r.length-1]
    if (x === last[0]) {
      last[1]++
    } else {
      r.push([x, 1])
    }
    return r
  }, [[1, 0]])

  const bRed = bNums.sort((a, b) => a - b).reduce((r, x) => {
    const last = r[r.length-1]
    if (x === last[0]) {
      last[1]++
    } else {
      r.push([x, 1])
    }
    return r
  }, [[1, 0]])

  const f = factors(k)

  for (const [x, xCount] of aRed) {
    for (const [y, yCount] of bRed) {
      const s = x*y
      // console.log([x, y])
      if (s >= k) {

        for (const t1 of f) {

          const t2 = k / t1
          // console.log(t1, t2)
          if (t1 <= x && t2 <= y) {
            // console.log(t1, t2)
            // console.log(x-t1+1, y-t2+1)
            sum += (x-t1+1) * (y-t2+1) * xCount * yCount
          }
        }
      }
    }
  }

  // console.log(hashMap)

  // for (const key in hashMap) {
  //   const [x, y] = key.split('_').map(x => +x)
  //   // console.log(k, x, y)
  //   let localSum = 0

  //   // console.log(localSum)
  //   // console.log(hashMap[key])
  //   sum = localSum * hashMap[key]
  // }

  console.log(sum)
}

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

const factors = (A) => {
  var output = [];

  for (var i=1; i <= Math.sqrt(A); i++) {
    if (A % i === 0) {
      output.push(i);

      if (i !== Math.sqrt(A)) output.push(A/i);
    }
  }

  if (output.indexOf(A) === -1) output.push(A);

  return output;
}

const processData = (lines) => {
  const [n, m, k] = lines[0].split(' ').map(x => +x)
  const a = lines[1].split(' ').map(x => +x)
  const b = lines[2].split(' ').map(x => +x)

  const aNums = []
  let acc = 0
  for (const num of a) {
    if (num === 0) {
      if (acc > 0) {
        aNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }

  if (acc>0) {
    aNums.push(acc)
  }

  // console.log(a)
  // console.log(aNums)

  const bNums = []
  acc = 0
  for (const num of b) {
    if (num === 0) {
      if (acc > 0) {
        bNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }
  if (acc>0) {
    bNums.push(acc)
  }

  let sum = 0
  //
  // const aRed = aNums.sort((a, b) => a - b).reduce((r, x) => {
  //   const last = r[r.length-1]
  //   if (x === last[0]) {
  //     last[1]++
  //   } else {
  //     r.push([x, 1])
  //   }
  //   return r
  // }, [[1, 0]])
  //
  // const bRed = bNums.sort((a, b) => a - b).reduce((r, x) => {
  //   const last = r[r.length-1]
  //   if (x === last[0]) {
  //     last[1]++
  //   } else {
  //     r.push([x, 1])
  //   }
  //   return r
  // }, [[1, 0]])

  const f = factors(k).sort((a, b) => a-b)

  for (const t1 of f) {
    const t2 = k / t1
    const aWidth = aNums.reduce( (r, x) => r + (x >= t1 ? (x - t1 + 1 ) : 0), 0)
    const bWidth = bNums.reduce( (r, y) => r + (y >= t2 ? (y - t2 + 1 ) : 0), 0)
    sum += aWidth * bWidth
  }

  console.log(sum)
}

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

const factors = (A) => {
  var output = [];

  for (var i=1; i <= Math.sqrt(A); i++) {
    if (A % i === 0) {
      output.push(i);

      if (i !== Math.sqrt(A)) output.push(A/i);
    }
  }

  if (output.indexOf(A) === -1) output.push(A);

  return output;
}

const processData = (lines) => {
  const [n, m, k] = lines[0].split(' ').map(x => +x)
  const a = lines[1].split(' ').map(x => +x)
  const b = lines[2].split(' ').map(x => +x)

  const aNums = []
  let acc = 0
  for (const num of a) {
    if (num === 0) {
      if (acc > 0) {
        aNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }

  if (acc>0) {
    aNums.push(acc)
  }

  // console.log(a)
  // console.log(aNums)

  const bNums = []
  acc = 0
  for (const num of b) {
    if (num === 0) {
      if (acc > 0) {
        bNums.push(acc)
        acc = 0
      }
    } else {
      acc++
    }
  }
  if (acc>0) {
    bNums.push(acc)
  }

  let sum = 0

  const aRed = aNums.sort((a, b) => a - b).reduce((r, x) => {
    const last = r[r.length-1]
    if (x === last[0]) {
      last[1]++
    } else {
      r.push([x, 1])
    }
    return r
  }, [[1, 0]])

  const bRed = bNums.sort((a, b) => a - b).reduce((r, x) => {
    const last = r[r.length-1]
    if (x === last[0]) {
      last[1]++
    } else {
      r.push([x, 1])
    }
    return r
  }, [[1, 0]])

  const f = factors(k).sort((a, b) => a-b)

  for (const t1 of f) {
    const t2 = k / t1
    const aWidth = aRed.reduce( (r, [x, c]) => r + (x >= t1 ? (x - t1 + 1 ) * c : 0), 0)
    const bWidth = bRed.reduce( (r, [y, c]) => r + (y >= t2 ? (y - t2 + 1 ) * c : 0), 0)
    sum += aWidth * bWidth
  }

  console.log(sum)
}

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

const init = () => {
  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();
  });

  global.readline = () => {
    return inputString[currentLine++];
  }
};

if (typeof readline === 'undefined') {
  init();
}

const print = (...args) => {
  console.log(...args);
};

const getFactors = (n) => {
  const result = new Set();
  for (let i = 1; i <= parseInt(n ** (1/2)); i++) {
    if (n % i === 0) {
      result.add(i);
      result.add(n / i);
    }
  }
  // print(result)
  return Array.from(result);
};

const getChunks = (arr) => {
  const result = {};
  let left = 0;
  arr.concat(0).forEach((x, i) => {
    if (x === 0) {
      result[i - left] = (result[i - left] || 0) + 1;
      left = i + 1;
    }
  })
  return result;
};

const main = () => {
  const [n, m, k] = readline().split(' ').map(x => parseInt(x));
  const a = readline().split(' ').map(x => parseInt(x));
  const b = readline().split(' ').map(x => parseInt(x));

  const factors = getFactors(k);
  const solve = (n, m) => {
    let cnt = 0;
    for (let i = 0; i < factors.length; i++) {
      const a = factors[i];
      const b = k / factors[i];
      if (n >= a && m >= b) cnt += (n - a + 1) * (m - b + 1);
    }
    return cnt
  };

  const note = new Map();

  let cnt = 0;
  const a_chunks = getChunks(a);
  const b_chunks = getChunks(b);
  for (const x in a_chunks) {
    for (const y in b_chunks) {
      const key = [x, y].join(',');
      const cached = note.get(key);
      if (cached !== undefined) {
        cnt += cached * a_chunks[x] * b_chunks[y];
      } else {
        const calc = solve(x, y);
        cnt += calc * a_chunks[x] * b_chunks[y];
        note.set(key, calc);
      }
    }
  }
  // print(note)
  // print(factors);
  // print(a_chunks, b_chunks);
  print(cnt);
};

const gets = (() => {
  const lines = [];

  require("readline")
    .createInterface({
      input: process.stdin,
      output: process.stdout
    })
    .on("line", line => {
      if (lines.length > 0 && typeof lines[0] === "function") {
        lines.shift()(line);
      } else {
        lines.push(line);
      }
    });

  return async () => {
    if (lines.length > 0 && typeof lines[0] === "string") {
      return lines.shift();
    }
    return new Promise(resolve => lines.push(resolve));
  };
})();

const get_nums = async () => (await gets()).split(" ").map(x => Number(x));

function build(a) {
  const n = a.length;
  const s = new Array(n + 1);
  s.fill(0);
  let c = 0;
  for (let i = 0; i < n; i++) {
    if (a[i] === 0) {
      c = 0;
    } else {
      c++;
      s[c]++;
    }
  }
  for (let i = n - 1; i >= 0; i--) {
    s[i] += s[i + 1];
  }
  return s;
}

async function main() {
  const [n, m, k] = await get_nums();
  const a = await get_nums();
  const b = await get_nums();
  const sa = build(a);
  const sb = build(b);
  const calc = (w, h) => w <= n && h <= m ? sa[w] * sb[h] : 0;

  let ans = 0;
  for (let i = 1; i * i <= k; i++) {
    if (k % i !== 0) {
      continue;
    }
    ans += calc(i, k / i);
    if (i !== k / i) {
      ans += calc(k / i, i);
    }
  }
  console.log(ans);
}

main();

var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
function main(raw) {
    var lines = raw.trim().split("\n").map(function (l) { return l.split(" ").map(function (u) { return parseInt(u, 10); }); });
    var _a = __read(lines.shift(), 3), n = _a[0], m = _a[1], k = _a[2];
    var as = lines.shift();
    var bs = lines.shift();
    // let [n, m, k] = [40000, 40000, Math.ceil(Math.random() * 10) * 2];
    // const as = Array.from({ length: n }, (_, i) => i % 2);
    // const bs = Array.from({ length: n }, () => Math.round(Math.random()));
    var count = 0;
    var awhs = new Map();
    ;
    for (var i = 0; i < n; i++) {
        var w = 0;
        while (as[i] === 1 && i < n) {
            i++;
            w++;
        }
        if (w > 0) {
            if (!awhs.has(w)) {
                awhs.set(w, 1);
            }
            else {
                awhs.set(w, awhs.get(w) + 1);
            }
        }
    }
    var _loop_1 = function (j) {
        var h = 0;
        while (bs[j] === 1 && j < m) {
            h++;
            j++;
        }
        if (h > 0) {
            __spread(awhs.entries()).forEach(function (_a) {
                var _b = __read(_a, 2), w = _b[0], t = _b[1];
                // console.log(w, t);
                count += t * countsubRets(w, h, k);
            });
        }
        out_j_1 = j;
    };
    var out_j_1;
    for (var j = 0; j < m; j++) {
        _loop_1(j);
        j = out_j_1;
    }
    console.log(count);
}
var dp = {};
function countsubRets(w, h, k) {
    // if(w * h in dp) {
    //     return dp[w * h];
    // }
    var cnt = 0;
    for (var pw = 1; pw <= w && pw <= k; pw++) {
        // console.log(pw, w, h, k);
        if (k % pw === 0) {
            var desiredH = k / pw;
            if (desiredH <= h) {
                var horz = w - pw + 1;
                var vert = h - desiredH + 1;
                cnt += horz * vert;
            }
        }
    }
    // console.log(cnt);
    // dp[w * h] = cnt;
    return cnt;
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();

const factors = (A) => {
  var output = [];

  for (var i=1; i <= Math.sqrt(A); i++) {
    if (A % i === 0) {
      output.push(i);

      if (i !== Math.sqrt(A)) output.push(A/i);
    }
  }

  if (output.indexOf(A) === -1) output.push(A);

  return output;
}

const processData = (lines) => {
  const [n, m, k] = lines[0].split(' ').map(x => +x)
  const a = lines[1].split(' ').map(x => +x)
  const b = lines[2].split(' ').map(x => +x)

  const aNums = []
  let acc = 0
  for (const num of a) {
    if (num === 0 && acc > 0) {
      aNums.push(acc)
      acc = 0
    } else {
      acc++
    }
  }
  if (acc>0) {
    aNums.push(acc)
  }
  const bNums = []
  acc = 0
  for (const num of b) {
    if (num === 0 && acc > 0) {
      bNums.push(acc)
      acc = 0
    } else {
      acc++
    }
  }
  if (acc>0) {
    bNums.push(acc)
  }

  const sizeArr = []
  for (const num of aNums) {
    for (const bNum of bNums) {
      const s = num * bNum
      if (s >= k) {
        sizeArr.push([num, bNum])
      }
    }
  }
  let sum = 0
  const f =  factors(k).sort((a, b) => a-b)

  for (const [x, y] of sizeArr) {
    // let t1 = 1
    // let t2 = f.reduce((r,x) => r*x, 1)
    for (let j = 0; j < f.length; j++) {

      const t1 = f[j]
      const t2 = k / f[j]
      // console.log(t1, t2)
      if (t1 <= x && t2 <= y) {
        // console.log(t1, t2)
        // console.log(x-t1+1, y-t2+1)
        sum += (x-t1+1) * (y-t2+1)
      }
    }
  }
  console.log(sum)
}

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

var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
function main(raw) {
    var lines = raw.trim().split("\n").map(function (l) { return l.split(" ").map(function (u) { return parseInt(u, 10); }); });
    var _a = __read(lines.shift(), 3), n = _a[0], m = _a[1], k = _a[2];
    var as = lines.shift();
    var bs = lines.shift();
    // let [n, m, k] = [40000, 40000, 2];
    // const as = Array.from({ length: n }, (_, i) => i % 3);
    // const bs = Array.from({ length: n }, () => Math.round(Math.random()));
    var count = 0;
    var awhs = new Map();
    ;
    for (var i = 0; i < n; i++) {
        var w = 0;
        while (as[i] === 1 && i < n) {
            i++;
            w++;
        }
        if (w > 0) {
            if (!awhs.has(w)) {
                awhs.set(w, 1);
            }
            else {
                awhs.set(w, awhs.get(w) + 1);
            }
        }
    }
    var _loop_1 = function (j) {
        var h = 0;
        while (bs[j] === 1 && j < m) {
            h++;
            j++;
        }
        if (h > 0) {
            __spread(awhs.entries()).forEach(function (_a) {
                var _b = __read(_a, 2), w = _b[0], t = _b[1];
                // console.log(w, t);
                count += t * countsubRets(w, h, k);
            });
        }
        out_j_1 = j;
    };
    var out_j_1;
    for (var j = 0; j < m; j++) {
        _loop_1(j);
        j = out_j_1;
    }
    console.log(count);
}
var dp = {};
function countsubRets(w, h, k) {
    if (w * h in dp) {
        return dp[w * h];
    }
    var cnt = 0;
    for (var pw = 1; pw <= w && pw <= k; pw++) {
        // console.log(pw, w, h, k);
        if (k % pw === 0) {
            var desiredH = k / pw;
            if (desiredH <= h) {
                var horz = w - pw + 1;
                var vert = h - desiredH + 1;
                cnt += horz * vert;
            }
        }
    }
    // console.log(cnt);
    dp[w * h] = cnt;
    return cnt;
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();


Ujan decided to make a new wooden roof for the house. He has $$$n$$$ rectangular planks numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th plank has size $$$a_i \times 1$$$ (that is, the width is $$$1$$$ and the height is $$$a_i$$$).Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.For example, if Ujan had planks with lengths $$$4$$$, $$$3$$$, $$$1$$$, $$$4$$$ and $$$5$$$, he could choose planks with lengths $$$4$$$, $$$3$$$ and $$$5$$$. Then he can cut out a $$$3 \times 3$$$ square, which is the maximum possible. Note that this is not the only way he can obtain a $$$3 \times 3$$$ square.  What is the maximum side length of the square Ujan can get?

The first line of input contains a single integer $$$k$$$ ($$$1 \leq k \leq 10$$$), the number of test cases in the input. For each test case, the first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 1\,000$$$), the number of planks Ujan has in store. The next line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$), the lengths of the planks.

For each of the test cases, output a single integer, the maximum possible side length of the square.

NoteThe first sample corresponds to the example in the statement.In the second sample, gluing all $$$4$$$ planks will result in a $$$4 \times 4$$$ square.In the third sample, the maximum possible square is $$$1 \times 1$$$ and can be taken simply as any of the planks.

'use strict'

const problem = (n, a) => {
    a = a.sort((x, y) => y - x);
    for (let i = 0; i < a.length; i++) {
        if (a[i] <= i) return i;
    }
    return a.length;
}
let q = +readline();
while(q--) print(problem(+readline(), readline().split(' ').map(Number)))

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

function solve(arr){
	arr.sort((a,b) => b-a);
	let min = 0;
	for (const el of arr) {
		min++;
		if(el<min){
			min--;
			break;
		}
	}
	return min;
}

function solveWrap(input) {
    let inputAr = input.trim().split('\n');
	let k = inputAr.shift();
	for (let i = 0; i < k; i++) {
		inputAr.shift();
		console.log(solve(inputAr.shift().split(' ').map((el) => +el)));
	}
}

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

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var list = nextIntArray();
    list.sort(function(a,b){
    	return b - a;
    });
    var max = 0;
    for(var j = 0; j < N; j++){
      if(j + 1 <= list[j]){
        max = j + 1;
      }else{
        break;
      }
      output[i] = max;
    }
  }
  myout(myconv(output, 9));
}

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

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

  if (c % 2 === 1) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  const obj = {};
  const uniqArr = [...new Set(arr)];

  for (let i = 0; i < uniqArr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (uniqArr[i] <= arr[j]) {
        if (!obj[uniqArr[i]]) {
          obj[uniqArr[i]] = 1;
        }
        else {
          obj[uniqArr[i]]++;
        }
      }
    }
  }

  let ans = 0;

  for (x in obj) {
    const target = Math.min(x, obj[x]);
    ans = Math.max(target, ans);
  }

  console.log(ans);

  c++;
});

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

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

let nl = nextLine();

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

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

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

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

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

const sol = () => {
	let t = nl.num();
  let ans = [];
  for(let i = 0; i < t; i++){
    let n = nl.num();
    let a = nl.nums();
    a.sort((x, y) => y - x);
    let flag = true;
    for(let j = 0; j < n; j++){
      if (a[j] <= j) {
        ans.push(j);
        flag = false;
        break;
      }
    }
    if (flag) {
      ans.push(n);
    }
  }
	console.log(ans.join('\n'));

};

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


Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer — a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has n students. Dean's office allows i-th student to use the segment (li, ri) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students!Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (n - 1) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.

The first line contains a positive integer n (1 ≤ n ≤ 100). The (i + 1)-th line contains integers li and ri (0 ≤ li < ri ≤ 100) — the endpoints of the corresponding segment for the i-th student.

On a single line print a single number k, equal to the sum of lengths of the parts of the dryer which are inside Alexey's segment and are outside all other segments.

NoteNote that it's not important are clothes drying on the touching segments (e.g. (0, 1) and (1, 2)) considered to be touching or not because you need to find the length of segments.In the first test sample Alexey may use the only segment (0, 1). In such case his clothes will not touch clothes on the segments (1, 6) and (2, 8). The length of segment (0, 1) is 1.In the second test sample Alexey may dry his clothes on segments (0, 1) and (5, 7). Overall length of these segments is 3.

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

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

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function main() {
	var endpointNum = parseInt(readline());
	var used = new Array(100);

	var alexeyEndpoints = tokenizeIntegers(readline());

	for (var i = 1; i < endpointNum; ++i) {
		var endpoints = tokenizeIntegers(readline());
		for (var j = endpoints[0]; j < endpoints[1]; ++j) {
			used[j] = true;
		}
	}

	var count = 0;
	for (var i = alexeyEndpoints[0]; i < alexeyEndpoints[1]; ++i) {
		if (!used[i]) {
			count += 1;
		}
	}

	print(count);
}

main();


You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:  the Power Gem of purple color,  the Time Gem of green color,  the Space Gem of blue color,  the Soul Gem of orange color,  the Reality Gem of red color,  the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.

In the first line of input there is one integer $$$n$$$ ($$$0 \le n \le 6$$$) — the number of Gems in Infinity Gauntlet. In next $$$n$$$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.

In the first line output one integer $$$m$$$ ($$$0 \le m \le 6$$$) — the number of absent Gems. Then in $$$m$$$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.

NoteIn the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.In the second sample Thanos doesn't have any Gems, so he needs all six.

var g = {
    'purple': 'Power',
    'green': 'Time',
    'blue': 'Space',
    'orange': 'Soul',
    'red': 'Reality',
    'yellow': 'Mind',
};
var n = parseInt(readline());
while(n--){
    x = readline();
    delete g[x];
}
print(Object.keys(g).length)
Object.keys(g).forEach((e)=>{
    print(g[e]);
})

function answer(input){
    var stones = {
        purple: 'Power',
        green: 'Time',
        blue: 'Space',
        orange: 'Soul',
        red: 'Reality',
        yellow: 'Mind'
    };

    var numStones = readline();
    var inputStones = [];
    var outputStones = [];

    for(var i = 0; i < numStones; i++){
        inputStones.push(readline());
    }

    inputStones.forEach(function(stoneColor){
        delete stones[stoneColor];
    });

    for(var stoneColor in stones){
        outputStones.push(stones[stoneColor]);
    }
    print(outputStones.length);
    outputStones.forEach(function(stone){
        print(stone);
    });
}

answer();

var n = Number(readline());
const map = {
  purple: "Power",
  green: "Time",
  blue: "Space",
  orange: "Soul",
  red: "Reality",
  yellow: "Mind"
};
const colors = new Set(Object.keys(map));
while (n--)
  colors.delete(readline().trim());
print(colors.size);
for (var color of colors)
  print(map[color]);

var n = readline().split(" ").map(function(x) { return parseInt(x); });
var s = ""
var obj = {}
for(var i = 0; i < n; i++){
    s = readline()
    switch(s){
        case "purple":
            obj.Power = 1
            break
        case "green":
            obj.Time = 1
            break
        case "blue":
            obj.Space = 1
            break
        case "orange":
            obj.Soul = 1
            break
        case "red":
            obj.Reality = 1
            break
        case "yellow":
            obj.Mind = 1
            break
    }
}
var ans = 0
var ansarr = []
if(!obj.hasOwnProperty("Power")){
    ans += 1
    ansarr.push("Power")
}
if(!obj.hasOwnProperty("Time")){
    ans += 1
    ansarr.push("Time")
}
if(!obj.hasOwnProperty("Space")){
    ans += 1
    ansarr.push("Space")
}
if(!obj.hasOwnProperty("Soul")){
    ans += 1
    ansarr.push("Soul")
}
if(!obj.hasOwnProperty("Reality")){
    ans += 1
    ansarr.push("Reality")
}
if(!obj.hasOwnProperty("Mind")){
    ans += 1
    ansarr.push("Mind")
}
print(ans)
for(var j = 0; j < ansarr.length; j++){
    print(ansarr[j])
}
    // the Power Gem of purple color,
    // the Time Gem of green color,
    // the Space Gem of blue color,
    // the Soul Gem of orange color,
    // the Reality Gem of red color,
    // the Mind Gem of yellow color.

// 2
// Time
// Space

var col2gem = {
    purple: "Power",
    green: "Time",
    blue: "Space",
    orange: "Soul",
    red: "Reality",
    yellow: "Mind",
};

var n = readline();

var seen = new Set();

for (var i = 0; i < n; i++) {
    seen.add(readline());
}

print(6 - n);

for (var col in col2gem) {
    if (!seen.has(col)) {
        print(col2gem[col]);
    }
}

// //The colors of the six gems
var gems = [
    { name: 'Power',    color: 'purple' },
    { name: 'Time',     color: 'green' },
    { name: 'Space',    color: 'blue' },
    { name: 'Soul',     color: 'orange' },
    { name: 'Reality',  color: 'red' },
    { name: 'Mind',     color: 'yellow' }
]
//the number of Gems in Infinity Gauntlet.
var n = readline();
// var n = prompt();
var colors = [];
if ((n > 0 || n == 0) && (n < 6 || n == 6)) {
    for (i = 0; i < n; i++) {
        colors.push(readline())
        // colors.push(prompt())
    }
}
var absent=gems.filter(function(gem){
    return (colors.indexOf(gem.color) == -1);
})
var m=absent.length
print(m)
// console.log(m)
// console.log(colors)
print(...absent.map(absent=>absent.name))
// console.log(...absent.map(absent=>absent.name))

var names = ["purple","green","blue","orange","red","yellow"];
var powers = ["Power","Time","Space","Soul","Reality","Mind"];

var number = +readline();
while(number > 0) {
    powers[names.indexOf(readline())] = 0;
    number --;
}

var results = powers.filter(power => power);
write(results.length + '\n');
results.forEach(result => write(result + '\n'))

  var n = parseInt(readline());
  var m = [];
  m['purple'] = 'Power';
  m['green'] = 'Time';
  m['blue'] = 'Space';
  m['orange'] = 'Soul';
  m['red'] = 'Reality';
  m['yellow'] = 'Mind';
  for(var i = 0; i < n; i += 1) {
    var tmp = readline();
    m[tmp] = '';
  }
  var res = '';
  var count = 0;
  for(var c in m) {
    if(m[c].length > 0) {
      res += m[c] + '\n';
      count += 1;
    }
  }
  print(count);
  print(res);

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

//Don't have to see. end------------------------------------------
function Main(){
	var map = {
		purple : "Power",
		green : "Time",
		blue : "Space",
		orange : "Soul",
		red : "Reality",
		yellow : "Mind"
	};
	var N = nextInt();
	for(var i = 0; i < N; i++){
		map[next()] = "";
	}
	var keys = Object.keys(map);
	var output = [];
	for(var i = 0; i < keys.length; i++){
		if(map[keys[i]] != ""){
			output.push(map[keys[i]]);
		}
	}
	myout(output.length);
	myout(myconv(output, 9));
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
const arr = [];
const obj = {
  purple: 'Power',
  green: 'Time',
  blue: 'Space',
  orange: 'Soul',
  red: 'Reality',
  yellow: 'Mind',
};

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

  delete obj[str];

  c++;
});

rl.on('close', () => {
  const ans = Object.values(obj);

  console.log(ans.length);
  for (let i = 0; i < ans.length; i++) {
    console.log(ans[i]);
  }
});

let input = [];

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

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

RL.on('close', () => {
    let n = parseInt(input[0]);
    let data = {
        "red" : [0, 'Reality'],
        "purple": [0, 'Power'],
        "yellow": [0, 'Mind'],
        "orange": [0, 'Soul'],
        "blue": [0, 'Space'],
        "green": [0, 'Time'],
    }

    console.log(6-n);
    if(6-n > 0){
        for(let i = 1; i <= n; i++){
            data[input[i]][0] = 1;
        }

        for(elem in data){
            if(data[elem][0] == 0){
                console.log(data[elem][1]);
            }
        }
    }
});

// http://codeforces.com/contest/987/problem/A
// A. Перчатка бесконечности
'use strict';

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

const gauntletMap = {
  purple: 'Power',
  green: 'Time',
  blue: 'Space',
  orange: 'Soul',
  red: 'Reality',
  yellow: 'Mind',
};

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

rl.on('close', function () {
  for (let i = 1; i < input.length; i++) {
    delete gauntletMap[input[i]];
  }

  console.log(Object.getOwnPropertyNames(gauntletMap).length);
  for (let key in gauntletMap) {
    console.log(gauntletMap[key]);
  }
});

function answer(input){
    var stones = {
        purple: 'Power',
        green: 'Time',
        blue: 'Space',
        orange: 'Soul',
        red: 'Reality',
        yellow: 'Mind'
    };

    var numStones = readline();
    var inputStones = [];
    var outputStones = [];
    for(var i = 0; i < numStones; i++){
        inputStones.push(readline());
    }
    inputStones.forEach(function(stoneColor){
        delete stones[stoneColor];
    });
    for(var stoneColor in stones){
        outputStones.push(stoneColor[stoneColor]);
    }
    print(outputStones.length);
    outputStones.forEach(function(stone){
        print(stone);
    });
}

answer();

var col2gem = {
    purple: "Power",
    green: "Time",
    blue: "Space",
    orange: "Soul",
    red: "Reality",
    yellow: "Mind",
};

var n = readline();

var seen = new Set();

for (var i = 0; i < n; i++) {
    seen.add(readline());
}

for (var col in col2gem) {
    if (!seen.has(col)) {
        print(col2gem[col]);
    }
}

// //The colors of the six gems
var gems = [
    { name: 'Power',    color: 'purple' },
    { name: 'Time',     color: 'green' },
    { name: 'Space',    color: 'blue' },
    { name: 'Soul',     color: 'orange' },
    { name: 'Reality',  color: 'red' },
    { name: 'Mind',     color: 'yellow' }
]
//the number of Gems in Infinity Gauntlet.
var n = readline();
// var n = prompt();
var colors = [];
if ((n > 0 || n == 0) && (n < 6 || n == 6)) {
    for (i = 0; i < n; i++) {
        colors.push(readline())
        // colors.push(prompt())
    }
}
var absent=gems.filter(function(gem){
    return (colors.indexOf(gem.color) == -1);
})
var m=absent.length
print(m)
// console.log(m)
// console.log(colors)
print(absent.map(absent=>absent.name))
// console.log(absent.map(absent=>absent.name))

// //The colors of the six gems
var gems = [
    { name: 'Power',    color: 'purple' },
    { name: 'Time',     color: 'green' },
    { name: 'Space',    color: 'blue' },
    { name: 'Soul',     color: 'orange' },
    { name: 'Reality',  color: 'red' },
    { name: 'Mind',     color: 'yellow' }
]
//the number of Gems in Infinity Gauntlet.
var n = readline().split(' ');
var colors = [];
var color;
if ((n > 0 || n == 0) && (n < 6 || n == 6)) {
    for (i = 0; i < n; i++) {
        colors.push(readline()+"/n")
    }
}
var absent=gems.filter(function(gem){
    return (colors.indexOf(gem.color) == -1);
})
var m=absent.length
print(m)
print(absent.map(absent=>absent.name))

  var n = parseInt(readline());
  var m = [];
  m['purple'] = 'power';
  m['green'] = 'Time';
  m['blue'] = 'Space';
  m['orange'] = 'Soul';
  m['red'] = 'Reality';
  m['yellow'] = 'Mind';
  for(var i = 0; i < n; i += 1) {
    var tmp = readline();
    m[tmp] = '';
  }
  var res = '';
  var count = 0;
  for(var c in m) {
    if(m[c].length > 0) {
      res += m[c] + '\n';
      count += 1;
    }
  }
  print(count);
  print(res);


Consider a simplified penalty phase at the end of a football match.A penalty phase consists of at most $$$10$$$ kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (note that it goes against the usual football rules). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the $$$7$$$-th kick the first team has scored $$$1$$$ goal, and the second team has scored $$$3$$$ goals, the penalty phase ends — the first team cannot reach $$$3$$$ goals.You know which player will be taking each kick, so you have your predictions for each of the $$$10$$$ kicks. These predictions are represented by a string $$$s$$$ consisting of $$$10$$$ characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way:  if $$$s_i$$$ is 1, then the $$$i$$$-th kick will definitely score a goal;  if $$$s_i$$$ is 0, then the $$$i$$$-th kick definitely won't score a goal;  if $$$s_i$$$ is ?, then the $$$i$$$-th kick could go either way. Based on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that the referee doesn't take into account any predictions when deciding to stop the penalty phase — you may know that some kick will/won't be scored, but the referee doesn't.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1\,000$$$) — the number of test cases. Each test case is represented by one line containing the string $$$s$$$, consisting of exactly $$$10$$$ characters. Each character is either 1, 0, or ?.

For each test case, print one integer — the minimum possible number of kicks in the penalty phase.

NoteConsider the example test:In the first test case, consider the situation when the $$$1$$$-st, $$$5$$$-th and $$$7$$$-th kicks score goals, and kicks $$$2$$$, $$$3$$$, $$$4$$$ and $$$6$$$ are unsuccessful. Then the current number of goals for the first team is $$$3$$$, for the second team is $$$0$$$, and the referee sees that the second team can score at most $$$2$$$ goals in the remaining kicks. So the penalty phase can be stopped after the $$$7$$$-th kick.In the second test case, the penalty phase won't be stopped until all $$$10$$$ kicks are finished.In the third test case, if the first team doesn't score any of its three first kicks and the second team scores all of its three first kicks, then after the $$$6$$$-th kick, the first team has scored $$$0$$$ goals and the second team has scored $$$3$$$ goals, and the referee sees that the first team can score at most $$$2$$$ goals in the remaining kicks. So, the penalty phase can be stopped after the $$$6$$$-th kick.In the fourth test case, even though you can predict the whole penalty phase, the referee understands that the phase should be ended only after the $$$9$$$-th kick.

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let str = readline().trim();
    let ans = 9,
      cnt0 = 0,
      cnt1 = 0;
    for (let i = 0; i < 10; i++) {
      if ((i + 1) % 2 === 1) {
        if (str[i] !== "0") cnt0++;
      } else if (str[i] === "1") cnt1++;
      if (cnt0 > cnt1 + Math.floor((10 - i) / 2)) ans = Math.min(ans, i);
      if (cnt1 > cnt0 + Math.floor((9 - i) / 2)) ans = Math.min(ans, i);
    }
    cnt0 = 0;
    cnt1 = 0;
    for (let i = 0; i < 10; i++) {
      if ((i + 1) % 2 === 1) {
        if (str[i] === "1") cnt0++;
      } else if (str[i] !== "0") cnt1++;
      if (cnt0 > cnt1 + Math.floor((10 - i) / 2)) ans = Math.min(ans, i);
      if (cnt1 > cnt0 + Math.floor((9 - i) / 2)) ans = Math.min(ans, i);
    }
    console.log(ans + 1);
  }
};
solve();

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 () {
	let t = rn();
	while (t--) {
		let s = rl();

		const winscrt1 = [3, 3, 2, 2];
		const winscrt2 = [3, 2, 2, 1];

		let i, mx = [0, 0], mn = [0, 0];
		for (i = 0; i < 9; i++) {
			const team = i % 2;
			if (s[i] == 1) {
				mx[team]++;
				mn[team]++;
			}
			if (s[i] == '?') {
				mx[team]++;
			}

			let t1rel = mx[0] - mn[1];
			let t2rel = mx[1] - mn[0];

			if (t1rel == winscrt1[i - 5]) break;
			if (t2rel == winscrt2[i - 5]) break;
		}
		ans = i + 1;
		console.log(ans);
	}
}


In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor.To begin with friends learned the rules: in the race there are n sections of equal length and m participants. The participants numbered from 1 to m. About each participant the following is known: li — the number of the starting section,  ri — the number of the finishing section (li ≤ ri), ti — the time a biathlete needs to complete an section of the path, ci — the profit in roubles. If the i-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman. The i-th biathlete passes the sections from li to ri inclusive. The competitor runs the whole way in (ri - li + 1)·ti time units. It takes him exactly ti time units to pass each section. In case of the athlete's victory on k sections the man who has betted on him receives k·ci roubles.In each section the winner is determined independently as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed.We should also add that Nikita can bet on each section and on any contestant running in this section.Help the friends find the maximum possible profit.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). Then follow m lines, each containing 4 integers li, ri, ti, ci (1 ≤ li ≤ ri ≤ n, 1 ≤ ti, ci ≤ 1000).

Print a single integer, the maximal profit in roubles that the friends can get. In each of n sections it is not allowed to place bets on more than one sportsman.

NoteIn the first test the optimal bet is: in the 1-2 sections on biathlete 1, in section 3 on biathlete 3, in section 4 on biathlete 4. Total: profit of 5 rubles for 1 section, the profit of 5 rubles for 2 section, profit of 30 rubles for a 3 section, profit of 20 rubles for 4 section. Total profit 60 rubles.In the second test the optimal bet is: on 1 and 5 sections on biathlete 1, in the 2-4 sections on biathlete 2, in the 6-7 sections on athlete 4. There is no winner in the 8 section. Total: profit of 10 rubles for 1 section, the profit of 15 rubles for 2,3,4 section, profit of 10 rubles for a 5 section, profit of 20 rubles for 6, 7 section. Total profit 105 rubles.

var nm = readline().split(' ').map(Number);
var n = nm[0];
var m = nm[1];
var p = [];
var sum = 0;
for (var i=0; i<m; i++){
	var s = readline().split(' ').map(Number);
	p[i] = s;
}
for (var i=0; i<n; i++){
	var sum1 = 0;
	var t = 1100;
	for (var j=0; j<m; j++){
		if ( (i+1) >= p[j][0] && (i+1) <= p[j][1] ) {
			if (p[j][2] < t) {
				t = p[j][2];
				sum1 = p[j][3];
			}
		}
	}
	sum += sum1;
}
print (sum);

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  let [U] = ipt.split(EOL)[0].split(' ').map(v => parseInt(v))
  let B = ipt.split(EOL).slice(1, -1).map(l => l.split(' ').map(v => parseInt(v)))

  let s = 0
  for (let i = 1; i < U + 1; i++) {
    s += b(i)
  }

  console.log(s)

  function b (u) {
    let bt = Infinity
    let m = 0
    for (let i = 0; i < B.length; i++) {
      const [l, r, t, c] = B[i]
      if (u < l || u > r) continue
      if (t < bt) {
        bt = t
        m = c
      }
    }
    return m
  }
})