Burenka is about to watch the most interesting sporting event of the year — a fighting tournament organized by her friend Tonya.$$$n$$$ athletes participate in the tournament, numbered from $$$1$$$ to $$$n$$$. Burenka determined the strength of the $$$i$$$-th athlete as an integer $$$a_i$$$, where $$$1 \leq a_i \leq n$$$. All the strength values are different, that is, the array $$$a$$$ is a permutation of length $$$n$$$. We know that in a fight, if $$$a_i > a_j$$$, then the $$$i$$$-th participant always wins the $$$j$$$-th.The tournament goes like this: initially, all $$$n$$$ athletes line up in ascending order of their ids, and then there are infinitely many fighting rounds. In each round there is exactly one fight: the first two people in line come out and fight. The winner goes back to the front of the line, and the loser goes to the back.Burenka decided to ask Tonya $$$q$$$ questions. In each question, Burenka asks how many victories the $$$i$$$-th participant gets in the first $$$k$$$ rounds of the competition for some given numbers $$$i$$$ and $$$k$$$. Tonya is not very good at analytics, so he asks you to help him answer all the questions.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq q \leq 10^5$$$) — the number of tournament participants and the number of questions. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the array $$$a$$$, which is a permutation. The next $$$q$$$ lines of a test case contain questions. Each line contains two integers $$$i$$$ and $$$k$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq k \leq 10^9$$$) — the number of the participant and the number of rounds. It is guaranteed that the sum of $$$n$$$ and the sum of $$$q$$$ over all test cases do not exceed $$$10^5$$$.

For each Burenka's question, print a single line containing one integer — the answer to the question.

NoteIn the first test case, the first numbered athlete has the strength of $$$3$$$, in the first round he will defeat the athlete with the number $$$2$$$ and the strength of $$$1$$$, and in the second round, the athlete with the number $$$3$$$ and the strength of $$$2$$$.In the second test case, we list the strengths of the athletes fighting in the first $$$5$$$ fights: $$$1$$$ and $$$3$$$, $$$3$$$ and $$$4$$$, $$$4$$$ and $$$2$$$, $$$4$$$ and $$$1$$$, $$$4$$$ and $$$3$$$. The participant with the number $$$4$$$ in the first $$$5$$$ rounds won $$$0$$$ times (his strength is $$$2$$$). The participant with the number $$$3$$$ has a strength of $$$4$$$ and won $$$1$$$ time in the first two fights by fighting $$$1$$$ time.

const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const [n, q] = input[index].split(" ").map((item) => parseInt(item));
    index++;
    const a = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      q,
      a,
      i: [],
      k: [],
    };
    for (let j = 0; j < q; j++) {
      index++;
      const [i, k] = input[index].split(" ").map((item) => parseInt(item));
      testCase.i.push(i);
      testCase.k.push(k);
    }
    testCases.push(testCase);
  }
}

function solution(testCase) {
  const { n, q, a, i, k } = testCase;
  // console.log(n, q, a, i, k);

  const winners = new Array(n + 1).fill(0).map((_) => []);
  let maxi = a[0];

  for (let j = 1; j < n; j++) {
    const val = a[j];

    if (val > maxi) {
      if (maxi && j > 1) winners[maxi].push(j - 1);
      maxi = val;
    }
    if (winners[maxi][0] == undefined) winners[maxi].push(j);
  }

  // console.log(winners);

  for (let j = 0; j < q; j++) {
    const ii = i[j];
    const kk = k[j];
    const val = a[ii - 1];

    const [startWin, endWin] = winners[val];
    // console.error(ii, val, kk, startWin, endWin);
    if (startWin == undefined) console.log(0);
    else {
      console.log(
        Math.max(
          0,
          Math.min(kk, endWin == undefined ? Infinity : endWin) - startWin + 1
        )
      );
    }

    // console.error("-----");
  }
}

parseInput();

testCases.forEach(solution);

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, q] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))
        l += q
        output[i] = solve(n, arr, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr, qs) {
    const win = Array(n + 1)
    let f = arr[0]
    for (let i = 1; i < arr.length; i++) {
        const x = arr[i]
        if (f < x) {
            f = x
        }
        win[f] = win[f] || []
        win[f].push(i)
        if (f === n) break
    }
// console.log(win)
    return qs.map(([i, k]) => {
        const x = arr[i - 1]
        const lst = win[x] || []
        let r = binarySearch(0, lst.length - 1, idx => lst[idx] <= k)
        if (x === n && k >= win[f]) {
            r += k - win[f]
        }
        return r + 1
    }).join('\n')
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

'use strict';

function solve(n, m, a, b) {
  const l = new Array(n).fill(0),
        r = new Array(n).fill(0);
  let max = -1;
  for (let i = 0; i < n; i++) {
    if (max === -1 || a[max] < a[i]) {
      max = i;
    } else {
      l[i] = 1;
    }
  }
  {
    const stack = [];
    for (let i = n - 1; i >= 0; i--) {
      while (stack.length && a[stack[stack.length - 1]] < a[i]) stack.pop();
      if (stack.length) r[i] = stack[stack.length - 1];
      stack.push(i);
    }
  }
  const res = [];
  for (let [i, k] of b) {
    i--;
    if (k < i || l[i]) {
      res.push(0);
    } else if (!r[i]) {
      res.push(k - i + (i ? 1 : 0));
    } else {
      let ans = 0;
      k -= i;
      if (i) ans = 1;
      res.push(Math.min(k, r[i] - i - 1) + ans);
    }
  }
  return res.join('\n');
}

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

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

class Record {
    constructor(id, start) {
        this.id = id;
        this.start = start;
    }

    lose(end) {
        this.end = end;
    }

    get(rounds) {
        if (rounds >= this.start) {
            return Math.min(this.end, (rounds + 1)) - this.start;
        } else {
            return 0;
        }
    }
}

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

    for (let test = 0; test < N; test++) {
        const [n, q] = readline().split(' ').map(Number);
        const arr = readline().split(' ').map(Number);

        const str = {};
        let maxId = -1;
        arr.forEach((val, i) => {
            str[i + 1] = val;
            if (val === n) {
                maxId = i + 1;
            }
        });

        const data = {};
        let first = 1;
        let curr = new Record(1, 1);
        data[1] = curr;

        for (let i = 2; i <= n; i++) {
            if (str[i] === n) {
                curr.lose(i - 1);
                break;
            }
            if (str[i] > str[first]) {
                first = i;
                curr.lose(i - 1);
                curr = new Record(i, i - 1);
                data[i] = curr;
            } else if (i === n) {
                curr.lose(i);
            }
        }

        for (let question = 0; question < q; question++) {
            const [i, k] = readline().split(' ').map(Number);

            if (i === maxId) {
                if (maxId < 3) {
                    output(k);
                } else {
                    output(Math.max((k - i + 2), 0));
                }
            } else if (!data[i]) {
                output(0);
            } else {
                output(data[i].get(k));
            }
        }
    }
}

var n, Q, a;

    var tests = parseInt(readline());
    for (var t=0; t<tests;t++) {
        var nq = readline().split(' ').map(x=>parseInt(x));
        n = nq[0];
        Q = nq[1];
        a = readline().split(' ').map(x=>parseInt(x));
        var wins = new Array(n).fill(0);
        var ind = 1;
        var curr = [0, a[0]];
        while (curr[1] != n) {
            if (a[ind] > curr[1]) {
                curr = [ind, a[ind]];
            }
            wins[curr[0]]++;
            ind++;
        }
        for (var q = 0; q < Q; q++) {
            var ik = readline().split(' ').map(x=>parseInt(x));
            var i = ik[0];
            var k = ik[1];
            if (k < i-1) {
                print(0);
                continue;
            }
            var ans = 0;
            if (curr[0]+1 == i) {
                ans = k - i + 2;
                if (i == 1) {
                    ans--;
                }
            } else {
                if (wins[i-1]) {
                    if (i == 1) {
                        ans = Math.min(k - i + 1, wins[i-1]);
                    } else {
                        ans = Math.min(k - i + 2, wins[i-1]);
                    }
                }
            }
            print(ans);
        }
    }

const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const [n, q] = input[index].split(" ").map((item) => parseInt(item));
    index++;
    const a = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      q,
      a,
      i: [],
      k: [],
    };
    for (let j = 0; j < q; j++) {
      index++;
      const [i, k] = input[index].split(" ").map((item) => parseInt(item));
      testCase.i.push(i);
      testCase.k.push(k);
    }
    testCases.push(testCase);
  }
}

function solution(testCase) {
  const { n, q, a, i, k } = testCase;
  // console.log(n, q, a, i, k);

  const winners = new Array(n + 1).fill(0).map((_) => []);
  let maxi = a[0];

  for (let j = 1; j < n; j++) {
    const val = a[j];

    if (val > maxi) {
      if (maxi && j > 1) winners[maxi].push(j - 1);
      maxi = val;
    }
    if (winners[maxi][0] == undefined) winners[maxi].push(j);
  }

  // console.log(winners);

  for (let j = 0; j < q; j++) {
    const ii = i[j];
    const kk = k[j];
    const val = a[ii - 1];

    const [startWin, endWin] = winners[val];
    // console.error(ii, val, kk, startWin, endWin);
    if (startWin == undefined) console.log(0);
    else {
      console.log(
        Math.min(kk, endWin == undefined ? Infinity : endWin) - startWin + 1
      );
    }

    // console.error("-----");
  }
}

parseInput();

testCases.forEach(solution);

const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const [n, q] = input[index].split(" ").map((item) => parseInt(item));
    index++;
    const a = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      q,
      a,
      i: [],
      k: [],
    };
    for (let j = 0; j < q; j++) {
      index++;
      const [i, k] = input[index].split(" ").map((item) => parseInt(item));
      testCase.i.push(i);
      testCase.k.push(k);
    }
    testCases.push(testCase);
  }
}

function solution(testCase) {
  const { n, q, a, i, k } = testCase;
  // console.log(n, q, a, i, k);

  const winners = new Array(n + 1).fill(0).map((_) => []);
  let maxi = a[0];

  for (let j = 1; j < n; j++) {
    const val = a[j];

    if (val > maxi) {
      if (maxi) winners[maxi].push(j - 1);
      maxi = val;
    }
    if (winners[maxi][0] == undefined) winners[maxi].push(j);
  }

  // console.log(winners);

  for (let j = 0; j < q; j++) {
    const ii = i[j];
    const kk = k[j];
    const val = a[ii - 1];

    const [startWin, endWin] = winners[val];
    // console.error(ii, val, kk, startWin, endWin);
    if (startWin == undefined) console.log(0);
    else {
      console.log(
        Math.min(kk, endWin == undefined ? Infinity : endWin) - startWin + 1
      );
    }

    //   console.log(result);
    // console.error("-----");
  }
}

parseInput();

testCases.forEach(solution);

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, q] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))
        l += q
        output[i] = solve(n, arr, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr, qs) {
    const win = Array(n + 1)
    let f = arr[0]
    for (let i = 1; i < arr.length; i++) {
        const x = arr[i]
        if (f < x) {
            f = x
        }
        win[f] = win[f] || []
        win[f].push(i)
        if (f === n) break
    }
// console.log(win)
    return qs.map(([i, k]) => {
        const x = arr[i - 1]
        const lst = win[x] || []
        let r = binarySearch(0, lst.length - 1, idx => lst[idx] <= k)
        if (x === n) {
            r += k - win[f]
        }
        return r + 1
    }).join('\n')
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

'use strict';

function solve(n, m, a, b) {
  const l = new Array(n).fill(0),
        r = new Array(n).fill(n);
  let max = -1;
  for (let i = 0; i < n; i++) {
    if (max === -1 || a[max] < a[i]) {
      max = i;
    } else {
      l[i] = 1;
    }
  }
  {
    const stack = [];
    for (let i = n - 1; i >= 0; i--) {
      while (stack.length && stack[stack.length - 1] < a[i]) stack.pop();
      if (stack.length) r[i] = stack[stack.length - 1];
      stack.push(i);
    }
  }
  const res = [];
  for (let [i, k] of b) {
    i--;
    if (k < i || l[i]) {
      res.push(0);
    } else if (r[i] === n) {
      res.push(k - i + (i ? 1 : 0));
    } else if (i < k) {
      let ans = 0;
      k -= i;
      if (i) ans = 1;
      res.push(Math.min(k, r[i] - i - 1) + ans);
    }
  }
  return res.join('\n');
}

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

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


You are given a set of $$$n$$$ ($$$n$$$ is always a power of $$$2$$$) elements containing all integers $$$0, 1, 2, \ldots, n-1$$$ exactly once.Find $$$\frac{n}{2}$$$ pairs of elements such that:  Each element in the set is in exactly one pair.  The sum over all pairs of the bitwise AND of its elements must be exactly equal to $$$k$$$. Formally, if $$$a_i$$$ and $$$b_i$$$ are the elements of the $$$i$$$-th pair, then the following must hold: $$$$$$\sum_{i=1}^{n/2}{a_i \& b_i} = k,$$$$$$ where $$$\&$$$ denotes the bitwise AND operation. If there are many solutions, print any of them, if there is no solution, print $$$-1$$$ instead.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 400$$$) — the number of test cases. Description of the test cases follows. Each test case consists of a single line with two integers $$$n$$$ and $$$k$$$ ($$$4 \leq n \leq 2^{16}$$$, $$$n$$$ is a power of $$$2$$$, $$$0 \leq k \leq n-1$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2^{16}$$$. All test cases in each individual input will be pairwise different.

For each test case, if there is no solution, print a single line with the integer $$$-1$$$. Otherwise, print $$$\frac{n}{2}$$$ lines, the $$$i$$$-th of them must contain $$$a_i$$$ and $$$b_i$$$, the elements in the $$$i$$$-th pair.  If there are many solutions, print any of them. Print the pairs and the elements in the pairs in any order.

NoteIn the first test, $$$(0\&3)+(1\&2) = 0$$$.In the second test, $$$(0\&2)+(1\&3) = 1$$$.In the third test, $$$(0\&1)+(2\&3) = 2$$$.In the fourth test, there is no solution.

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();

		if (n == 4 & k == 3) {
			console.log(-1);
			continue;
		}

		if (k == 0) {
			for (let i = 0; i < n/2; i++) {
				console.log(i, n-1-i);
			}
		} else if (k < n-1) {
			console.log(k, n-1);
			console.log(n-1-k, 0);
			for (let i = 0; i < n/2; i++) {
				if (i == 0 || i == k || i == n-1-k) continue;
				console.log(i, n-1-i);
			}
		} else {
			console.log(n-1, n-2);
			console.log(1, 3);
			console.log(0, n-1-3);
			for (let i = 0; i < n/2; i++) {
				if (i == 0 || i == 1 || i == 3) continue;
				console.log(i, n-1-i);
			}
		}
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();

		if (n == 4 & k == 3) {
			console.log(-1);
			continue;
		}

		if (k != n-1) {
			console.log(k, n-1);
			k && console.log(n-1-k, 0);
			for (let i = 0; i < n/2; i++) {
				if (i == 0 || i == k || i == n-1-k) continue;
				console.log(i, n-1-i);
			}
		} else {
			console.log(n-1, n-2);
			console.log(1, 3);
			console.log(0, n-1-3);
			for (let i = 0; i < n/2; i++) {
				if (i == 0 || i == 1 || i == 3) continue;
				console.log(i, n-1-i);
			}
		}
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();

		if (n == 4 & k == 3) {
			console.log(-1);
			continue;
		}

		if (k != n-1) {
			console.log(k, n-1);
			k && console.log(n-1-k, 0);
			for (let i = 0; i < n/2; i++) {
				if (i == 0 || i == k || i == n-1-k) continue;
				console.log(i, n-1-i);
			}
		} else {
			console.log(n-1, n-2);
			console.log(1, 3);
			console.log(0, n-1-3);
			for (let i = 0; i < n/2; i++) {
				if (i == 0 || i == 1 || i == 2 || i == 3) continue;
				console.log(i, n-1-i);
			}
		}
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();

		if (n == 4 & k == 3) {
			console.log(-1);
			continue;
		}

		if (k != n-1) {
			console.log(k, n-1);
			k && console.log(n-1-k, 0);
			for (let i = 0; i < n/2; i++) {
				if (i == 0 || i == k || i == n-1-k) continue;
				console.log(i, n-1-i);
			}
		} else {
			console.log(n-1, n-2);
			console.log(1, 3);
			console.log(0, n-1-3);
			for (let i = 0; i < n/2; i++) {
				if (i == 0 || i == 1 || i == 2) continue;
				console.log(i, n-1-i);
			}
		}
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();

		if (n == 4 & k == 3) {
			console.log(-1);
			continue;
		}

		if (k != n-1) {
			console.log(k, n-1);
			console.log(n-1-k, 0);
			for (let i = 0; i < n/2; i++) {
				if (n == 0 || n == k || n == n-1-k) continue;
				console.log(i, n-1-i);
			}
		} else {
			console.log(n-1, n-2);
			console.log(1, 3);
			console.log(0, n-1-3);
			for (let i = 0; i < n/2; i++) {
				if (n == 0 || n == 1 || n == 2) continue;
				console.log(i, n-1-i);
			}
		}
	}
}


You are given a directed graph consisting of $$$n$$$ vertices. Each directed edge (or arc) labeled with a single character. Initially, the graph is empty.You should process $$$m$$$ queries with it. Each query is one of three types:   "$$$+$$$ $$$u$$$ $$$v$$$ $$$c$$$" — add arc from $$$u$$$ to $$$v$$$ with label $$$c$$$. It's guaranteed that there is no arc $$$(u, v)$$$ in the graph at this moment;  "$$$-$$$ $$$u$$$ $$$v$$$" — erase arc from $$$u$$$ to $$$v$$$. It's guaranteed that the graph contains arc $$$(u, v)$$$ at this moment;  "$$$?$$$ $$$k$$$" — find the sequence of $$$k$$$ vertices $$$v_1, v_2, \dots, v_k$$$ such that there exist both routes $$$v_1 \to v_2 \to \dots \to v_k$$$ and $$$v_k \to v_{k - 1} \to \dots \to v_1$$$ and if you write down characters along both routes you'll get the same string. You can visit the same vertices any number of times.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$1 \le m \le 2 \cdot 10^5$$$) — the number of vertices in the graph and the number of queries. The next $$$m$$$ lines contain queries — one per line. Each query is one of three types:    "$$$+$$$ $$$u$$$ $$$v$$$ $$$c$$$" ($$$1 \le u, v \le n$$$; $$$u \neq v$$$; $$$c$$$ is a lowercase Latin letter);  "$$$-$$$ $$$u$$$ $$$v$$$" ($$$1 \le u, v \le n$$$; $$$u \neq v$$$);  "$$$?$$$ $$$k$$$" ($$$2 \le k \le 10^5$$$).  It's guaranteed that you don't add multiple edges and erase only existing edges. Also, there is at least one query of the third type.

For each query of the third type, print YES if there exist the sequence $$$v_1, v_2, \dots, v_k$$$ described above, or NO otherwise.

NoteIn the first query of the third type $$$k = 3$$$, we can, for example, choose a sequence $$$[1, 2, 3]$$$, since $$$1 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 3$$$ and $$$3 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 1$$$.In the second query of the third type $$$k = 2$$$, and we can't find sequence $$$p_1, p_2$$$ such that arcs $$$(p_1, p_2)$$$ and $$$(p_2, p_1)$$$ have the same characters.In the third query of the third type, we can, for example, choose a sequence $$$[1, 2, 3, 2, 1]$$$, where $$$1 \xrightarrow{\text{a}} 2 \xrightarrow{\text{b}} 3 \xrightarrow{\text{d}} 2 \xrightarrow{\text{c}} 1$$$.

let n, m;

let graph = {};
let countLengthGraph = 0;

let cycle = {};
let countLengthCycle = 0;

let sameChar = {};
let countLengthChar = 0;

const addEdge = ([u, v, c]) => {
  if (!graph[u]) {
    graph[u] = {};
  }
  graph[u][v] = c;
  countLengthGraph++;

  if (graph[v] && graph[v][u]) {
    const x = Math.min(u, v);
    const y = Math.max(u, v);
    if (!cycle[x]) {
      cycle[x] = {};
    }
    cycle[x][y] = true;
    countLengthCycle++;

    if (graph[v][u] === c) {
      if (!sameChar[x]) {
        sameChar[x] = {};
      }
      sameChar[x][y] = true;
      countLengthChar++;
    }
  }
};

const removeEdge = ([u, v]) => {
  delete graph[u][v];
  countLengthGraph--;
  if (Object.keys(graph[u]).length === 0) {
    delete graph[u];
  }

  const x = Math.min(u, v);
  const y = Math.max(u, v);

  if (cycle[x] && cycle[x][y]) {
    delete cycle[x][y];
    countLengthCycle--;
    if (countLengthCycle === 0) {
      delete cycle[x];
    }
  }

  if (sameChar[x] && sameChar[x][y]) {
    delete sameChar[x][y];
    countLengthChar--;
    if (countLengthChar === 0) {
      delete sameChar[x];
    }
  }
};

const query = ([k]) => {
  if (k % 2 === 1) return countLengthCycle !== 0;
  return countLengthChar !== 0;
};

const main = () => {
  [n, m] = readListInt();
  for (let i = 0; i < m; i++) {
    const [q, ...rest] = readLine().split(" ");
    if (q === "+") {
      addEdge(rest);
    } else if (q === "-") {
      removeEdge(rest);
    } else if (q === "?") {
      const res = query(rest);
      console.log(res ? "YES" : "NO");
    }
  }
};

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 => string.trim());
  main();
});

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(s));
};


Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times. Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.

The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.  The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.

In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.  In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.

const reader = require("readline").createInterface({
  input: process.stdin
});

const input = [];

reader.on("line", storeInput);
reader.on("close", submitResult);

function storeInput(line) {
  input.push(line);
}
function submitResult() {
  const result = performCalculation();
  for (let line of result) {
    process.stdout.write(line + "\n");
  }
}
function performCalculation() {
  // Define input values
  const requiredSum = Number(input[0].split(" ")[1]);
  const statistics = input[1].split(" ").map(Number);

  // We can get O(n) solution:
  // iterate over the statistics, starting from 2nd element
  // apply logic to find required maximum for current item

  // from task description: item `n + 1` is always `requiredSum`

  let totalAdded = 0;
  let addition = 0;
  if (statistics.length > 1) {
    for (let i = 1; i < statistics.length; i++) {
      addition = requiredSum - statistics[i - 1] - statistics[i];
      if (addition > 0) {
        statistics[i] += addition;
        totalAdded += addition;
      }
    }
  }

  // answer in required format
  return [totalAdded, statistics.join(" ")];
}

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

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

function main() {
	let [n, k] = readLine()
		.split(' ')
		.map(x => x >> 0);
	let schedules = readLine()
		.split(' ')
		.map(x => x >> 0);

	let b = [];
	let extra = 0;
	b.push(schedules[0]);

	for (let i = 1; i < n; i++) {
		let sum = schedules[i] + schedules[i - 1];
		if (sum >= k) {
			b[i] = schedules[i];
		} else {
			b[i] = schedules[i] + (k - sum);
			schedules[i] = b[i];
			extra += k - sum;
		}
	}

	console.log(extra);
	console.log(b.join(' '));
}

function trips(k, planned) {
    let newPlan = [parseInt(planned[0])];
    let extra = 0;
    for (let i = 1; i < planned.length; i ++) {
        let previous = parseInt(planned[i - 1]);
        let difference = k - (parseInt(planned[i]) + previous);
        if (difference > 0) {
            extra += difference;
            planned[i] = parseInt(planned[i]) + difference;
        }
    }
    return {
        extra,
        newPlan: planned.join(' ')
    }
}

function processData(input) {
    let arr = input.split('\n');
    let numbers = arr[0].split(' ');

    let n = parseInt(numbers[0]);
    let k = parseInt(numbers[1]);

    let data = arr[1].split(' ');
    let answer = trips(k, data);
    console.log(answer.extra);
    console.log(answer.newPlan);
}

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

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

var k = readline().split(' ').map(Number)[1];
var a = readline().split(' ').map(Number);
var sum = a.reduce((a, b) => a + b);
for (var i = 1; i < a.length; i++) {
    a[i] = Math.max(a[i], k - a[i - 1])
}
print(a.reduce((a, b) => a + b) - sum);
print(a.join(' '));

var nk = readline().trim().split(' ').map((x)=>parseInt(x))
var n=nk[0],k=nk[1];

var a = readline().trim().split(' ').map((x)=>parseInt(x))
var b = [a[0]];
var nbr =0;
for(var i=1;i<n;i++){
    nbr+=Math.max(k-(b[i-1]+a[i]),0);
    b[i]=a[i]+Math.max(k-(b[i-1]+a[i]),0);
}
print(nbr)
print(b.join(' '))

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

var given = readIntTabLine(), // n days k walks for two days <500
    plan = readIntTabLine()

/*
for (var i = 0 ; i < given[0] ; i++) {
  plan[i] = parseInt(readline())
}
*///console.log(plan)

var ans = [], ans2 = [], tot = -1, tot2 = 0, start = 0

do {
  tot2 = start
  ans2 = [start + plan[0]]

  for (var i = 1 ; i < given[0] ; i++) {
    if (ans2[i-1] + plan[i] < given[1]) {
      tot2 += given[1] - plan[i] - ans2[i-1]
      ans2[i] = given[1] - ans2[i-1]
    } else {
      ans2[i] = plan[i]
    }//console.log(start,tot2,ans2)
  }

  if (tot2 < tot || tot == -1) {
    ans = ans2
    tot = tot2
  }

  start++
} while (plan[0] + start <= given[1] && tot != 0)

print(tot)
print(ans.join(' '))

var amount = readline().split(' ')[1];

var daysArray = readline().split(' '), plus = 0;

for(var i = 0; i < daysArray.length; i++) {
    daysArray[i] = +daysArray[i];
}

for(var i = 0; i < daysArray.length; i++) {
    var count = daysArray[i] + daysArray[i+1];
    if(count < amount) {
        plus += amount - count;
        daysArray[i+1] += amount - count;
    }
}

print(plus);
print(daysArray.join(' '));

var arr = readline().split(' ');
var N = Number(arr[0]);
var K = Number(arr[1]);

var days = [];

var rs = 0;

arr = readline().split(' ');
for (var i = 0;i < N;i ++) {
	days[i] = Number(arr[i]);
}

if (days.length == 1) {
	rs = 0;
} else {
	for (var i = 0;i < days.length - 1;i ++) {
		if (days[i] + days[i + 1] < K) {
			if (i + 1 == days.length - 1 || days[i + 2] + days[i + 1] >= K) {
				rs += K - days[i + 1] - days[i];
				days[i] = K - days[i + 1];
			} else {
				rs += K - days[i + 1] - days[i];
				days[i + 1] = K - days[i];
			}
		}
	}
}

print(rs);
var str = "";
for(var i = 0;i < days.length;i ++) {
	str += days[i];
	if (i != days.length - 1) {
		 str += " ";
	}
}
print(str);

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

ans = 0;

for (var i = 1; i < n; i++) {
    var extra = k - a[i-1] - a[i];
    if (extra > 0) {
        a[i] += extra;
        ans += extra;
    }
}

print(ans);
print(a.join(' '));

function main() {
    var line = readline().split(' ').map(Number);
    var n = line[0];
    var k = line[1];
    var data = readline().split(' ').map(Number);
    var res = 0;
    for(var i=0;i<n-1;i++){
        if(data[i] + data[i+1] < k){
            res += k - (data[i] + data[i+1]);
            data[i+1] += k - (data[i] + data[i+1]);
        }
    }
    print(res)
    print(data.join(' '))
}

main()

var g = readline().split(" ");
var n = Number(g[0]);
var k = Number(g[1]);
var y = readline().split(" ");
var o = y.slice(0);
var count = 0;
var h = [];
for(i=0;i<n;i++){
    if(Number(y[i]) + Number(y[i+1]) < k){
       y[i+1] = k - y[i];
    }
}
for(b=0;b<n;b++){
    count += y[b] - o[b];
}
print(count);
print(y.join(" "));

const reader = require("readline").createInterface({
  input: process.stdin
});

const input = [];

reader.on("line", storeInput);
reader.on("close", submitResult);

function storeInput(line) {
  input.push(line);
}
function submitResult() {
  const result = performCalculation();
  for (let line of result) {
    process.stdout.write(line + '\n');
  }
}
function performCalculation() {
  // Define input values
  const requiredSum = Number(input[0].split(" ")[1]);
  const statistics = input[1].split(" ").map(Number);

  // We can get O(n) solution:
  // iterate over the statistics, starting from 2nd element
  // apply logic to find required maximum for current item

  // from task description: item `n + 1` is always `requiredSum`

  let totalAdded = 0;
  let addition = 0;
  if (statistics.length === 1) {
    addition = requiredSum - statistics[0];
    if (addition > 0) {
      statistics[0] += addition;
      totalAdded += addition;
    }
  } else {
    for (let i = 1; i < statistics.length; i++) {
      addition = requiredSum - statistics[i - 1] - statistics[i];
      if (addition > 0) {
        statistics[i] += addition;
        totalAdded += addition;
      }
    }
  }

  // answer in required format
  return [totalAdded, statistics.join(" ")];
}

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

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

function main() {
	let [n, k] = readLine()
		.split(' ')
		.map(x => x >> 0);
	let schedules = readLine()
		.split(' ')
		.map(x => x >> 0);

	let b = [];
	let extra = 0;
	b.push(schedules[0]);

	for (let i = 1; i < n; i++) {
		let sum = schedules[i] + schedules[i - 1];
		if (sum >= k) {
			b[i] = schedules[i];
		} else {
			b[i] = schedules[i] + (k - sum);
			schedules[i] = b[i];
			extra += b[i];
		}
	}

	console.log(extra);
	console.log(b.join(' '));
}

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

var given = readIntTabLine(), // n days k walks for two days <500
    plan = readIntTabLine()

/*
for (var i = 0 ; i < given[0] ; i++) {
  plan[i] = parseInt(readline())
}
*///console.log(plan)

var ans = [], ans2 = [], tot = -1, tot2 = 0, start = 0

do {
  tot2 = start
  ans2 = [start + plan[0]]

  for (var i = 1 ; i < given[0] ; i++) {
    if (ans2[i-1] + plan[i] < given[1]) {
      tot2 += given[1] - plan[i] - ans2[i-1]
      ans2[i] = given[1] - ans2[i-1]
    } else {
      ans2[i] = plan[i]
    }//console.log(start,tot2,ans2)
  }

  if (tot2 < tot || tot == -1) {
    ans = ans2
    tot = tot2
  }

  start++
} while (plan[0] + start <= given[1] && tot != 0)

print(tot)
print(ans)

var arr = readline().split(' ');
var N = Number(arr[0]);
var K = Number(arr[1]);

var days = [];

var rs = 0;

arr = readline().split(' ');
for (var i = 0;i < N;i ++) {
	days[i] = Number(arr[i]);
}

if (days.length == 1) {
	if (K >= days[0]) {
		rs = K - days[0];
		days = [K];
	} else {
		rs = 0;
	}
} else {
	for (var i = 0;i < days.length - 1;i ++) {
		if (days[i] + days[i + 1] < K) {
			if (i + 1 == days.length - 1 || days[i + 2] + days[i + 1] >= K) {
				rs += K - days[i + 1] - days[i];
				days[i] = K - days[i + 1];
			} else {
				rs += K - days[i + 1] - days[i];
				days[i + 1] = K - days[i];
			}
		}
	}
}

print(rs);
var str = "";
for(var i = 0;i < days.length;i ++) {
	if (i != days.length - 1) {
		str += days[i] + " ";
	}
}
print(str);

var arr = readline().split(' ');
var N = Number(arr[0]);
var K = Number(arr[1]);

var days = [];

var rs = 0;

arr = readline().split(' ');
for (var i = 0;i < N;i ++) {
	days[i] = Number(arr[i]);
}

if (days.length == 1) {
	if (K >= days[0]) {
		rs = K - days[0];
		days = [K];
	} else {
		rs = 0;
	}
} else {
	for (var i = 0;i < days.length - 1;i ++) {
		if (days[i] + days[i + 1] < K) {
			if (i + 1 == days.length - 1 || days[i + 2] + days[i + 1] >= K) {
				days[i] = K - days[i + 1];
				rs += K - days[i + 1] - days[i];
			} else {
				days[i + 1] = K - days[i];
				rs += K - days[i + 1] - days[i];
			}
		}
	}
}

print(rs);
var str = "";
for(var i = 0;i < days.length;i ++) {
	if (i != days.length - 1) {
		str += days[i] + " ";
	}
}
print(str);

var arr = readline().split(' ');
var N = Number(arr[0]);
var K = Number(arr[1]);

var days = [];

var rs = 0;

arr = readline().split(' ');
for (var i = 0;i < N;i ++) {
	days[i] = Number(arr[i]);
}

if (days.length == 1) {
	if (K >= days[0]) {
		rs = K - days[0];
		days = [K];
	} else {
		rs = 0;
	}
} else {
	for (var i = 0;i < days.length - 1;i ++) {
		if (days[i] + days[i + 1] < K) {
			if (i + 1 == days.length - 1 || days[i + 2] + days[i + 1] >= K) {
				rs += K - days[i + 1] - days[i];
				days[i] = K - days[i + 1];
			} else {
				rs += K - days[i + 1] - days[i];
				days[i + 1] = K - days[i];
			}
		}
	}
}

print(rs);
var str = "";
for(var i = 0;i < days.length;i ++) {
	str += days[i];
	if (i != days.length - 1) {
		 str += " ";
	}
}
print(str);

var arr = readline().split(' ');
var N = Number(arr[0]);
var K = Number(arr[1]);

var days = [];

var rs = 0;

arr = readline().split(' ');
for (var i = 0;i < arr.length;i ++) {
	days[i] = Number(arr[i]);
}

if (days.length == 1) {
	if (K >= days[0]) {
		rs = K - days[0];
		days = [K];
	} else {
		rs = 0;
	}
} else {
	for (var i = 0;i < days.length - 1;i ++) {
		if (days[i] + days[i + 1] < K) {
			if (i + 1 == days.length - 1 || days[i + 2] + days[i + 1] >= K) {
				days[i] = K;
				rs += K - days[i];
			} else {
				days[i + 1] = K;
				rs += K - days[i + 1];
			}
		}
	}
}

print(rs);
var str = "";
for(var i = 0;i < days.length;i ++) {
	if (i != days.length - 1) {
		str += days[i] + " ";
	}
}
print(str);

function main() {
    var line = readline().split(' ').map(Number);
    var n = line[0];
    var k = line[1];
    var data = readline().split(' ').map(Number);
    for(var i=0;i<n-1;i++){
        if(data[i] + data[i+1] < k){
            data[i+1] += k - (data[i] + data[i+1]);
        }
    }
    print(data.join(' '))
}

main()

var g = readline().split(" ");
var n = Number(g[0]);
var k = Number(g[1]);
var y = readline().split(" ");
var k = y.slice(0);
var count = 0;
var h = [];
for(i=0;i<n;i++){
    if(Number(y[i]) + Number(y[i+1]) < k){
       y[i+1] = k - y[i];
    }
}
for(b=0;b<n;b++){
    count += y[b] - k[b];
}
print(count);
print(y.join(" "));


Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t - 1 gestures (if the icon is on the screen t), and then make another gesture — press the icon of the required application exactly once to launch it.After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.

The first line of the input contains three numbers n, m, k (1 ≤ n, m, k ≤ 105) — the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen. The next line contains n integers, permutation a1, a2, ..., an — the initial order of icons from left to right in the menu (from the first to the last one), ai —  is the id of the application, whose icon goes i-th in the menu. Each integer from 1 to n occurs exactly once among ai. The third line contains m integers b1, b2, ..., bm(1 ≤ bi ≤ n) — the ids of the launched applications in the planned order. One application may be launched multiple times.

Print a single number — the number of gestures that Anya needs to make to launch all the applications in the desired order.

NoteIn the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1, 2, 3, the second screen contains icons 4, 5, 6, the third screen contains icons 7, 8. After application 7 is launched, we get the new arrangement of the icons — (123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture.In total, Anya makes 7 gestures.

var L1 = readline().split(' ').map(function (a) {return parseInt(a); });

var n = L1[0];
var m = L1[1];
var k = L1[2];

var order = readline().split(' ');
var launch = readline().split(' ');

var dict = {};
for (var o=0; o<order.length; o++) {
    var app = order[o];
    dict[app] = o;
}

function swap(app) {
    var spot = dict[app];
    if (spot == 0) return;

    var same = order[spot];
    var other = order[spot - 1];

    var otherSpot = dict[other];
    var temp = spot;
    dict[app] = otherSpot;
    dict[other] = temp;

    temp = same;
    order[spot] = other;
    order[spot - 1] = temp;
}

function getGestures(i, k) {
    return Math.floor(i / k) + 1;
}

var gestures = 0;

for (var i=0; i<m; i++) {
    var a = launch[i];
    var pos = dict[a];
    gestures += getGestures(pos, k);
    swap(a);
}

print(gestures);

function main()    {
          var n = readline().split(/\s/gi).map(Number),
              k = n[2], m = n[1], n = n[0],
              screenLength = Math.ceil(n / k),
              appList = readline().split(/\s/gi),
              launchList = readline().split(/\s/gi),
              appMap = {}, screen = [[]], gesture = 0;

          // var startTime = new Date();

          appList.forEach(function(app, index)    {
              var screenIndex = Math.floor(index / k);

              if(!screen[screenIndex])    screen[screenIndex] = [];

              screen[screenIndex].push(app);
              appMap[app] = {
                  'screen' : {
                      'index' : screenIndex,
                      'loc' : screen[screenIndex].length - 1
                  }
              };
          });

          // var endTime = new Date();
          // console.log('%f', (endTime - startTime) / 1000);
          //console.log('%s %s %s %s', JSON.stringify(appMap), JSON.stringify(screen), JSON.stringify(launchList), '---------------------------------------------------');
          // var startTime = new Date();

          launchList.forEach(function(app, index)    {
              var screenIndex1 = appMap[app].screen.index, appIndex1 = appMap[app].screen.loc,
                  screenIndex2 = screenIndex1, appIndex2 = appIndex1 - 1, app2;

              if(appIndex1 == 0)    {
                  if(screenIndex1 != 0)    {
                      screenIndex2 = screenIndex1 - 1;
                      appIndex2 = k - 1;
                      gesture += screenIndex1;
                  } else  {
                      appIndex2 = appIndex1;
                  }
              } else    {
                  gesture += screenIndex1;
              }

              app2 = screen[screenIndex2][appIndex2];
              // console.log('%s, %s', app, app2);
              appMap[app].screen.index = screenIndex2;
              appMap[app].screen.loc = appIndex2;
              appMap[app2].screen.index = screenIndex1;
              appMap[app2].screen.loc = appIndex1;

              swapAppLocation(screen, screenIndex1, screenIndex2, appIndex1, appIndex2);

              gesture += 1;
              // console.log('%s\n%s', JSON.stringify(screen), '---------------------------------------------------');
          });

          // var endTime = new Date();
          // console.log('%f', (endTime - startTime) / 1000);

          print(gesture);
      };

      function swapAppLocation(screen, screenIndex1, screenIndex2, appIndex1, appIndex2)    {
          if(screenIndex1 < 0 || screenIndex2 < 0)    return;
          var temp = screen[screenIndex1][appIndex1];

          screen[screenIndex1][appIndex1] = screen[screenIndex2][appIndex2];
          screen[screenIndex2][appIndex2] = temp;
      };
main();

function main()    {
    var n = readline().split(/\s/gi).map(Number),
        k = n[1], m = n[2], n = n[0],
        screenLength = Math.ceil(n / k),
        appList = readline().split(/\s/gi),
        launchList = readline().split(/\s/gi),
        appMap = {},
        screen = [[]],
        gesture = 0;

    screen[-1] = [];

    appList.forEach(function(app, index)    {
        var screenIndex = Math.floor(index / screenLength);

        if(!screen[screenIndex])    screen[screenIndex] = [];

        screen[screenIndex].push(app);
        appMap[app] = screenIndex;
    });

    //console.log(screen);

    launchList.forEach(function(app, index)    {
        var screenIndex = appMap[app],
            appLocIndex = screen[screenIndex].indexOf(app);

        gesture += (screenIndex + 1);

        if(appLocIndex == 0)    {
            swapAppLocation(screen, screenIndex, screenIndex - 1, appLocIndex, screen[screenIndex - 1].length - 1);
            if(screenIndex != 0)    appMap[app] = screenIndex - 1;
        } else    {
            swapAppLocation(screen, screenIndex, screenIndex, appLocIndex, appLocIndex - 1);
        }
        //console.log(screen);
    });

    print(gesture);
};

function swapAppLocation(screen, screenIndex1, screenIndex2, screenIndex1AppIndex, screenIndex2AppIndex)    {
    if(screenIndex1 < 0 || screenIndex2 < 0)    return;
    var temp = screen[screenIndex1][screenIndex1AppIndex]

    screen[screenIndex1][screenIndex1AppIndex] = screen[screenIndex2][screenIndex2AppIndex];
    screen[screenIndex2][screenIndex2AppIndex] = temp;
};

main();


Vasya has an array $$$a_1, a_2, \dots, a_n$$$.You don't know this array, but he told you $$$m$$$ facts about this array. The $$$i$$$-th fact is a triple of numbers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$) and it means:  if $$$t_i=1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is sorted in non-decreasing order;  if $$$t_i=0$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter. For example if $$$a = [2, 1, 1, 3, 2]$$$ then he could give you three facts: $$$t_1=1, l_1=2, r_1=4$$$ (the subarray $$$[a_2, a_3, a_4] = [1, 1, 3]$$$ is sorted), $$$t_2=0, l_2=4, r_2=5$$$ (the subarray $$$[a_4, a_5] = [3, 2]$$$ is not sorted), and $$$t_3=0, l_3=3, r_3=5$$$ (the subarray $$$[a_3, a_5] = [1, 3, 2]$$$ is not sorted).You don't know the array $$$a$$$. Find any array which satisfies all the given facts.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 1000, 1 \le m \le 1000$$$). Each of the next $$$m$$$ lines contains three integers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$). If $$$t_i = 1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is sorted. Otherwise (if $$$t_i = 0$$$) subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is not sorted.

If there is no array that satisfies these facts in only line print NO (in any letter case). If there is a solution, print YES (in any letter case). In second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$, satisfying all the given facts. If there are multiple satisfying arrays you can print any of them.

"use strict";

// readline().split(' ').map(value => +value);
var input = readline().split(' ').map(value => +value);
var n = input[0];
var m = input[1];

var M = [];
for (var i = 0; i < m; ++i) {
    M.push(readline().split(' ').map(value => +value));
}

M.sort(function(a, b) {
    if (a[1] !== b[1])
        return a[1] - b[1];
    return a[2] - b[2];
});

var R = new Array(n + 10);
R[1] = 9999;
for (var i = 1, j = 2; i < n; ++i, ++j) {
    R[j] = R[i] - 1;
}

for (var i = 0; i < m; ++i) {
    var t = M[i][0];
    var l = M[i][1];
    var r = M[i][2];

    if (t === 1) {
        for (var j = l; j <= r; ++j) {
            R[j] = R[l];
        }
    }
}

var f = true;
for (var i = 0; i < m; ++i) {
    var t = M[i][0];
    var l = M[i][1];
    var r = M[i][2];

    if (t === 1) {
        for (var j = l, k = l+1; k <= r; ++j, ++k) {
            if (R[j] > R[k]) {
                f = false;
            }
        }
    } else {
        var b = false;
        for (var j = l, k = l+1; k <= r; ++j, ++k) {
            if (R[j] > R[k]) {
                b = true;
            }
        }
        f = f && b;
    }
}

if (f) {
    write('YES\n');
    write(R.slice(1, n+1).join(' '));
} else {
    write('NO\n');
}

process.stdin.setEncoding("ascii");

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(-1);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            for (let i = l; i < r; i++)
                mark[i] = 0;
        });
    array[0] = n;
    for (let i = 1; i < array.length; i++)
        array[i] = array[i - 1] + mark[i - 1];

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});

"use strict";

// readline().split(' ').map(value => +value);
var input = readline().split(' ').map(value => +value);
var n = input[0];
var m = input[1];

var M = [];
for (var i = 0; i < m; ++i) {
    M.push(readline().split(' ').map(value => +value));
}

M.sort(function(a, b) {
    if (a[1] !== b[1])
        return a[1] - b[1];
    return a[2] - b[2];
});

var R = new Array(n + 10);
R[1] = 9999;
for (var i = 1, j = 2; i < n; ++i, ++j) {
    R[j] = R[i] - 1;
}

for (var i = 0; i < m; ++i) {
    var t = M[i][0];
    var l = M[i][1];
    var r = M[i][2];

    if (t === 1) {
        for (var j = l; j <= r; ++j) {
            R[j] = R[l];
        }
    }
}

var f = true;
for (var i = 0; i < m; ++i) {
    var t = M[i][0];
    var l = M[i][1];
    var r = M[i][2];

    if (t === 1) {
        for (var j = l, k = l+1; k <= r; ++j, ++k) {
            if (R[j] > R[k]) {
                f = false;
            }
        }
    } else {
        for (var j = l, k = l+1; k <= r; ++j, ++k) {
            if (R[j] <= R[k]) {
                f = false;
            }
        }
    }
}

if (f) {
    write('YES\n');
    write(R.slice(1, n+1).join(' '));
} else {
    write('NO\n');
}

"use strict";

// readline().split(' ').map(value => +value);
var input = readline().split(' ').map(value => +value);
var n = input[0];
var m = input[1];

var M = [];
for (var i = 0; i < m; ++i) {
    M.push(readline().split(' ').map(value => +value));
}

M.sort(function(a, b) {
    return a[1] - b[1];
});

var R = new Array(n + 10);
R[1] = 9999;
for (var i = 1, j = 2; i < n; ++i, ++j) {
    R[j] = R[i] - 1;
}

for (var i = 0; i < m; ++i) {
    var t = M[i][0];
    var l = M[i][1];
    var r = M[i][2];

    if (t === 1) {
        for (var j = l; j <= r; ++j) {
            R[j] = R[l];
        }
    }
}

var f = true;
for (var i = 0; i < m; ++i) {
    var t = M[i][0];
    var l = M[i][1];
    var r = M[i][2];

    if (t === 1) {
        for (var j = l, k = l+1; k <= r; ++j, ++k) {
            if (R[j] > R[k]) {
                f = false;
            }
        }
    } else {
        for (var j = l, k = l+1; k <= r; ++j, ++k) {
            if (R[j] <= R[k]) {
                f = false;
            }
        }
    }
}

if (f) {
    write('YES\n');
    write(R.slice(1, n+1).join(' '));
} else {
    write('NO\n');
}

"use strict";

// readline().split(' ').map(value => +value);
var input = readline().split(' ').map(value => +value);
var n = input[0];
var m = input[1];

var M = [];
for (var i = 0; i < m; ++i) {
    M.push(readline().split(' ').map(value => +value));
}

var R = new Array(n + 10);
R[1] = 9999;
for (var i = 1, j = 2; i < n; ++i, ++j) {
    R[j] = R[i] - 1;
}

for (var i = 0; i < m; ++i) {
    var t = M[i][0];
    var l = M[i][1];
    var r = M[i][2];

    if (t === 1) {
        for (var j = l; j <= r; ++j) {
            R[j] = R[l];
        }
    }
}

var f = true;
for (var i = 0; i < m; ++i) {
    var t = M[i][0];
    var l = M[i][1];
    var r = M[i][2];

    if (t === 1) {
        for (var j = l, k = l+1; k <= r; ++j, ++k) {
            if (R[j] > R[k]) {
                f = false;
            }
        }
    } else {
        for (var j = l, k = l+1; k <= r; ++j, ++k) {
            if (R[j] <= R[k]) {
                f = false;
            }
        }
    }
}

if (f) {
    write('YES\n');
    write(R.slice(1, n+1).join(' '));
} else {
    write('NO\n');
}

process.stdin.setEncoding("ascii");

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    const getUniqueID = (() => {
        let counter = 0;
        return () => ++counter;
    })();
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || getUniqueID();
            for (let i = l; i <= r; i++)
                mark[i] = fill;
        });

    if (mark.every(x => x === undefined)) {
        array[0] = 2;
        for (let i = 1; i < array.length; i++)
            array[i] = 1;
        console.log("YES");
        console.log(array.join(" "));
        return;
    }

    // extend the marked ranges so that all the ranges cover the array
    const getID = index => {
        if (mark[index] !== undefined) return mark[index];
        if (index < 0) return undefined;
        if (index >= mark.length) return undefined;
        return [getID(index - 1), getID(index + 1)].find(x => x !== undefined);
    };
    Object.assign(mark, mark.map((_, index) => getID(index)));

    const conditions = [];

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        const subarrayIDs = mark.slice(l, r + 1).filter(x => x !== undefined);
        if (subarrayIDs.length < 2) {
            console.log("NO");
            return;
        }
        conditions.push(subarrayIDs);
    }

    const weights = Array(Math.max(...mark) + 1).fill(0);

    for (const binaryCondition of conditions.filter(condition => condition.length === 2)) {
        const [mark1, mark2] = binaryCondition;
        if (weights[mark1] <= weights[mark2])
            weights[mark2]--;
    }

    outer:
    for (const nonBinaryCondition of conditions.filter(condition => condition.length !== 2)) {
        for (let i = 1; i < nonBinaryCondition.length; i++) {
            const mark1 = nonBinaryCondition[i - 1];
            const mark2 = nonBinaryCondition[i];
            if (weights[mark1] > weights[mark2]) {
                continue outer;
            }
        }
        const mark1 = nonBinaryCondition[0];
        const mark2 = nonBinaryCondition[1];
        weights[mark2]--;
    }

    console.log(mark.map(x => weights[x] + n + 1).join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

const getUniqueNumber = (() => {
    let counter = 0;
    return () => ++counter;
})();

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || getUniqueNumber();
            for (let i = l; i <= r; i++)
                mark[i] = fill;
        });

    let previousValueIsUndefined = false;
    const ranges = [];
    for (let i = 0; i < mark.length; i++) {
        if (mark[i] === undefined) {
            if (previousValueIsUndefined) {
                ranges[ranges.length - 1].push(i);
            } else {
                ranges.push([i]);
            }
            previousValueIsUndefined = true;
        }
        if (mark[i] !== undefined) {
            previousValueIsUndefined = false;
        }
    }

    ranges.forEach(range => {
        const fill = getUniqueNumber();
        range.forEach(index => {
            mark[index] = fill;
        });
    });

    const map = [...new Set(mark)].reduce((previousValue, currentValue, currentIndex, array) => {
        previousValue.set(currentValue, currentIndex);
        return previousValue;
    }, new Map());

    mark.map(fill => map.get(fill));

    let counter = 1000000001;
    const values = Array(Math.max(...mark) + 1).fill(0);
    for (let i = 1; i < values.length; i++)
        values[i] = --counter;

    Object.assign(array, mark.map(fill => values[fill]));

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || Math.random();
            for (let i = l; i <= r; i++)
                mark[i] = fill;
        });
    array[0] = n;
    for (let i = 1; i < array.length; i++) {
        if (mark[i] !== mark[i - 1]) {
            array[i] = array[i - 1] - 1;
            continue;
        }
        array[i] = array[i - 1];
    }

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);
    facts.forEach(([t, l, r]) => {
        l--;
        r--;
        const fill = Math.max(...array.slice(l, r + 1));
        if (t == 1) {
            array.fill(fill, l, r);
        } else {
            array.fill(fill - 1, l, r);
        }
    });
    console.log("YES");
    const x = -Math.min(...array) + 1;
    if (x > 0) {
        console.log(array.map(k => k + x).join(" "));
    } else {
        console.log(array.join(" "));
    }
});

process.stdin.setEncoding("ascii");

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || Math.random();
            for (let i = l; i < r; i++)
                mark[i] = fill;
        });
    array[0] = n;
    for (let i = 1; i < array.length; i++) {
        if (mark[i] !== mark[i - 1]) {
            array[i] = array[i - 1] - 1;
            continue;
        }
        array[i] = array[i - 1];
    }

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);
    facts.forEach(([t, l, r]) => {
        l--;
        r--;
        if (t == 1) {
            array.fill(array[l], l, r);
        } else {
            array.fill(array[l] - 1, l, r);
        }
    });
    console.log("YES");
    const x = -Math.min(...array) + 1;
    if (x > 0) {
        console.log(array.map(k => k + x).join(" "));
    } else {
        console.log(array.join(" "));
    }
});

process.stdin.setEncoding("ascii");

let input = "";

const getUniqueNumber = (() => {
    let counter = 0;
    return () => ++counter;
})();

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || getUniqueNumber();
            for (let i = l; i <= r; i++)
                mark[i] = fill;
        });

    const getFill = (index) => {
        if (mark[index] !== undefined) return mark[index];
        if (index < 0 || index >= mark.length) return undefined;
        return [getFill(index - 1), getFill(index + 1)].find(x => x !== undefined);
    }

    Object.assign(mark, mark.map((_, index) => getFill(index)));

    let counter = 1000000001;
    const values = Array(Math.max(...mark) + 1).fill(0);
    for (let i = 1; i < values.length; i++)
        values[i] = --counter;

    Object.assign(array, mark.map(fill => values[fill]));

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    const getUniqueID = (() => {
        let counter = 0;
        return () => ++counter;
    })();
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || getUniqueID();
            for (let i = l; i <= r; i++)
                mark[i] = fill;
        });

    if (mark.every(x => x === undefined)) {
        array[0] = 2;
        for (let i = 1; i < array.length; i++)
            array[i] = 1;
        console.log("YES");
        console.log(array.join(" "));
        return;
    }

    // extend the marked ranges so that all the ranges cover the array
    const getID = index => {
        if (mark[index] !== undefined) return mark[index];
        if (index < 0) return undefined;
        if (index >= mark.length) return undefined;
        return [getID(index - 1), getID(index + 1)].find(x => x !== undefined);
    };
    Object.assign(mark, mark.map((_, index) => getID(index)));

    const conditions = [];

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        const subarrayIDs = mark.slice(l, r + 1).filter(x => x !== undefined);
        if (subarrayIDs.length < 2) {
            console.log("NO");
            return;
        }
        conditions.push(subarrayIDs);
    }

    const weights = Array(Math.max(...mark) + 1).fill(0);

    for (const binaryCondition of conditions.filter(condition => condition.length === 2)) {
        const [mark1, mark2] = binaryCondition;
        if (weights[mark1] <= weights[mark2])
            weights[mark2]--;
    }

    outer:
    for (const nonBinaryCondition of conditions.filter(condition => condition.length !== 2)) {
        for (let i = 1; i < nonBinaryCondition.length; i++) {
            const mark1 = nonBinaryCondition[i - 1];
            const mark2 = nonBinaryCondition[i];
            if (weights[mark1] > weights[mark2]) {
                continue outer;
            }
        }
        const mark1 = nonBinaryCondition[0];
        const mark2 = nonBinaryCondition[1];
        weights[mark2]--;
    }
    console.log("YES");
    console.log(mark.map(x => weights[x] + n + 1).join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(0);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = Math.random();
            for (let i = l; i < r; i++)
                mark[i] = fill;
        });
    array[0] = n;
    for (let i = 1; i < array.length; i++) {
        if (mark[i] !== mark[i - 1]) {
            array[i] = array[i - 1] - 1;
            continue;
        }
        array[i] = array[i - 1];
    }

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);
    facts.forEach(([t, l, r]) => {
        l--;
        r--;
        if (t == 1) {
            array.fill(array[l], l, r);
        } else {
            array.fill(array[l] - 1, l, r);
        }
    });
    console.log("YES");
    console.log(array.join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

const getUniqueNumber = (() => {
    let counter = 0;
    return () => ++counter;
})();

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || getUniqueNumber();
            for (let i = l; i <= r; i++)
                mark[i] = fill;
        });

    let previousValueIsUndefined = false;
    const ranges = [];
    for (let i = 0; i < mark.length; i++) {
        if (mark[i] === undefined) {
            if (previousValueIsUndefined) {
                ranges[ranges.length - 1].push(i);
            } else {
                ranges.push([i]);
            }
            previousValueIsUndefined = true;
        }
        if (mark[i] !== undefined) {
            previousValueIsUndefined = false;
        }
    }

    ranges.forEach(range => {
        const fill = getUniqueNumber();
        range.forEach(index => {
            mark[index] = fill;
        });
    });

    let counter = 1000000001;
    const values = Array(Math.max(...mark) + 1).fill(0);
    for (let i = 1; i < values.length; i++)
        values[i] = --counter;

    Object.assign(array, mark.map(fill => values[fill]));

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

const getUniqueNumber = (() => {
    let counter = 0;
    return () => ++counter;
})();

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || getUniqueNumber();
            for (let i = l; i <= r; i++)
                mark[i] = fill;
        });
    array[0] = n;
    for (let i = 1; i < array.length; i++) {
        if (mark[i - 1] !== mark[i]) {
            array[i] = array[i - 1] - 1;
            continue;
        }
        array[i] = array[i - 1];
    }

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

const getUniqueNumber = (() => {
    let counter = 0;
    return () => ++counter;
})();

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || getUniqueNumber();
            for (let i = l; i <= r; i++)
                mark[i] = fill;
        });

    let previousValueIsUndefined = false;
    const ranges = [];
    for (let i = 0; i < mark.length; i++) {
        if (mark[i] === undefined) {
            if (previousValueIsUndefined) {
                ranges[ranges.length - 1].push(i);
            } else {
                ranges.push([i]);
            }
            previousValueIsUndefined = true;
        }
        if (mark[i] !== undefined) {
            previousValueIsUndefined = false;
        }
    }

    ranges.forEach(range => {
        const fill = getUniqueNumber();
        range.forEach(index => {
            mark[index] = fill;
        });
    });

    const map = [...new Set(mark)].reduce((previousValue, currentValue, currentIndex, array) => {
        previousValue.set(currentValue, currentIndex);
        return previousValue;
    }, new Map());

    Object.assign(mark, mark.map(fill => map.get(fill)));

    let counter = 1000000001;
    const values = Array(Math.max(...mark) + 1).fill(0);
    for (let i = 1; i < values.length; i++)
        values[i] = --counter;

    Object.assign(array, mark.map(fill => values[fill]));

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(1);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            for (let i = l; i <= r; i++)
                mark[i] = 0;
        });
    array[0] = n;
    for (let i = 1; i < array.length; i++)
        array[i] = array[i - 1] + mark[i - 1];

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    const getUniqueID = (() => {
        let counter = 0;
        return () => ++counter;
    })();
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || getUniqueID();
            for (let i = l; i <= r; i++)
                mark[i] = fill;
        });

    if (mark.every(x => x === undefined)) {
        array[0] = 2;
        for (let i = 1; i < array.length; i++)
            array[i] = 1;
        console.log("YES");
        console.log(array.join(" "));
        return;
    }

    // extend the marked ranges so that all the ranges cover the array
    const getID = index => {
        if (mark[index] !== undefined) return mark[index];
        if (index < 0) return undefined;
        if (index >= mark.length) return undefined;
        return [getID(index - 1), getID(index + 1)].find(x => x !== undefined);
    };
    Object.assign(mark, mark.map((_, index) => getID(index)));

    const conditions = [];

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        const subarrayIDs = [...new Set(mark.slice(l, r + 1).filter(x => x !== undefined))];
        if (subarrayIDs.length < 2) {
            console.log("NO");
            return;
        }
        conditions.push(subarrayIDs);
    }

    const weights = Array(Math.max(...mark) + 1).fill(0);

    for (const binaryCondition of conditions.filter(condition => condition.length === 2)) {
        const [mark1, mark2] = binaryCondition;
        if (weights[mark1] <= weights[mark2])
            weights[mark2]--;
    }

    outer:
    for (const nonBinaryCondition of conditions.filter(condition => condition.length !== 2)) {
        for (let i = 1; i < nonBinaryCondition.length; i++) {
            const mark1 = nonBinaryCondition[i - 1];
            const mark2 = nonBinaryCondition[i];
            if (weights[mark1] > weights[mark2]) {
                continue outer;
            }
        }
        const mark1 = nonBinaryCondition[0];
        const mark2 = nonBinaryCondition[1];
        weights[mark2]--;
    }
    console.log("YES");
    console.log(mark.map(x => weights[x] + n + 1).join(" "));
});

process.stdin.setEncoding("ascii");

let input = "";

const getUniqueNumber = (() => {
    let counter = 0;
    return () => ++counter;
})();

process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
    const [[n, m], ...facts] = input.trim().split("\n").map(x => x.trim().split(" ").map(Number));
    const array = Array(n).fill(0);

    const mark = Array(n).fill(undefined);
    facts
        .filter(([t]) => t === 1)
        .forEach(([t, l, r]) => {
            l--;
            r--;
            const fill = mark.slice(l, r + 1).find(x => x !== undefined) || getUniqueNumber();
            for (let i = l; i <= r; i++)
                mark[i] = fill;
        });

    let previousValueIsUndefined = false;
    const ranges = [];
    for (let i = 0; i < mark.length; i++) {
        if (mark[i] === undefined) {
            if (previousValueIsUndefined) {
                ranges[ranges.length - 1].push(i);
            } else {
                ranges.push([i]);
            }
            previousValueIsUndefined = true;
        }
        if (mark[i] !== undefined) {
            previousValueIsUndefined = false;
        }
    }

    ranges.forEach(range => {
        const fill = getUniqueNumber();
        range.forEach(index => {
            mark[index] = fill;
        });
    });

    const map = [...new Set(mark)].reduce((previousValue, currentValue, currentIndex, array) => {
        previousValue.set(currentValue, currentIndex + 1);
        return previousValue;
    }, new Map());

    Object.assign(mark, mark.map(fill => map.get(fill)));

    let counter = 1000000001;
    const values = Array(Math.max(...mark) + 1).fill(0);
    for (let i = 1; i < values.length; i++)
        values[i] = --counter;

    Object.assign(array, mark.map(fill => values[fill]));

    const sortedNonDecreasing = array => {
        for (let i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i])
                return false;
        }
        return true;
    }

    for (let [t, l, r] of facts.filter(([t]) => t === 0)) {
        l--;
        r--;
        if (sortedNonDecreasing(array.slice(l, r + 1))) {
            console.log("NO");
            return;
        }
    }

    console.log("YES");
    console.log(array.join(" "));
});