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

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

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


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


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

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(" "));


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();


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 {
        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');
}

"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(" "));
});


let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    for(i = 1; i <= t; i++){
        var k = lines[i].split(' ').map(Number);
        var n = k[0], m = k[1];
        var ans = n + m - 2;
        ans += Math.min(n, m);
    console.log(n == 1 && m == 1 ? 0 : ans);
    }
});

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseArray = readline().split(" ");
    var rows = parseInt(caseArray[0]) - 1;
    var columns = parseInt(caseArray[1]) - 1;
    if (rows > 0 || columns > 0)
    {
        var lower = Math.min(rows, columns);
        var higher = Math.max(rows, columns);
        var result = (2 * lower) + higher + 1;
        print(result);
    }
    else print(0);
}

var tests = parseInt(readline());
    var n, m;
    for (var t=0; t < tests; t++) {
        var nm = readline().split(' ').map(x=>parseInt(x));
        n = nm[0];
        m = nm[1];
        if (n == 1 && m == 1) {
            print(0);
            continue;
        }
        var ans = 0;
        ans += n + m - 2;
        ans += Math.min(n, m);
        print(ans);
    }

T = readline()

while(T--){
  str = readline().split(' ').map(el => +el)
  n =str[0]
  m =str[1]

  if(n==1 && m ==1){
    print(0)
  }
  else{
    if(n>=m){
    print(m+m+n-2)
  }
  else{
    print((n-1) + m +n-1)
  }
  }

}

function convertNumberArray(str){ // '  12   43 123 4 ' >> [12, 43, 123, 4]
    return str.replace(/ +/g, " ").trim().split(' ').map(string => Number(string));
}

const process = require('process');
const {EOL} = require('os');
const { mainModule } = require('process');

let data = '';
process.stdin.on('data', string=>data+=string);
process.stdin.on('end', () => {
    const dataLines = data.split(EOL);
    A1715(dataLines);
});

const A1715 = (input)=>{
    // console.debug('DEBUGGGGGASDKJLADJSLJASDLJASD', input);
    let result = '';
    const tests = Number(input[0]);
    for(let i=1; i<=tests; i++){
        const [n, m] = convertNumberArray(input[i]);
        // console.log(solve(n, m));
        process.stdout.write(solve(n, m) + '\n');
        result+=solve(n, m) + '\n'
        // console.debug('DEBUGGGGGASDKJLADJSLJASDLJASD', result);
    }
    return result;
}
function solve(n, m){
    if(n==1 && m==1) return 0;
    else return Math.min(n,m) + Math.min(n,m)-1 + Math.max(n,m)-1;
}

// module.exports = {A1715};

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {

    result = i.split('\n').slice(1, -1)
        .map(l => l.split(" ").map(t => parseInt(t)))
        .map(l => l[0] + l[1] - 2 + Math.min(l[0], l[1]))
        .map(l => (l === 1) ? 0 : l)
        .join('\n')

    console.log(result)
})

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let i=1;i<=t;i++)
    {
        let [n,m]=line[i].split(' ').map(x=>{return parseInt(x)});
        let ans=n+m-2;
        ans+=Math.min(n,m);
        if(n==1&&m==1) ans=0;
        console.log(ans);
    }
})

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var M = nextInt();
		var min = Math.min(N, M);
		var max = Math.max(N, M);
		if(min == 1 && max == 1){
			myout(0);
			continue;
		}
		myout(min * 2 + max - 2);
	}
}

function solve(a, b) {
    // For she # of energy would be a - 1 + b - 1
    const herEnergy = a - 1 + b - 1;
    // For he # of energy would be min(a, b)
    const hisEnergy = a === 1 && b === 1 ? 0 : Math.min(a, b);
    return herEnergy + hisEnergy;
}

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

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (var i = 1; i < lines.length; i++) {
        const [a, b] = lines[i].split(' ').map(Number);
        process.stdout.write(solve(a, b) + '\n');
    }
});

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function isPossible(n, x, heights) {
    heights.sort();
    heights.sort(function(a, b) {
        return a - b;
      });
    // //console.log(heights)

    let front = []
    let back = []

    for (let i = 0; i < heights.length; i++) {
        if (i < n) {
            front.push(heights[i])
        } else {
            back.push(heights[i])
        }
    }

    // //console.log(front)
    // //console.log(back)
    for (let j = 0; j < front.length; j++) {
        if (back[j] - front[j] < x) {
            // //console.log(back[j] + " " + front[j])
            return "NO";
        }
    }

    return "YES";
}

function calc(a, m) {
    let s = "";
    for (let index = 0; index < m; index++) {
        s += "B"
    }

   for (let index = 0; index < a.length; index++) {
        let ai = a[index];

        if (ai < (m + 1 - ai)) {
            let _s = s.replaceAt(ai - 1, "A");
            if (compare(_s, s) < 0) {
                s = _s;
                continue;
            } else if (compare(_s, s) >= 0) {
                    let __ss = s.replaceAt(m + 1 - ai - 1, "A");
                    if (compare(__ss, s) < 0) {
                        s = __ss;
                        continue;
                    }
            }
         }  else {
            let _s = s.replaceAt(m + 1 - ai - 1, "A");
            if (compare(_s, s) < 0) {
                s = _s;
                continue;
            }  if (compare(_s, s) >= 0) {
                    let __ss = s.replaceAt(ai - 1, "A");
                    if (compare(__ss, s) < 0) {
                        s = __ss;
                        continue;
                    }
            }
    }
}

   return s;
}

function compare(s1, s2) {
    return s1.localeCompare(s2)
}

String.prototype.replaceAt = function(index, replacement) {
    return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        // const n = parseInt(readLine().trim(), 10);
        const arr = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));

        const m = arr[0]
        const n = arr[1]

        if (m == 1 && n == 1) console.log(0)
        else if (m == 1 || n == 1) {
            let x = m > n ? m : n;
            console.log(x)
        } else {
            let s = 0;
            if (m > n)
                s = m + (n -1)*2
            else
                s = n + (m-1)*2
            console.log(s);
        }

    }

    // ws.end();
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    for (let test = 0; test < N; test++) {
        let [n, m] = readline().split(' ').map(Number);
        if (n === 1 && m === 1) {
            output(0);
        } else if (n === 1 || m === 1) {
            output(Math.max(n, m));
        } else {
            let bigger = Math.max(n, m);
            let smaller = Math.min(n, m);
            output(bigger + ((smaller - 1) * 2));
        }
    }
}

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, m] = input[index].split(" ").map((item) => parseInt(item));

    const testCase = {
      n,
      m,
    };

    testCases.push(testCase);
  }
}

function solution(testCase) {
  const { n, m } = testCase;

  console.log(
    n -
      1 +
      m -
      1 +
      (Math.max(n - 1, m - 1) > 0 ? 1 : 0) +
      Math.min(n - 1, m - 1)
  );
}

parseInput();

testCases.forEach(solution);

function convertNumberArray(str){ // '  12   43 123 4 ' >> [12, 43, 123, 4]
    return str.replace(/ +/g, " ").trim().split(' ').map(string => Number(string));
}

const process = require('process');
const {EOL} = require('os');
const { mainModule } = require('process');

let data = '';
process.stdin.on('data', string=>data+=string);
process.stdin.on('end', () => {
    const dataLines = data.split(EOL);
    A1715(dataLines);
});

const A1715 = (input)=>{
    console.debug('DEBUGGGGGASDKJLADJSLJASDLJASD', input);
    let result = '';
    const tests = Number(input[0]);
    for(let i=1; i<=tests; i++){
        const [n, m] = convertNumberArray(input[i]);
        // console.log(solve(n, m));
        process.stdout.write(solve(n, m) + '\n');
        result+=solve(n, m) + '\n'
        console.debug('DEBUGGGGGASDKJLADJSLJASDLJASD', result);
    }
    return result;
}
function solve(n, m){
    if(n==1 && m==1) return 0;
    else return Math.min(n,m) + Math.min(n,m)-1 + Math.max(n,m)-1;
}

// module.exports = {A1715};

function convertNumberArray(str){ // '  12   43 123 4 ' >> [12, 43, 123, 4]
    return str.replace(/ +/g, " ").trim().split(' ').map(string => Number(string));
}

const process = require('process');
const {EOL} = require('os');
const { mainModule } = require('process');

let data = '';
process.stdin.on('data', string=>data+=string);
process.stdin.on('end', () => {
    const dataLines = data.split(EOL);
    A1715(dataLines);
});

const A1715 = (input)=>{
    console.log('DEBUGGGGGASDKJLADJSLJASDLJASD', input);
    let result = '';
    const tests = Number(input[0]);
    for(let i=1; i<=tests; i++){
        const [n, m] = convertNumberArray(input[i]);
        // console.log(solve(n, m));
        process.stdout.write(solve(n, m) + '\n');
        result+=solve(n, m) + '\n'
        console.log('DEBUGGGGGASDKJLADJSLJASDLJASD', result);
    }
    return result;
}
function solve(n, m){
    if(n==1 && m==1) return 0;
    else return Math.min(n,m) + Math.min(n,m)-1 + Math.max(n,m)-1;
}

// module.exports = {A1715};

function convertNumberArray(str){ // '  12   43 123 4 ' >> [12, 43, 123, 4]
    return str.replace(/ +/g, " ").trim().split(' ').map(string => Number(string));
}

const process = require('process');
const {EOL} = require('os');
const { mainModule } = require('process');

let data = '';
process.stdin.on('data', string=>data+=string);
process.stdin.on('end', () => {
    const dataLines = data.split(EOL);
    A1715(dataLines);
});

function A1715(input) {
    const tests = Number(input[0]);
    for(let i=0; i<tests; i++){
        const [n, m] = convertNumberArray(input[i]);
        // console.log(solve(n, m));
        process.stdout.write(solve(n, m) + '\n');
    }
}

function solve(n, m){
    if(n==1 && m==1) return 0;
    else return Math.min(n,m) + Math.min(n,m)-1 + Math.max(n,m)-1;
}

function convertNumberArray(str){ // '  12   43 123 4 ' >> [12, 43, 123, 4]
    return str.replace(/ +/g, " ").trim().split(' ').map(string => Number(string));
}

const process = require('process');
const {EOL} = require('os');
const { mainModule } = require('process');

let data = '';
process.stdin.on('data', string=>data+=string);
process.stdin.on('end', () => {
    const dataLines = data.split(EOL);
    A1715(dataLines);
});

function A1715(input) {
    const tests = Number(input[0]);
    for(let i=0; i<tests; i++){
        const [n, m] = convertNumberArray(input[i]);
        console.log(solve(n, m));
    }
}

function solve(n, m){
    if(n==1 && m==1) return 0;
    else return Math.min(n,m) + Math.min(n,m)-1 + Math.max(n,m)-1;
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {

    let result = i.split('\n').slice(1)
        .map(l => l.split(" ").map(t => parseInt(t)))
        .map(l => l[0] + l[1] - 2 + Math.min(l[0], l[1]))
        .map(l => (l === 1) ? 0 : l)
        .join('\n')

    console.log(result)
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    let result = i.split('\n').slice(1)
        .map(l => l.split(" ").map(t => parseInt(t)))
        .map(l => l[0] + l[1] - 2 + Math.min(l[0], l[1]))
        .map(l => (l === 1) ? 0 : l)
        .reduce((l1, l2) => l1 + '' + l2, '')

    console.log(result)
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    let result = i.split('\n').slice(1)
        .map(l => l.split(" ").map(t => parseInt(t)))
        .map(l => l[0] + l[1] - 2 + Math.min(l[0], l[1]))
        .map(l => (l === 1) ? 0 : l)
        .reduce((l1, l2) => l1 + '\n' + l2, '')

    console.log(result)
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL)

    let result = lines.slice(1)
        .map(l => l.split(" ").map(t => parseInt(t)))
        .map(l => l[0] + l[1] - 2 + Math.min(l[0], l[1]))
        .map(l => (l === 1) ? 0 : l)

    console.log(result)
})

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let i=1;i<=t;i++)
    {
        let [n,m]=line[i].split(' ').map(x=>{return parseInt(x)});
        let ans=n+m-2;
        ans+=Math.min(n,m);
        console.log(ans);
    }
})


'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(s2) {
  if (s2[s2.length - 1] !== 'B') {
    console.log('NO');
    return;
  }
  let prea = 0,
      preb = 0;
  for (let char of s2) {
    if (char === 'A') prea++;else preb++;
    if (preb > prea) {
      console.log('NO');
      return;
    }
  }
  console.log('YES');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const s2 = await read();
    solve(s2);
  }
}

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

var t = readline();

for (var i = 0; i < t; i++) {
  var s = readline().split('');
  var n = s.length;
  var cur = 0;
  var f = s[n - 1] === 'B';

  for (var j = 0; j < n; j++) {
    cur += s[j] == 'A' ? 1 : -1;
    if (cur < 0) f = false;
  }

  if (f) print('YES');
  else print('NO');
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

    for (let test = 0; test < N; test++) {
        const s2 = readline();
        let s1 = '';
        if (s2[0] === 'B' || s2[s2.length - 1] === 'A') {
            output('NO');
            continue;
        }

        let a = 0;
        let b = 0;

        let no = false;
        for (let i = 0; i < s2.length; i++) {
           if (s2[i] === 'A') { a++ } else { b++ };
           if (b>a) {
                no = true;
                break;
           }
        }

        output(no ? 'NO' : 'YES');

    }
}

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length - 1] != 'B' || x[0] != 'A')
      ans = 'NO'
   allB = 0
   allA = 0
   for(i=0; i< x.length; i++){
      if(x[i]==='B')
         allB ++
      else
         allA ++
      if(allB > allA){
         ans = 'NO'
         break
      }

   }

   print(ans)
}

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

let ls = [];

function solve() {
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let i = 0; i < t; i++){
        const s = ls[l++];
        let chrz = 0;
        let ans = true;
        let hasB = false;
        for (let j = 0; j < s.length; j++){
            if (s[j] == 'A'){
                chrz++;
            }
            else{
                chrz--;
                hasB = true;
            }
            ans &= (chrz >= 0);
        }

        let lastB = s[s.length - 1] == 'B';
        console.log(ans && hasB && lastB ? 'YES' : 'NO');
    }
}

rl.on('line', (l) => ls.push(l));
rl.on('close', () => solve());

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length - 1] != 'B' || x[0] != 'A')
      ans = 'NO'
   allB = 0
   allA = 0
   for(i=0; i< x.length; i++){
      if(x[i]==='B')
         allB ++
      else
         allA ++
   }
   if(allB>allA)
      ans = 'NO'
   print(ans)
}

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length] != 'B' || x[0] != 'A')
      ans = 'NO'
   for(i=0; i < x.length - 1; i++){
      if(x[i] === x[i+1] && x[i] === 'B'){
         ans = 'NO'
         break
      }
   }
   print(ans)
}

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length - 1] != 'B' || x[0] != 'A')
      ans = 'NO'
   for(i=0; i < x.length - 2; i++){
      if(x[i] === x[i+1] && x[i] === 'B'){
         ans = 'NO'
         break
      }
   }
   print(ans)
}

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length - 1] != 'B' || x[0] != 'A')
      ans = 'NO'
   for(i=0; i < x.length - 1; i++){
      if(x[i] === x[i+1] && x[i] === 'B'){
         ans = 'NO'
         break
      }
   }
   print(ans)
}

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length - 1] != 'B')
      ans = 'NO'
   for(i=0; i < x.length - 1; i++){
      if(x[i] === x[i+1] && x[i] === 'B'){
         ans = 'NO'
         break
      }
   }
   print(ans)
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

    for (let test = 0; test < N; test++) {
        const s2 = readline();
        let s1 = '';
        if (s2[0] === 'B') {
            output('NO');
            continue;
        } else if (s2 === 'A') {
            output('NO');
            continue;
        } else if (s2[s2.length - 1] === 'A') {
            output('NO');
            continue;
        }

        let no = false;
        for (let i = 1; i < s2.length; i++) {
            if (s2[i] === 'B' && s2[i - 1] === 'B') {
                no = true;
                break;
            }
        }

        output(no ? 'NO' : 'YES');

    }
}

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

let ls = [];

function solve() {
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let i = 0; i < t; i++){
        const s = ls[l++];
        let chrz = 0;
        let ans = true;
        let hasB = false;
        for (let j = 0; j < s.length; j++){
            if (s[j] == 'A'){
                chrz++;
            }
            else{
                chrz--;
                hasB = true;
            }
            ans &= (chrz >= 0);
        }
        console.log(ans && hasB ? 'YES' : 'NO');
    }
}

rl.on('line', (l) => ls.push(l));
rl.on('close', () => solve());