The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order:  She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$).  She collects all mushrooms on point $$$y$$$.  A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$, $$$1\le k \le 10^9$$$) — the number of positions with mushrooms and the time Marisa has, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial number of mushrooms on point $$$1,2,\ldots,n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$.

For each test case, print the maximum number of mushrooms Marisa can pick after $$$k$$$ minutes.

NoteTest case 1:Marisa can start at $$$x=2$$$. In the first minute, she moves to $$$x=1$$$ and collect $$$5$$$ mushrooms. The number of mushrooms will be $$$[1,7,2,3,4]$$$. In the second minute, she moves to $$$x=2$$$ and collects $$$7$$$ mushrooms. The numbers of mushrooms will be $$$[2,1,3,4,5]$$$. After $$$2$$$ minutes, Marisa collects $$$12$$$ mushrooms.It can be shown that it is impossible to collect more than $$$12$$$ mushrooms.Test case 2:This is one of her possible moving path:$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5$$$It can be shown that it is impossible to collect more than $$$37$$$ mushrooms.

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = [arr[0]]
    for (let i = 1; i < n; i++) {
        sum[i] = sum[i - 1] + arr[i]
    }
    // console.log(sum)
    if (k >= n) {
        // const t = Math.floor((k - 1) / (n - 1))
        // const r = k % (n - 1)
        return BigInt(sum[n - 1]) + mul(k - 1 + k - 1 - n + 1, n) / 2n
    } else {
        let max = 0
        for (let i = 0; i < n; i++) {
            const after = n - 1 - i + 1
            if (k <= after) {
                const now = range(i, i + k - 1)
                if (now > max) max = now
            }
            // console.log(now)
        }
        // 0, 1, ..., k - 1
        return BigInt(max) + mul(k - 1, k) / 2n
    }
    function range(i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

const lines = [];
const _rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
_rl.on('line', line => lines.push(line));
_rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);
const rl = readline;

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const sumab = (a, b) => {
    if (a > b) return 0;
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return x * y;
}

const calc = (t)=>{
    /* read */
    let [n, k] = ra();
    let a = ra();

    if (n === 1) {
        return a[0] + k - 1;
    }

    if (k <= n) {
        let i = 0;
        let curSum = 0;
        for (; i < k; i++) {
            curSum += a[i];
        }
        let maxSum = curSum;
        for (; i < n; i++) {
            curSum += a[i];
            curSum -= a[i - k];
            maxSum = Math.max(maxSum, curSum);
        }
        return maxSum + sumab(1, k - 1);
    } else {
        let sum = 0;
        for (let i = 0; i < n; i++) {
            sum += a[i];
        }
        // console.log(`DEBUG t ${t} sum`, sum);
        let wait = k - n;
        // console.log(`DEBUG t ${t} wait`, wait);
        let traverse = sumab(wait + 1, wait + n - 1);
        // console.log(`DEBUG t ${t} traverse`, traverse);
        let result = sum + wait + traverse;
        return result;
    }
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc(t));
        // process.stdout.write(`${calc(t)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

'use strict';

function solve(n, m, a) {
  const bm = BigInt(m),
        bn = BigInt(n);
  if (m >= n) {
    return (a.reduce((a, b) => a + b, 0n) + bm * (bm - 1n) / 2n - (bm - bn) * (bm - bn - 1n) / 2n).toString();
  }
  const sum = [];
  let max = 0n;
  for (let [i, num] of a.entries()) {
    var _sum, _sum2;
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0n) + num;
    const cur = sum[i] - ((_sum2 = sum[i - m]) !== null && _sum2 !== void 0 ? _sum2 : 0n);
    if (max < cur) max = cur;
  }
  return (max + bm * (bm - 1n) / 2n).toString();
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(BigInt);
      res.push(solve(n, m, a));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});

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

function main() {
    const t = readline()
    for(let _=0;_<t;_++) {
        const [n, k] = readline().split(' ').map(Number)
        const arr = readline().split(' ').map(Number)
        let answer = 0

        let sum_list = Array(n+1).fill(0)
        sum_list[1] = arr[0]

        for (let i=2;i<n+1;i++) {
            sum_list[i] = sum_list[i-1] + arr[i-1]
        }
        if (n < k) {
            answer = sum_list[n] + parseInt(n * (n - 1) / 2) + n * (k - n)
        } else {
            for(let i=k;i<n+1;i++){
                answer = Math.max(answer, sum_list[i] - sum_list[i-k])
            }
            answer += parseInt(k * (k - 1) / 2)
        }
        print(answer)
    }

}

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = [arr[0]]
    for (let i = 1; i < n; i++) {
        sum[i] = sum[i - 1] + arr[i]
    }
    // console.log(sum)
    if (k >= n) {
        // const t = Math.floor((k - 1) / (n - 1))
        // const r = k % (n - 1)
        return BigInt(sum[n - 1]) + mul(k - 1 + k - 1 - n + 1, n) / 2n
    } else {
        let max = 0
        for (let i = 0; i < n; i++) {
            const after = n - 1 - i + 1
            let now
            if (k <= after) {
                now = range(i, i + k - 1)
            } else {
                const before = k - after
                now = range(i, n - 1) + range(n - 2 - before + 1, n - 2)
            }
            if (now > max) max = now
            // console.log(now)
            if (i + 1 < k) {
                const before = k - (i + 1)
                now = range(1, 1 + before - 1) + range(0, i)
                if (now > max) max = now
                // console.log(now)
            }
        }
        // 0, 1, ..., k - 1
        return BigInt(max) + mul(k - 1, k) / 2n
    }
    function range(i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = [arr[0]]
    for (let i = 1; i < n; i++) {
        sum[i] = sum[i - 1] + arr[i]
    }
    // console.log(sum)
    if (k >= n) {
        // const t = Math.floor((k - 1) / (n - 1))
        // const r = k % (n - 1)
        return BigInt(sum[n - 1]) + mul(k - 1 + k - 1 - n + 1, n) / 2n
    } else {
        let max = 0
        for (let i = 0; i < n; i++) {
            const after = n - 1 - i + 1
            let now
            if (k <= after) {
                now = range(i, i + k - 1)
            } else {
                const before = k - after
                now = range(i, n - 1) + range(n - 1 - before + 1, n - 1)
            }
            if (now > max) max = now
            // console.log(now)
            if (i + 1 < k) {
                const before = k - (i + 1)
                now = range(0, before - 1) + range(0, i)
                if (now > max) max = now
                // console.log(now)
            }
        }
        // 0, 1, ..., k - 1
        return BigInt(max) + mul(k - 1, k) / 2n
    }
    function range(i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = [arr[0]]
    for (let i = 1; i < n; i++) {
        sum[i] = sum[i - 1] + arr[i]
    }
    // console.log(sum)
    if (k >= n) {
        // const t = Math.floor((k - 1) / (n - 1))
        // const r = k % (n - 1)
        return BigInt(sum[n - 1]) + mul(k - 1 + k - 1 - n + 1, n) / 2n
    } else {
        let max = 0
        for (let i = 0; i < n; i++) {
            const after = n - 1 - i + 1
            let now
            if (k <= after) {
                now = range(i, i + k - 1)
            } else {
                const before = k - after
                now = range(i, n - 1) + range(n - 1 - before + 1, n - 1)
            }
            if (now > max) max = now
            // console.log(now)
        }
        // 0, 1, ..., k - 1
        return BigInt(max) + mul(k - 1, k) / 2n
    }
    function range(i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

const readline = require('readline')

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

function solve(n, k, arr) {
    const sum = [arr[0]]
    for (let i = 1; i < n; i++) {
        sum[i] = sum[i - 1] + arr[i]
    }
    // console.log(sum)
    if (k >= n) {
        // const t = Math.floor((k - 1) / (n - 1))
        // const r = k % (n - 1)
        return BigInt(sum[n - 1]) + mul(k - 1 + k - 1 - n + 1, n) / 2n
    } else {
        let max = 0
        for (let i = 0; i < n; i++) {
            const after = n - 1 - i + 1
            let now
            if (k <= after) {
                now = range(i, i + k - 1)
            } else {
                const before = k - after
                now = range(i, n - 1) + range(0, before - 1)
            }
            if (now > max) max = now
        }
        // 0, 1, ..., k - 1
        return BigInt(max) + mul(k - 1, k) / 2n
    }
    function range(i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const sumab = (a, b) => {
    if (a > b) return 0;
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return x * y;
}

const calc = (t)=>{
    /* read */
    let [n, k] = ra();
    let a = ra();

    if (n === 1) {
        return a[0] + k - 1;
    }

    if (k < n) {
        let i = 0;
        let curSum = 0;
        for (; i < k; i++) {
            curSum += a[i];
        }
        let maxSum = curSum;
        for (; i < n; i++) {
            curSum += a[i];
            curSum -= a[i - k];
            maxSum = Math.max(maxSum, curSum);
        }
        return maxSum + sumab(1, k - 1);
    } else {
        let start = k % n;
        // console.log(`DEBUG t ${t} start`, start);
        let sum = 0;
        for (let i = 0; i < n; i++) {
            sum += a[i];
        }
        let initial = start + n;
        // console.log(`DEBUG t ${t} initial`, initial);
        let cycles = Math.floor((k - initial) / (n - 1) + 0.000001);
        // console.log(`DEBUG t ${t} cycles`, cycles);

        let result = sumab(1, n - 1) * 2 * cycles + sum;
        // console.log(`DEBUG t ${t} result1`, result);

        let remMoves = k - initial - cycles * (n - 1);
        // console.log(`DEBUG t ${t} remMoves`, remMoves);
        result += sumab(1, remMoves) * 2;
        // console.log(`DEBUG t ${t} result2`, result);

        result += sumab(1, start) + sumab(1, start - 1) * 2;
        // console.log(`DEBUG t ${t} result3`, result);

        let rem = n - start;
        // console.log(`DEBUG t ${t} rem`, rem);
        let ns = start * 2;
        result += sumab(ns, ns + rem - 1);
        // console.log(`DEBUG t ${t} result4`, result);
        return result;
    }
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc(t));
        // process.stdout.write(`${calc(t)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

'use strict';

function solve(n, m, a) {
  if (m >= n) {
    return a.reduce((a, b) => a + b, 0) + m * (m - 1) / 2 - (m - n) * (m - n - 1) / 2;
  }
  const sum = [];
  let max = 0;
  for (let [i, num] of a.entries()) {
    var _sum, _sum2;
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + num;
    max = Math.max(max, sum[i] - ((_sum2 = sum[i - m]) !== null && _sum2 !== void 0 ? _sum2 : 0));
  }
  return max + m * (m - 1) / 2;
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res.push(solve(n, m, a));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$ and an integer $$$k$$$, such that $$$1 \leq k \leq n$$$. A permutation means that every number from $$$1$$$ to $$$n$$$ is contained in $$$p$$$ exactly once.Let's consider all partitions of this permutation into $$$k$$$ disjoint segments. Formally, a partition is a set of segments $$$\{[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\}$$$, such that:  $$$1 \leq l_i \leq r_i \leq n$$$ for all $$$1 \leq i \leq k$$$;  For all $$$1 \leq j \leq n$$$ there exists exactly one segment $$$[l_i, r_i]$$$, such that $$$l_i \leq j \leq r_i$$$. Two partitions are different if there exists a segment that lies in one partition but not the other.Let's calculate the partition value, defined as $$$\sum\limits_{i=1}^{k} {\max\limits_{l_i \leq j \leq r_i} {p_j}}$$$, for all possible partitions of the permutation into $$$k$$$ disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by $$$998\,244\,353$$$.

The first line contains two integers, $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 200\,000$$$) — the size of the given permutation and the number of segments in a partition. The second line contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$) — the given permutation.

Print two integers — the maximum possible partition value over all partitions of the permutation into $$$k$$$ disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo $$$998\,244\,353$$$. Please note that you should only find the second value modulo $$$998\,244\,353$$$.

NoteIn the first test, for $$$k = 2$$$, there exists only two valid partitions: $$$\{[1, 1], [2, 3]\}$$$ and $$$\{[1, 2], [3, 3]\}$$$. For each partition, the partition value is equal to $$$2 + 3 = 5$$$. So, the maximum possible value is $$$5$$$ and the number of partitions is $$$2$$$.In the third test, for $$$k = 3$$$, the partitions with the maximum possible partition value are $$$\{[1, 2], [3, 5], [6, 7]\}$$$, $$$\{[1, 3], [4, 5], [6, 7]\}$$$, $$$\{[1, 4], [5, 5], [6, 7]\}$$$, $$$\{[1, 2], [3, 6], [7, 7]\}$$$, $$$\{[1, 3], [4, 6], [7, 7]\}$$$, $$$\{[1, 4], [5, 6], [7, 7]\}$$$. For all of them, the partition value is equal to $$$7 + 5 + 6 = 18$$$. The partition $$$\{[1, 2], [3, 4], [5, 7]\}$$$, however, has the partition value $$$7 + 3 + 6 = 16$$$. This is not the maximum possible value, so we don't count it.

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

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

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

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() {
  return parseInt(input[ptr++])
}

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

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

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

function main() {
  const [n, k] = readInts()
  const p = readInts()
  const mod = 998244353
  const x = p.map((a, i) => [a, i])
  x.sort((a, b) => b[0] - a[0])
  let ans1 = 0
  let ans2 = 1
  const mark = new Array(n).fill(0)
  for(let i = 0; i < k; i++) {
    ans1 += x[i][0]
    mark[x[i][1]] = 1
  }
  let ptr = mark[0] ? 0 : -1
  for(let i = 1; i < n; i++) {
    if(mark[i] && ptr === -1) {
      ptr = i
    }
    else if(mark[i] && ptr !== -1) {
      ans2 = ans2 *(i - ptr) % mod
      ptr = i
    }
  }

  wr(ans1, ans2)
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
var inputString = '';
var currentLine = 0;
process.stdin.on('data', function (input) { inputString += input; });
process.stdin.on('end', function (_) { inputString = inputString.split('\n'); main(); });
var readline = function () { return inputString[currentLine++]; };
function main() {
    var _a = readline().split(' ').map(function (x) { return parseInt(x); }), n = _a[0], k = _a[1];
    var p = readline().split(' ').map(function (x) { return parseInt(x); });
    var mnMax = n - k + 1;
    var pos = -1;
    var sum = 0;
    var parts = 1;
    p.forEach(function (val, index) {
        if (val >= mnMax) {
            sum += val;
            if (pos != -1)
                parts = (parts * (index - pos)) % 998244353;
            pos = index;
        }
    });
    console.log(sum, parts);
}

process.stdin.resume();
process.stdin.setEncoding('utf-8')
let inputString = '';
let currentLine = 0;
process.stdin.on('data', input => { inputString += input; })
process.stdin.on('end', _ => { inputString = inputString.split('\n'); main(); })
const readline = () => { return inputString[currentLine++] }

function main() {
    [n, k] = readline().split(' ').map(x => parseInt(x));
    p = readline().split(' ').map(x => parseInt(x));
    let mnMax = n - k + 1;
    let pos = -1;
    let sum = 0;
    let parts = 1;
    p.forEach((val, index) => {
        if(val >= mnMax){
            sum += val;
            if(pos != -1)
                parts = (parts * (index - pos)) % 998244353;
            pos = index;
        }
    })
    console.log(sum, parts);
}

const mod =  998244353

const processData = (lines) => {
  const [num, k] = lines[0].split(' ').map(x => +x)

  const nums = lines[1].split(' ').map(x => +x)
  const sliced = nums.map((x, pos) => ({num: x, pos})).sort((a, b) => b.num-a.num).slice(0, k)
  const max = sliced.reduce((r, x) => r+x.num, 0)

  sliced.sort((a, b) => a.pos - b.pos)

  let multipliers = []
  let prevPos = sliced[0].pos
  for (let i=1; i<sliced.length; i++) {
    const pos = sliced[i].pos
    if (pos - prevPos > 1) {
      multipliers.push(pos - prevPos)
    }
    prevPos = pos
  }

  let sum = 1
  for (const m of multipliers) {
    sum = (sum * m) % mod
  }

  console.log(`${max} ${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 mod =  998244353

const processData = (lines) => {
  const [num, k] = lines[0].split(' ').map(x => +x)

  const nums = lines[1].split(' ').map(x => +x)
  const sliced = nums.map((x, pos) => ({num: x, pos})).sort((a, b) => b.num-a.num).slice(0, k)
  const max = sliced.reduce((r, x) => r+x.num, 0)

  sliced.sort((a, b) => a.pos - b.pos)

  let multipliers = []
  let prevPos = 0
  for (let i=0; i<sliced.length; i++) {
    const pos = sliced[i].pos
    if (pos - prevPos > 1) {
      multipliers.push(pos - prevPos)
    }
    prevPos = pos
  }

  let sum = 1
  for (const m of multipliers) {
    sum = (sum * m) % mod
  }

  console.log(`${max} ${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 mod =  998244353

const processData = (lines) => {
  const [num, k] = lines[0].split(' ').map(x => +x)

  const nums = lines[1].split(' ').map(x => +x)
  const sliced = nums.map((x, pos) => ({num: x, pos})).sort((a, b) => b.num-a.num).slice(0, k)
  const max = sliced.reduce((r, x) => r+x.num, 0)

  sliced.sort((a, b) => a.pos - b.pos)

  let multipliers = []
  let prevPos = 0
  for (let i=0; i<sliced.length; i++) {
    const pos = sliced[i].pos
    if (pos - prevPos > 1) {
      multipliers.push(pos - prevPos)
    }
    prevPos = pos
  }
  if (prevPos < num - 1) {
    multipliers.push(num - 1 - prevPos)
  }

  let sum = 1
  for (const m of multipliers) {
    sum = (sum * m) % mod
  }

  console.log(`${max} ${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)
})


Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.

The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.

Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.

function main() {
    var n = Number(readline());
    var edges = [];
    for(var i=0;i<n-1;i++){
        var line = readline().split(' ').map(Number);
        line[0]-=1
        line[1]-=1
        edges.push(line);
    }
    var colors = readline().split(' ').map(Number);
    var badEdges = edges.filter(e => colors[e[0]] != colors[e[1]]);
    if(badEdges.length == 0){
        return print("YES" + "\n" + 1)
    }
    var counters = [];
    for(var i=0;i<n;i++){
        counters[i] = 0;
    }
    for(var i=0;i<badEdges.length;i++){
        counters[badEdges[i][0]]++
        counters[badEdges[i][1]]++
    }
    for(var i=0;i<n;i++){
        if(counters[i] == badEdges.length){
            return print("YES" + "\n" + (i+1))
        }
    }
    print("NO");
}

main()

function main() {
    var n = Number(readline());
    var edges = [];
    for(var i=0;i<n-1;i++){
        var line = readline().split(' ').map(Number);
        line[0]-=1
        line[1]-=1
        edges.push(line);
    }
    var colors = readline().split(' ').map(Number);
    var badEdges = edges.filter(e => colors[e[0]] != colors[e[1]]);
    if(badEdges.length == 0){
        return print("YES" + "\n" + 1)
    }
    var counters = [];
    for(var i=0;i<n;i++){
        counters[i] = 0;
    }
    for(var i=0;i<badEdges.length;i++){
        counters[badEdges[i][0]]++
        counters[badEdges[i][1]]++
    }
    for(var i=0;i<badEdges.length;i++){
        if(counters[i] == badEdges.length){
            return print("YES" + "\n" + (i+1))
        }
    }
    print("NO");
}

main()


The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single odd integer $$$n$$$ ($$$3 \le n \le 199$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon.

Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i <= Number(q[0]); i++) {
        console.log(solve(q[i]))
    }
}
function solve(n) {
    const ang1 = Math.PI / n;
    const R = 0.5 / Math.sin(ang1 / 2);
    function ee(shift) {
        let xl = Number.MAX_VALUE;
        let yb = Number.MAX_VALUE;
        let xr = Number.MIN_VALUE;
        let yt = Number.MIN_VALUE;
        for (let i = 0; i < 2 * n; i++) {
            const x = Math.cos(Math.PI / n * i + shift);
            const y = Math.sin(Math.PI / n * i + shift);
            xl = Math.min(xl, x);
            xr = Math.max(xr, x);
            yb = Math.min(yb, y);
            yt = Math.max(yt, y);
        }
        return Math.max(xr - xl, yt - yb) * R;
    }

    return ee(Math.PI / 4 / n).toPrecision(10);
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i <= Number(q[0]); i++) {
        console.log(solve(q[i]))
    }
}
function solve(n) {
    const ang1 = Math.PI / n;
    const R = 0.5 / Math.sin(ang1 / 2);
    function ee(shift) {
        let xl = Number.MAX_VALUE;
        let yb = Number.MAX_VALUE;
        let xr = Number.MIN_VALUE;
        let yt = Number.MIN_VALUE;
        for (let i = 0; i < 2 * n; i++) {
            const x = R * Math.cos(Math.PI / n * i + shift);
            const y = R * Math.sin(Math.PI / n * i + shift);
            xl = Math.min(xl, x);
            xr = Math.max(xr, x);
            yb = Math.min(yb, y);
            yt = Math.max(yt, y);
        }
        return Math.max(xr - xl, yt - yb);
    }
    let l = 0;
    let r = (2 * Math.PI) / (2 * n);
    for (let i = 0; i < 100; i++) {
        const l1 = (2 * l + r) / 3;
        const r1 = (2 * r + l) / 3;
        const calc1 = ee(l1);
        const calc2 = ee(r1);
        if (calc1 < calc2) {
            r = r1;
        } else {
            l = l1;
        }
    }
    return ee((l + r) / 2).toPrecision(10);
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})

function Main() {
  var A = Number(readline());
  for(var i=0;i<A;i++){
    var n = Number(readline());
    print(Math.sin((Math.PI*(n-1/2))/(2*n))/(Math.sin(Math.PI/(2*n))));
  }
}
Main();

const readline = require('readline');
const input = [];
function A(q) {
    for (let i = 1; i <= Number(q[0]); i++) {
        console.log(solve(q[i]))
    }
}
function solve(n) {
    const ang1 = Math.PI / n;
    const R = 0.5 / Math.sin(ang1 / 2);
    function ee(shift) {
        let xl = Number.MAX_VALUE;
        let yb = Number.MAX_VALUE;
        let xr = Number.MIN_VALUE;
        let yt = Number.MIN_VALUE;
        for (let i = 0; i < n; i++) {
            const x = R * Math.cos(Math.PI / n * i + shift);
            const y = R * Math.sin(Math.PI / n * i + shift);
            xl = Math.min(xl, x);
            xr = Math.max(xr, x);
            yb = Math.min(yb, y);
            yt = Math.max(yt, y);
        }
        return Math.max(xr - xl, yt - yb);
    }
    let l = 0;
    let r = (2 * Math.PI) / (2 * n);
    for (let i = 0; i < 100; i++) {
        const l1 = (2 * l + r) / 3;
        const r1 = (2 * r + l) / 3;
        if (ee(l1) < ee(r1)) {
            r = r1;
        } else {
            l = l1;
        }
    }
    return ee((l + r) / 2).toPrecision(10);
}
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', q => {
    input.push(q.trim())
});
rl.on('close', () => {
    A(input);
})


The only difference between the easy and hard versions is that the given string $$$s$$$ in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.Alice and Bob are playing a game on a string $$$s$$$ of length $$$n$$$ consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations:   Choose any $$$i$$$ ($$$1 \le i \le n$$$), where $$$s[i] =$$$ '0' and change $$$s[i]$$$ to '1'. Pay 1 dollar.  Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$). The second line of each test case contains the string $$$s$$$ of length $$$n$$$, consisting of the characters '0' and '1'. It is guaranteed that the string $$$s$$$ contains at least one '0'. Note that there is no limit on the sum of $$$n$$$ over test cases.

For each test case print a single word in a new line:    "ALICE", if Alice will win the game,  "BOB", if Bob will win the game,  "DRAW", if the game ends in a draw.

NoteIn the first test case of example,   in the $$$1$$$-st move, Alice will use the $$$2$$$-nd operation to reverse the string, since doing the $$$1$$$-st operation will result in her loss anyway. This also forces Bob to use the $$$1$$$-st operation.  in the $$$2$$$-nd move, Bob has to perform the $$$1$$$-st operation, since the $$$2$$$-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.  Alice spends $$$0$$$ dollars while Bob spends $$$1$$$ dollar. Hence, Alice wins.In the second test case of example,   in the $$$1$$$-st move Alice has to perform the $$$1$$$-st operation, since the string is currently a palindrome.  in the $$$2$$$-nd move Bob reverses the string.  in the $$$3$$$-rd move Alice again has to perform the $$$1$$$-st operation. All characters of the string are '1', game over.  Alice spends $$$2$$$ dollars while Bob spends $$$0$$$ dollars. Hence, Bob wins.

var readline = require('readline');

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

function solve(str) {
    const mid = Math.ceil(str.length / 2)

    let zero = 0
    let diff = 0
    for (let i = mid - 1; i >= 0; i--) {
        const j = str.length - 1 - i
        if (str[i] !== str[j]) diff++
        else if (str[i] === '0') zero++
    }

    let cost
    if ((str.length & 1) && str[mid - 1] === '0') {
        // alice change the middle 0 first
        // then convert to 0x0
        if (zero === 1) {
            cost = [1, 0]
            // if diff > 1, alice will reverse, and make bob pay the total
            if (diff > 1) {
                cost = [0, 1 + diff]
            } else if (diff === 1) {
            // if diff == 1, bob can force alice to fill the uniqe 0
                cost = [1, 1]
            }
        } else {
            // alices starts the process
            // if bob skips to reduce the diff, just reverse
            cost = [1, 2 + diff]
        }
    } else {
        // 00x00 -> 10x00 -> 10x01, same with 0x0
        cost = [2, 0]
        if (diff) {
            // alice reverses first, no matter bob chooses to reduce the diff,
            // or start 00 process, bob pays the total
            cost = [0, 2 + diff]
        }
    }

    if (cost[0] !== cost[1]) {
        return cost[0] < cost[1] ? 'ALICE' : 'BOB'
    } else {
        return 'DRAW'
    }
}

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 05/20/21 afternoon

const solve = (n, s) => {
    let cnt = 0;
    for (const c of s) cnt += (c == '0');
    if (cnt == 0) return pr('DRAW');
    if (!isPalindrome(s)) {
        if (n & 1 && s[n >>> 1] == '0' && cnt == 2) {
            return pr('DRAW');
        }
        return pr('ALICE');
    }
    if (n & 1 && s[n >>> 1] == '0') {
        if (cnt == 1) {
            return pr('BOB');
        } else if (cnt == 2) {
            return pr('DRAW');
        } else {
            return pr("ALICE");
        }
    }
    pr('BOB');
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line);
    });
    rl.on('close', () => {
        let t = Number(input[0]);
        let i = 1;
        while (t--) {
            solve(input[i], input[i + 1]);
            i += 2;
        }
    });
};

main()

var readline = require('readline');

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

function solve(str) {
    const mid = Math.ceil(str.length / 2)

    let zero = 0
    let diff = 0
    for (let i = mid - 1; i >= 0; i--) {
        const j = str.length - 1 - i
        if (str[i] !== str[j]) diff++
        else if (str[i] === '0') zero++
    }

    let cost
    if ((str.length & 1) && str[mid - 1] === '0') {
        // alice change the middle 0 first
        // then convert to 0x0
        if (zero === 1) {
            cost = [1, 0]
            // if diff > 1, alice will reverse, and make bob pay the total
            if (diff > 1) {
                cost = [0, 1 + diff]
            } else {
            // if diff == 1, bob can force alice to fill the uniqe 0
                cost = [1, 1]
            }
        } else {
            // alices starts the process
            // if bob skips to reduce the diff, just reverse
            cost = [1, 2 + diff]
        }
    } else {
        // 00x00 -> 10x00 -> 10x01, same with 0x0
        cost = [2, 0]
        if (diff) {
            // alice reverses first, no matter bob chooses to reduce the diff,
            // or start 00 process, bob pays the total
            cost = [0, 2 + diff]
        }
    }

    if (cost[0] !== cost[1]) {
        return cost[0] < cost[1] ? 'ALICE' : 'BOB'
    } else {
        return 'DRAW'
    }
}

var readline = require('readline');

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

function solve(str) {
    const mid = Math.ceil(str.length / 2)

    let zero = 0
    let diff = 0
    for (let i = mid - 1; i >= 0; i--) {
        const j = str.length - 1 - i
        if (str[i] !== str[j]) diff++
        else if (str[i] === '0') zero++
    }

    let cost
    if ((str.length & 1) && str[mid - 1] === '0') {
        // alice change the middle 0 first
        // then convert to 0x0
        if (zero === 1) {
            cost = [1, 0]
        } else {
            cost = [1, 2]
        }
    } else {
        // 00x00 -> 10x00 -> 10x01, same with 0x0
        cost = [2, 0]
    }

    const [a, b] = cost
    if (diff) {
        // not reverse, [a + diff, b]
        // reverse, [b, a + diff]
        cost = [Math.min(a + diff, b), Math.max(a + diff, b)]
    }

    if (cost[0] !== cost[1]) {
        return cost[0] < cost[1] ? 'ALICE' : 'BOB'
    } else {
        return 'DRAW'
    }
}

var readline = require('readline');

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

function solve(str) {
    const mid = Math.ceil(str.length / 2)

    let zero = 0
    let diff = 0
    for (let i = mid - 1; i >= 0; i--) {
        const j = str.length - 1 - i
        if (str[i] !== str[j]) diff++
        else if (str[i] === '0') zero++
    }

    // 00x00 -> 10x00 -> 10x01, same with 0x0
    let cost = [2, 0]
    if ((str.length & 1) && str[mid - 1] === '0') {
        // alice change the middle 0 first
        // then convert to 0x0
        cost = [1, 2]
        return diff === 1 ? 'DRAW' : 'ALICE'
    }
    if (diff) {
        cost = [0, 2 + diff]
    }

    const [a, b] = cost
    if (a !== b) {
        return a < b ? 'ALICE' : 'BOB'
    } else {
        return 'DRAW'
    }
}

var readline = require('readline');

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

let cache0, cache1
function solve(str) {
    cache0 = {}
    cache1 = {}

    const mid = Math.ceil(str.length / 2)
    for (let i = mid - 1; i >= 0; i--) {
        const j = str.length - i
        cache0[i] = solvePay(str, i, j)
        cache1[i] = solvePay(str, i, j, 1)
    }
    const [a, b] = cache0[0]
    // console.log(cache0)
    if (a === b) return 'DRAW'
    return a < b ? 'ALICE' : 'BOB'
}

// @returns [a, b, p], `p` means `str` is palindrome
function solvePay(str, i, j, r /* if 1, can't reverse */) {
    str = str.slice(i, j)

    const len = str.length
    if (len === 1) {
        return str === '1' ? [0, 0, 1] : [1, 0, 1]
    } else if (len === 2) {
        if (str === '11') {
            return [0, 0, 1]
        } else if (str === '00') {
            // change -> reverse -> change
            return [2, 0, 1]
        } else {
            // reverse -> change
            return r ? [1, 0, 0] : [0, 1, 0]
        }
    } else {
        const r1 = cache0[i + 1]
        const r2 = cache1[i + 1]
        const [a, b, p] = r1
        const [a2, b2, p2] = r2

        str = str[0] + str[str.length - 1]
        if (str === '11') {
            if (r) {
                // still can't reverse, do nothing
                return r2
            } else if (p) {
                return r1
            } else {
                return [b, a, p]
            }
        } else if (str === '00') {
            if (p || r) {
                // can't reverse
                return [b + 2, a, p]
            } else {
                return [a, b + 2, p]
            }
        } else {
            if (r) {
                return [a + 1, b, 0]
            } else {
                return [a, b + 1, 0]
            }
        }
    }
}

// console.log(solvePay('11'))
// console.log(solvePay('1111'))

var readline = require('readline');

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

let cache0, cache1
function solve(str) {
    cache0 = {}
    cache1 = {}

    const mid = Math.ceil(str.length / 2)
    for (let i = mid - 1; i >= 0; i--) {
        const j = str.length - i
        cache0[i] = solvePay(str, i, j)
        cache1[i] = solvePay(str, i, j, 1)
    }
    const [a, b] = cache0[0]
    // console.log(cache0)
    if (a === b) return 'DRAW'
    return a < b ? 'ALICE' : 'BOB'
}
function solvePay(str, i, j, r /* if 1, can't reverse */) {
    str = str.slice(i, j)

    const len = str.length
    if (len === 1) {
        return str === '1' ? [0, 0, 1] : [1, 0, 1]
    } else if (len === 2) {
        if (str === '11') {
            return [0, 0, 1]
        } else if (str === '00') {
            // change -> reverse -> change
            return [2, 0, 1]
        } else {
            // reverse -> change
            return r ? [1, 0, 0] : [0, 1, 0]
        }
    } else {
        const r1 = cache0[i + 1]
        const r2 = cache1[i + 1]
        const [a, b, p] = r1
        const [a2, b2, p2] = r2

        str = str[0] + str[str.length - 1]
        if (str === '11') {
            if (r) {
                // still can't reverse
                return r2
            } else {
                return r1
            }
        } else if (str === '00') {
            if (p || r) {
                // can't reverse
                return [a + 2, b, p]
            } else {
                return [a, b + 2, p]
            }
        } else {
            if (r) {
                return [a + 1, b, 0]
            } else {
                return [a, b + 1, 0]
            }
        }
    }
}

// console.log(solvePay('11'))
// console.log(solvePay('1111'))

var readline = require('readline');

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

function solve(str) {
    const [a, b] = solvePay(str)
    if (a === b) return 'DRAW'
    return a < b ? 'ALICE' : 'BOB'
}
function solvePay(str) {
    if (str.length === 1) {
        return str === '1' ? [0, 0, 1] : [1, 0, 1]
    } else if (str.length === 2) {
        if (str === '11') {
            return [0, 0, 1]
        } else if (str === '00') {
            // change -> reverse -> change
            return [2, 0, 1]
        } else {
            // reverse -> change
            return [0, 1, 0]
        }
    } else {
        const [a, b, p] = solvePay(str.slice(1, -1))
        if (str === '11') {
            return [a, b, p]
        } else if (str === '00') {
            if (p) {
                return [a + 2, b, p]
            } else {
                return [a, b + 2, p]
            }
        } else {
            return [a, b + 1, 0]
        }
    }
}

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/20/21 afternoon
 * https://codeforces.com/contest/1527/problem/B2
 */

const solve = (n, s) => {
    let se = new Set();
    for (let i = 0; i < n; i++) {
        if (s[i] == '0') se.add(i);
    }
    let a = s.split("");
    let Alice = Bob = 0;
    let isP = isPalindrome(s);
    let round = 1;
    let pre;
    while (se.size) {
        if (isP == false && pre != 'rv') {
            a.reverse();
            pre = 'rv';
        } else {
            let did = false;
            for (const i of se) {
                if (i == n - 1 - i || a[n - 1 - i] == '1') {
                    a[i] = '1';
                    did = true;
                    se.delete(i);
                    break;
                }
            }
            if (!did) {
                let first = se.values().next().value;
                a[first] = '1';
                se.delete(first);
                isP = false;
            }
            round & 1 ? Alice++ : Bob++;
            pre = 'rp';
        }
        round++;
    }
    if (Alice > Bob) {
        pr("BOB");
    } else if (Alice < Bob) {
        pr("ALICE");
    } else {
        pr("DRAW")
    }
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line);
    });
    rl.on('close', () => {
        let t = Number(input[0]);
        let i = 1;
        while (t--) {
            solve(input[i], input[i + 1]);
            i += 2;
        }
    });
};

main()


You are given a grid with $$$n$$$ rows and $$$m$$$ columns, where each cell has a positive integer written on it. Let's call a grid good, if in each row the sequence of numbers is sorted in a non-decreasing order. It means, that for each $$$1 \le i \le n$$$ and $$$2 \le j \le m$$$ the following holds: $$$a_{i,j} \ge a_{i, j-1}$$$.You have to to do the following operation exactly once: choose two columns with indexes $$$i$$$ and $$$j$$$ (not necessarily different), $$$1 \le i, j \le m$$$, and swap them.You are asked to determine whether it is possible to make the grid good after the swap and, if it is, find the columns that need to be swapped.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of rows and columns respectively. Each of the next $$$n$$$ rows contains $$$m$$$ integers, $$$j$$$-th element of $$$i$$$-th row is $$$a_{i,j}$$$ ($$$1 \le a_{i,j} \le 10^9$$$) — the number written in the $$$j$$$-th cell of the $$$i$$$-th row. It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

If after the swap it is impossible to get a good grid, output $$$-1$$$. In the other case output $$$2$$$ integers — the indices of the columns that should be swapped to get a good grid. If there are multiple solutions, print any.

NoteIn the first test case the grid is initially good, so we can, for example, swap the first column with itself.In the second test case it is impossible to make the grid good.In the third test case it is needed to swap the first and the second column, then the grid becomes good.

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const calc = ()=>{
    /* read */
    let [n, m] = ra();
    let g = [];
    let cols = new Array(m);
    let scols = new Array(m);
    let sg = [];
    for (let i = 0; i < n; i++) {
        let row = ra();
        g.push(row);
        sg.push([...row]);
    }

    for (let i = 0; i < m; i++) {
        cols[i] = i;
        scols[i] = i;
    }

    if (m === 1) return "1 1";

    const isInc = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] > g[i][b]) return false;
        }
        return true;
    }

    const isDec = (a, b) => {
        let eqcnt = 0;
        for (let i = 0; i < n; i++) {
            if (g[i][a] < g[i][b]) return false;
            if (g[i][a] === g[i][b]) eqcnt++;
        }
        return eqcnt !== n;
    }

    const isEq = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] !== g[i][b]) return false;
        }
        return true;
    }

    for (let i = 0; i < n; i++) {
        sg[i].sort((a, b) => a - b);
    }

    // scols.sort((a, b) => {
    //     if (isEq(a, b)) return 0;
    //     if (isInc(a, b)) return -1;
    //     return 1;
    // });

    // console.log('DEBUG g', g);
    // console.log('DEBUG sg', sg);

    let diffs = new Set();

    for (let i = 0; i < n; i++){
        for (let j = 0; j < m; j++) {
            if (g[i][j] !== sg[i][j]) diffs.add(j);
        }
    }

    // console.log('DEBUG diffs', diffs);

    diffs = Array.from(diffs);

    if (diffs.length > 2) return "-1";

    if (diffs.length === 2) {
        for (let i = 0; i < n; i++) {
            let tmp = g[i][diffs[0]];
            g[i][diffs[0]] = g[i][diffs[1]];
            g[i][diffs[1]] = tmp;
        }
    }

    // console.log('DEBUG g', g);

    for (let i = 0; i < n; i++){
        for (let j = 0; j < m - 1; j++) {
            if (g[i][j] > g[i][j + 1]) return "-1";
        }
    }

    return diffs.length === 2 ? `${diffs[0] + 1} ${diffs[1] + 1}` : "1 1";

};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

'use strict';

var readline = require('readline');

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

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

function solve(n, m, grid) {
  let res = [-1, -1];
  skip: for (let i = 0; i < n; i++) {
    const dp = [],
          nums = grid[i];
    for (let j = m - 1; j >= 0; j--) {
      var _nums$dp;
      if (nums[j] < ((_nums$dp = nums[dp[j + 1]]) !== null && _nums$dp !== void 0 ? _nums$dp : Infinity)) {
        dp[j] = j;
      } else {
        dp[j] = dp[j + 1];
      }
    }
    for (let j = 0; j < m; j++) {
      if (nums[dp[j]] < nums[j]) {
        res = [j, dp[j]];
        break skip;
      }
    }
  }
  if (res[0] === -1) return `1 1`;
  const [a, b] = res;
  const swap = (i, j, k) => [grid[i][j], grid[i][k]] = [grid[i][k], grid[i][j]];
  for (let i = 0; i < n; i++) {
    if (grid[i][a] < grid[i][b]) return -1;
    swap(i, a, b);
  }
  for (let i = 0; i < n; i++) {
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) return -1;
    }
  }
  return [a + 1, b + 1].join(' ');
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const [n, m] = (await read()).split(' ').map(Number);
    const a = [];
    let tmp = n;
    while (tmp--) {
      a.push((await read()).split(' ').map(Number));
    }
    res.push(solve(n, m, a));
  }
  console.log(res.join('\n'));
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, m, grid) {
  let res = [];
  const swap = (i, j, k) => [grid[i][j], grid[i][k]] = [grid[i][k], grid[i][j]];
  for (let i = 0; i < n; i++) {
    let a = -1,
        b = -1;
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) {
        let t = j - 1;
        for (let k = j - 1; k >= 0; k--) {
          if (nums[k] === nums[j - 1]) t = k;
        }
        if (t === j - 1) {
          let t1 = j;
          for (let k = j + 1; k < m; k++) {
            if (nums[k] <= nums[j]) t1 = k;
          }
          if (t1 === j) {
            if (nums[j + 1] < nums[j]) {
              [a, b] = [t, j + 1];
            } else {
              [a, b] = [t, j];
            }
          } else {
            [a, b] = [t, t1];
          }
        } else {
          [a, b] = [t, j];
        }
        break;
      }
    }
    if (a !== -1) {
      res.push([a, b]);
      break;
    }
  }
  if (!res.length) return `1 1`;
  const [a, b] = res[0];
  for (let i = 0; i < n; i++) {
    if (grid[i][a] < grid[i][b]) return -1;
    swap(i, a, b);
  }
  for (let i = 0; i < n; i++) {
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) return -1;
    }
  }
  return [a + 1, b + 1].join(' ');
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const [n, m] = (await read()).split(' ').map(Number);
    const a = [];
    let tmp = n;
    while (tmp--) {
      a.push((await read()).split(' ').map(Number));
    }
    res.push(solve(n, m, a));
  }
  console.log(res.join('\n'));
}

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

const comp = (arr,n)=>{
     let sort = [...arr].sort((a,b)=>a-b);
     let res = [],cnt = 0;
     for(let i=0;i<n;i++){
          if(arr[i]!==sort[i]){
               cnt++;
               res.push(i);
          }
          if(cnt===3) return -1;
     }
     if(cnt===0) return 1;
     else return res;
}
const swap = (arr,n,s)=>{
     for(let i=0;i<n;i++) [arr[i][s[0]],arr[i][s[1]]] = [arr[i][s[1]],arr[i][s[0]]]
}
const check = (arr,n,m)=>{
     for(let i=0;i<n;i++){
          for(let j=1;j<m;j++){
               if(arr[i][j-1]>arr[i][j]) return false;
          }
     }
     return true;
}
const solve = (arr,n,m)=>{
     if(m===1) return `1 1`;
     for(let i=0;i<n;i++){
          let s = comp(arr[i],m);
          if(s===-1) return -1;
          if(s===1) continue;
          swap(arr,n,s);
          if(check(arr,n,m)) return `${s[0]+1} ${s[1]+1}`;
          else return -1;
     }
     return `1 1`;
}

function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for (let i = 0; i < t; i++) {
       let [n,m] = readline().trim().split(" ").map(cur=>parseInt(cur));
       let mat = [];
       for(let i=0;i<n;i++){
            mat.push(readline().trim().split(" ").map(cur=>parseInt(cur)));
       }
       console.log(solve(mat,n,m))
  }
}
main();

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const calc = (testN)=>{
  // READING:
  let [n, m] = ra();
  let A = [];
  let SA = [];
  for (let i=0; i<n; i++){
    A.push(ra())
    SA.push(A[i].slice().sort((a, b)=>a-b));
  }
  LT({n, m, A});
  //L(SA.join('\n'))
  // PROCESSING:
  let DIFFS = [];
  let ref_diff;
  for (let i=0; i<n; i++){
    let diffs = [];
    for (let j=0; j<m; j++){
      if (A[i][j]!=SA[i][j])
        diffs.push(j);
    }
    if (diffs.length>2)
      return -1;
    if (diffs.length==2)
      ref_diff = diffs;
    DIFFS.push(diffs);
  }
  if (!ref_diff)
    return '1 1';
  for (let i=0; i<n; i++){
    let diff = DIFFS[i];
    if (diff.length==2){
      if (diff[0]!=ref_diff[0] || diff[1]!=ref_diff[1])
        return -1;
    } else {
      if (SA[i][ref_diff[0]]!=SA[i][ref_diff[1]])
        return -1;
    }
  }
  return `${ref_diff[0]+1} ${ref_diff[1]+1}`;
};

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const calc = ()=>{
    /* read */
    let [n, m] = ra();
    let g = [];
    for (let i = 0; i < n; i++) {
        g.push(ra());
    }

    if (m === 1) return "1 1";

    // console.log('DEBUG g', g);

    let lastIncCol = 0;
    let lastDecCol = m - 1;

    const isInc = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] > g[i][b]) return false;
        }
        return true;
    }

    const isDec = (a, b) => {
        let eqcnt = 0;
        for (let i = 0; i < n; i++) {
            if (g[i][a] < g[i][b]) return false;
            if (g[i][a] === g[i][b]) eqcnt++;
        }
        return eqcnt !== n;
    }

    while (lastIncCol < m - 1 && isInc(lastIncCol, lastIncCol + 1)) lastIncCol++;

    // console.log('DEBUG lastIncCol', lastIncCol);

    if (lastIncCol === m - 1) return "1 1";

    while (lastDecCol > 0 && isDec(lastDecCol, lastDecCol - 1)) lastDecCol--;

    // console.log('DEBUG lastDecCol', lastDecCol);

    for (let i = 0; i < n; i++) {
        let tmp = g[i][lastIncCol];
        g[i][lastIncCol] = g[i][lastDecCol];
        g[i][lastDecCol] = tmp;
    }

    for (let i = 0; i < m - 1; i++) {
        if (!isInc(i, i + 1)) return "-1";
    }

    return `${lastIncCol + 1} ${lastDecCol + 1}`;
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const calc = ()=>{
    /* read */
    let [n, m] = ra();
    let g = [];
    let cols = new Array(m);
    let scols = new Array(m);
    let sg = [];
    for (let i = 0; i < n; i++) {
        let row = readline().split(' ');
        g.push(row);
        sg.push([...row]);
    }

    for (let i = 0; i < m; i++) {
        cols[i] = i;
        scols[i] = i;
    }

    if (m === 1) return "1 1";

    const isInc = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] > g[i][b]) return false;
        }
        return true;
    }

    const isDec = (a, b) => {
        let eqcnt = 0;
        for (let i = 0; i < n; i++) {
            if (g[i][a] < g[i][b]) return false;
            if (g[i][a] === g[i][b]) eqcnt++;
        }
        return eqcnt !== n;
    }

    const isEq = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] !== g[i][b]) return false;
        }
        return true;
    }

    for (let i = 0; i < n; i++) {
        sg[i].sort((a, b) => a - b);
    }

    // scols.sort((a, b) => {
    //     if (isEq(a, b)) return 0;
    //     if (isInc(a, b)) return -1;
    //     return 1;
    // });

    // console.log('DEBUG g', g);
    // console.log('DEBUG sg', sg);

    let diffs = new Set();

    for (let i = 0; i < n; i++){
        for (let j = 0; j < m; j++) {
            if (g[i][j] !== sg[i][j]) diffs.add(j);
        }
    }

    // console.log('DEBUG diffs', diffs);

    diffs = Array.from(diffs);

    if (diffs.length > 2) return "-1";

    if (diffs.length === 2) {
        for (let i = 0; i < n; i++) {
            let tmp = g[i][diffs[0]];
            g[i][diffs[0]] = g[i][diffs[1]];
            g[i][diffs[1]] = tmp;
        }
    }

    // console.log('DEBUG g', g);

    for (let i = 0; i < n; i++){
        for (let j = 0; j < m - 1; j++) {
            if (g[i][j] > g[i][j + 1]) return "-1";
        }
    }

    return diffs.length === 2 ? `${diffs[0] + 1} ${diffs[1] + 1}` : "1 1";

};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const calc = ()=>{
    /* read */
    let [n, m] = ra();
    let g = [];
    let cols = new Array(m);
    let scols = new Array(m);
    let sg = [];
    for (let i = 0; i < n; i++) {
        let row = readline().split(' ');
        g.push(row);
        sg.push([...row]);
    }

    for (let i = 0; i < m; i++) {
        cols[i] = i;
        scols[i] = i;
    }

    if (m === 1) return "1 1";

    const isInc = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] > g[i][b]) return false;
        }
        return true;
    }

    const isDec = (a, b) => {
        let eqcnt = 0;
        for (let i = 0; i < n; i++) {
            if (g[i][a] < g[i][b]) return false;
            if (g[i][a] === g[i][b]) eqcnt++;
        }
        return eqcnt !== n;
    }

    const isEq = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] !== g[i][b]) return false;
        }
        return true;
    }

    for (let i = 0; i < n; i++) {
        sg[i].sort((a, b) => a - b);
    }

    // scols.sort((a, b) => {
    //     if (isEq(a, b)) return 0;
    //     if (isInc(a, b)) return -1;
    //     return 1;
    // });

    // console.log('DEBUG sg', sg);

    let diffs = new Set();

    for (let i = 0; i < n; i++){
        for (let j = 0; j < m; j++) {
            if (g[i][j] !== sg[i][j]) diffs.add(j);
            if (diffs.size > 2) return "-1";
        }
    }

    diffs = Array.from(diffs);

    if (diffs.length !== 2 && diffs.length !== 0) return "-1";

    if (diffs.length === 2) {
        // console.log('DEBUG diffs', diffs);
        for (let i = 0; i < n; i++) {
            let tmp = g[i][diffs[0]];
            g[i][diffs[0]] = g[i][diffs[1]];
            g[i][diffs[1]] = tmp;
        }
    }

    for (let i = 0; i < n; i++){
        for (let j = 0; j < m - 1; j++) {
            if (g[i][j] > g[i][j + 1]) return "-1";
        }
    }

    return diffs.length === 2 ? `${diffs[0] + 1} ${diffs[1] + 1}` : "1 1";

};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const calc = ()=>{
    /* read */
    let [n, m] = ra();
    let g = [];
    let cols = new Array(m);
    let scols = new Array(m);
    let sg = [];
    for (let i = 0; i < n; i++) {
        let row = readline().split(' ');
        g.push(row);
        sg.push([...row]);
    }

    for (let i = 0; i < m; i++) {
        cols[i] = i;
        scols[i] = i;
    }

    if (m === 1) return "1 1";

    const isInc = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] > g[i][b]) return false;
        }
        return true;
    }

    const isDec = (a, b) => {
        let eqcnt = 0;
        for (let i = 0; i < n; i++) {
            if (g[i][a] < g[i][b]) return false;
            if (g[i][a] === g[i][b]) eqcnt++;
        }
        return eqcnt !== n;
    }

    const isEq = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] !== g[i][b]) return false;
        }
        return true;
    }

    for (let i = 0; i < n; i++) {
        sg[i].sort((a, b) => a - b);
    }

    // scols.sort((a, b) => {
    //     if (isEq(a, b)) return 0;
    //     if (isInc(a, b)) return -1;
    //     return 1;
    // });

    // console.log('DEBUG sg', sg);

    let diffs = new Set();

    for (let i = 0; i < n; i++){
        for (let j = 0; j < m; j++) {
            if (g[i][j] !== sg[i][j]) diffs.add(j);
            if (diffs.size > 2) return "-1";
        }
    }

    diffs = Array.from(diffs);

    if (diffs.length !== 2 && diffs.length !== 0) return "-1";

    if (diffs.length === 2) {
        for (let i = 0; i < n; i++) {
            let tmp = g[i][diffs[0]];
            g[i][diffs[0]] = g[i][diffs[1]];
            g[i][diffs[1]] = tmp;
        }
    }

    for (let i = 0; i < m - 1; i++) {
        if (!isInc(i, i + 1)) return "-1";
    }

    return diffs.length === 2 ? `${diffs[0] + 1} ${diffs[1] + 1}` : "1 1";

};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const calc = ()=>{
    /* read */
    let [n, m] = ra();
    let g = [];
    let cols = new Array(m);
    let scols = new Array(m);
    let sg = [];
    for (let i = 0; i < n; i++) {
        let row = readline().split(' ');
        g.push(row);
        sg.push([...row]);
    }

    for (let i = 0; i < m; i++) {
        cols[i] = i;
        scols[i] = i;
    }

    if (m === 1) return "1 1";

    const isInc = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] > g[i][b]) return false;
        }
        return true;
    }

    const isDec = (a, b) => {
        let eqcnt = 0;
        for (let i = 0; i < n; i++) {
            if (g[i][a] < g[i][b]) return false;
            if (g[i][a] === g[i][b]) eqcnt++;
        }
        return eqcnt !== n;
    }

    const isEq = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] !== g[i][b]) return false;
        }
        return true;
    }

    scols.sort((a, b) => {
        if (isEq(a, b)) return 0;
        if (isInc(a, b)) return -1;
        return 1;
    });

    // console.log('DEBUG scols', scols);

    let diffs = [];

    for (let i = 0; i < m; i++) {
        if (cols[i] !== scols[i]) diffs.push(i);
        if (diffs.length > 2) return "-1";
    }

    if (diffs.length !== 2 && diffs.length !== 0) return "-1";

    if (diffs.length === 2) {
        for (let i = 0; i < n; i++) {
            let tmp = g[i][diffs[0]];
            g[i][diffs[0]] = g[i][diffs[1]];
            g[i][diffs[1]] = tmp;
        }
    }

    for (let i = 0; i < m - 1; i++) {
        if (!isInc(i, i + 1)) return "-1";
    }

    return diffs.length === 2 ? `${diffs[0] + 1} ${diffs[1] + 1}` : "1 1";

};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const calc = ()=>{
    /* read */
    let [n, m] = ra();
    let g = [];
    for (let i = 0; i < n; i++) {
        g.push(readline().split(' '));
    }

    if (m === 1) return "1 1";

    // console.log('DEBUG g', g);

    let lastIncCol = 0;
    let lastDecCol = m - 1;

    const isInc = (a, b) => {
        for (let i = 0; i < n; i++) {
            if (g[i][a] > g[i][b]) return false;
        }
        return true;
    }

    const isDec = (a, b) => {
        let eqcnt = 0;
        for (let i = 0; i < n; i++) {
            if (g[i][a] < g[i][b]) return false;
            if (g[i][a] === g[i][b]) eqcnt++;
        }
        return eqcnt !== n;
    }

    while (lastIncCol < m - 1 && isInc(lastIncCol, lastIncCol + 1)) lastIncCol++;

    // console.log('DEBUG lastIncCol', lastIncCol);

    if (lastIncCol === m - 1) return "1 1";

    while (lastDecCol > 0 && isDec(lastDecCol, lastDecCol - 1)) lastDecCol--;

    // console.log('DEBUG lastDecCol', lastDecCol);

    for (let i = 0; i < n; i++) {
        let tmp = g[i][lastIncCol];
        g[i][lastIncCol] = g[i][lastDecCol];
        g[i][lastDecCol] = tmp;
    }

    for (let i = 0; i < m - 1; i++) {
        if (!isInc(i, i + 1)) return "-1";
    }

    return `${lastIncCol + 1} ${lastDecCol + 1}`;
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

'use strict';

var readline = require('readline');

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

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

function solve(n, m, grid) {
  let res = [];
  const swap = (i, j, k) => [grid[i][j], grid[i][k]] = [grid[i][k], grid[i][j]];
  for (let i = 0; i < n; i++) {
    let a = -1,
        b = -1;
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) {
        let t = j - 1;
        for (let k = j - 1; k >= 0; k--) {
          if (nums[k] === nums[j - 1]) t = k;
        }
        if (t === j - 1) {
          let t1 = j;
          for (let k = j + 1; k < m; k++) {
            if (nums[k] === nums[j]) t1 = k;
          }
          if (t1 === j) {
            if (nums[j + 1] < nums[j]) {
              [a, b] = [t, j + 1];
            } else {
              [a, b] = [t, j];
            }
          } else {
            [a, b] = [t, t1];
          }
        } else {
          [a, b] = [t, j];
        }
        break;
      }
    }
    if (a !== -1) {
      res.push([a, b]);
      break;
    }
  }
  if (!res.length) return `1 1`;
  const [a, b] = res[0];
  for (let i = 0; i < n; i++) {
    if (grid[i][a] < grid[i][b]) return -1;
    swap(i, a, b);
  }
  for (let i = 0; i < n; i++) {
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) return -1;
    }
  }
  return [a + 1, b + 1].join(' ');
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const [n, m] = (await read()).split(' ').map(Number);
    const a = [];
    let tmp = n;
    while (tmp--) {
      a.push((await read()).split(' ').map(Number));
    }
    res.push(solve(n, m, a));
  }
  console.log(res.join('\n'));
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, m, grid) {
  let res = [];
  const swap = (i, j, k) => [grid[i][j], grid[i][k]] = [grid[i][k], grid[i][j]];
  for (let i = 0; i < n; i++) {
    let a = -1,
        b = -1;
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) {
        let t = j - 1;
        while (nums[t - 1] === nums[j - 1]) {
          t--;
        }
        if (t === j - 1) {
          let t1 = j;
          for (let k = j + 1; k < m; k++) {
            if (nums[k] === nums[j]) t1 = k;
          }
          if (t1 === j) {
            if (nums[j + 1] < nums[j]) {
              [a, b] = [t, j + 1];
            } else {
              [a, b] = [t, j];
            }
          } else {
            [a, b] = [t, t1];
          }
        } else {
          [a, b] = [t, j];
        }
        break;
      }
    }
    if (a !== -1) {
      res.push([a, b]);
      break;
    }
  }
  if (!res.length) return `1 1`;
  const [a, b] = res[0];
  for (let i = 0; i < n; i++) {
    if (grid[i][a] < grid[i][b]) return -1;
    swap(i, a, b);
  }
  for (let i = 0; i < n; i++) {
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) return -1;
    }
  }
  return [a + 1, b + 1].join(' ');
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const [n, m] = (await read()).split(' ').map(Number);
    const a = [];
    let tmp = n;
    while (tmp--) {
      a.push((await read()).split(' ').map(Number));
    }
    res.push(solve(n, m, a));
  }
  console.log(res.join('\n'));
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, m, grid) {
  let res = [];
  const swap = (i, j, k) => [grid[i][j], grid[i][k]] = [grid[i][k], grid[i][j]];
  for (let i = 0; i < n; i++) {
    let index = [-1, -1];
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) {
        let t = j - 1;
        while (nums[t - 1] === nums[t]) {
          t--;
        }
        if (t === j - 1) {
          let t1 = j;
          while (nums[t1 + 1] === nums[j]) {
            t1++;
          }
          if (t1 === j) {
            if (nums[j + 1] < nums[j]) {
              index = [t, j + 1];
            } else {
              index = [t, j];
            }
          } else {
            index = [j - 1, t1];
          }
        } else {
          index = [t, j];
        }
        break;
      }
    }
    if (index[0] !== -1) {
      res.push(index);
      break;
    }
  }
  if (!res.length) return `1 1`;
  const [a, b] = res[0];
  for (let i = 0; i < n; i++) {
    if (grid[i][a] < grid[i][b]) return -1;
    swap(i, a, b);
  }
  for (let i = 0; i < n; i++) {
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) return -1;
    }
  }
  return [a + 1, b + 1].join(' ');
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const [n, m] = (await read()).split(' ').map(Number);
    const a = [];
    let tmp = n;
    while (tmp--) {
      a.push((await read()).split(' ').map(Number));
    }
    res.push(solve(n, m, a));
  }
  console.log(res.join('\n'));
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, m, grid) {
  let res = [];
  const swap = (i, j, k) => [grid[i][j], grid[i][k]] = [grid[i][k], grid[i][j]];
  for (let i = 0; i < n; i++) {
    let index = [-1, -1];
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) {
        if (j > 2 && nums[j] < nums[j - 3]) return -1;
        if (j < m - 2 && nums[j - 1] > nums[j + 2]) return -1;
        if (j > 1 && nums[j - 1] === nums[j - 2]) {
          if (nums[j - 1] > nums[j + 1]) return -1;
          index = [j - 2, j];
        } else if (nums[j] >= nums[j + 1]) {
          if (j > 1 && nums[j + 1] < nums[j - 2]) return -1;
          index = [j - 1, j + 1];
        } else {
          if (nums[j - 1] > nums[j + 1]) return -1;
          index = [j - 1, j];
        }
        break;
      }
    }
    if (index[0] !== -1) {
      res.push(index);
      break;
    }
  }
  if (!res.length) return `1 1`;
  const [a, b] = res[0];
  for (let i = 0; i < n; i++) {
    if (grid[i][a] < grid[i][b]) return -1;
    swap(i, a, b);
  }
  for (let i = 0; i < n; i++) {
    for (let j = 1; j < m; j++) {
      const nums = grid[i];
      if (nums[j] < nums[j - 1]) return -1;
    }
  }
  return [a + 1, b + 1].join(' ');
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const [n, m] = (await read()).split(' ').map(Number);
    const a = [];
    let tmp = n;
    while (tmp--) {
      a.push((await read()).split(' ').map(Number));
    }
    res.push(solve(n, m, a));
  }
  console.log(res.join('\n'));
}

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

const swap = (arr,c1,c2,n,m)=>{
     for(let i=0;i<n;i++){
          [arr[i][c1],arr[i][c2]] = [arr[i][c2],arr[i][c1]];
     }
}
const check = (arr,n,m)=>{
     for(let i=0;i<n;i++){
          for(let j=0;j<m-1;j++){
               if(arr[i][j]>arr[i][j+1]) return false;
          }
     }
     return true;
}
const solve = (arr,n,m)=>{
     if(m===1) return `1 1`;
     let c1 = 0,c2 = 0;
     for(let i=0;i<n;i++){
          let cnt = 0;
          for(let j=1;j<m;j++){
               if(arr[i][j-1]>arr[i][j]){
                    cnt++;
                    c1 = cnt===1 ? j-1 : c1;
                    c2 = j;
               }
          }
          if(cnt===3) return -1;
          if((c1!==0)||(c2!==0)){
               swap(arr,c1,c2,n,m);
               if(check(arr,n,m)) return `${c1+1} ${c2+1}`;
               else return -1;
          }
     }
     return `1 1`;
}

function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for (let i = 0; i < t; i++) {
       let [n,m] = readline().trim().split(" ").map(cur=>parseInt(cur));
       let mat = [];
       for(let i=0;i<n;i++){
            mat.push(readline().trim().split(" ").map(cur=>parseInt(cur)));
       }
       console.log(solve(mat,n,m))
  }
}
main();


Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li.You are given lengths of the claws. You need to find the total number of alive people after the bell rings.

The first line contains one integer n (1 ≤ n ≤ 106) — the number of guilty people. Second line contains n space-separated integers L1, L2, ..., Ln (0 ≤ Li ≤ 109), where Li is the length of the i-th person's claw.

Print one integer — the total number of alive people after the bell rings.

NoteIn first sample the last person kills everyone in front of him.

var n = parseInt(readline());
var vivos=0;
var array2 = readline().split(' ');
for(var i = 0; i < n ; i++){
	array2[i]= parseInt(array2[i]);
}
var ultimo=n-1;
for(var i = n-1; i >=0  ;i--){
	 if (i === ultimo) {
        vivos++;
    }
    ultimo = Math.min(ultimo, i - array2[i] - 1);
}
print(vivos);

n = +readline();
l = readline().split(" ").map(Number);
ans = 0;
cmp = n;
for (i = n - 1; i >= 0; i--) {
  if (i < cmp)
    ans++;
  cmp = Math.min(cmp, i - l[i]);
}
print(ans);

const count = readline();
const claws = readline().split(' ').map(v=> parseInt(v));

var alive = 0;
var lastAlive = claws.length - 1;

for (var killer = claws.length - 1; killer >= 0; killer--) {
    if (killer === lastAlive) {
        alive++;
    }
    lastAlive = Math.min(lastAlive, killer - claws[killer] - 1);
}

print(alive);

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

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

process.stdin.on('end', () => {
  arr = arr.split('\n')
  const n = parseInt(arr.shift())
  const claw = arr.shift().split(' ')

  var count = 1
  var last = n - 1
  for(let i = n - 1; i >= 0; i --) {
    // console.log(i, claw[i], last, count)
    if(i < last) count ++
    if(i - claw[i] <= last && claw[i] != 0) last = i - claw[i]
  }
  console.log(count)
})

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const n = readline();
  const l = readline().split(' ').map(Number);
  helper(n, l);
}

function helper(n, l) {
    let killNum = n
    let alive = 0
    for (let i = n - 1; i >= 0; i--) {
        if (i < killNum) alive++
        killNum = Math.min(killNum, i - l[i])
    }

    console.log(alive + '')
}

n = +readline();
l = readline().split().map(Number);
ans = 0
cmp = n
for (i = n - 1; i >= 0; i--) {
  if (i < cmp)
    ans++;
  cmp = Math.min(cmp, i - l[i]);
}
print(ans)

const count = readline();
const claws = readline().split(' ').map(v=> parseInt(v));

var alive = 0;
var lastAlive = claws.length - 1;

for (var killer = claws.length - 1; killer >= 0; killer--) {
    print(lastAlive);

    if (killer === lastAlive) {
        alive++;
    }

    lastAlive = Math.min(lastAlive, killer - claws[killer] - 1);
}

print(alive);

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const n = readline();
  const l = readline().split(' ').map(Number);
  helper(n, l);
}

function helper(n, l) {
    let killed = new Set()
    for (let i = n - 1; i >= 0; i--) {
        for (let j = 1; j <= l[i]; j++) {
            killed.add(i - j)
        }
        if (killed.size === n - 1) {
            console.log('1')
            return
        }
    }

    console.log((n - killed.size) + '')
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const n = readline();
  const l = readline().split(' ').map(Number);
  helper(n, l);
}

function helper(n, l) {
    let killed = new Set()
    for (let i = n - 1; i >= 0; i--) {
        if (l[i] >= i) {
            if (i === n - 1) {
                console.log('1')
                return;
            }
            break;
        }
        for (let j = 1; j <= l[i] && j <= i; j++) {
            killed.add(i - j)
        }
        if (killed.size >= n - 1) {
            console.log('1')
            return
        }
    }

    console.log((n - killed.size) + '')
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const n = readline();
  const l = readline().split(' ').map(Number);
  helper(n, l);
}

function helper(n, l) {
    let killed = new Set()
    for (let i = n - 1; i >= 0; i--) {
        if (l[i] >= i) {
            if (i === n - 1) {
                console.log('1')
            } else {
                console.log((n - killed.size - i + 1) + '')
            }
            return

        }
        for (let j = 1; j <= l[i] && j <= i; j++) {
            killed.add(i - j)
        }
    }

    console.log((n - killed.size) + '')
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const n = readline();
  const l = readline().split(' ').map(Number);
  helper(n, l);
}

function helper(n, l) {
    let killed = new Set()
    for (let i = n - 1; i >= 0; i--) {
        if (l[i] >= i) {
            if (i === n - 1) {
                console.log('1')
            } else {
                console.log((n - killed.size - i) + '')
            }
            return

        }
        for (let j = 1; j <= l[i] && j <= i; j++) {
            killed.add(i - j)
        }
    }

    console.log((n - killed.size) + '')
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

// Make a Snippet for the code above this and then write your logic in main()
function main() {
  const n = readline();
  const l = readline().split(' ').map(Number);
  helper(n, l);
}

function helper(n, l) {
    let killed = new Set()
    for (let i = n - 1; i >= 0; i--) {
        if (l[i] >= i) {
            if (i === n - 1) {
                console.log('1')
                return
            } else {
                console.log((n - killed.size - i) + '')
            }

        }
        for (let j = 1; j <= l[i] && j <= i; j++) {
            killed.add(i - j)
        }
    }

    console.log((n - killed.size) + '')
}