//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] = BigInt(next());
		}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 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 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();
	var list = [];
	var now = 1;
	while(list.length < 1000){
		if(now % 3 != 0 && now % 10 != 3){
			list.push(now);
		}
		now++;
	}
	while(hasNext()){
		var K = nextInt();
		myout(list[K - 1]);
	}
}

function checkIsValid (i) {
    if (i % 3 === 0) {
        return false;
    }
    if (i % 10 === 3) {
        return false;
    }
    return true;
}
function main(array) {
    let i = 0;
    let arr = [];
    while (true) {
        i += 1;
        if (checkIsValid(i)) {
            arr.push(i);
            if (arr.length >= 1001) {
                break;
            }
        }
    }
    const T = array[0];
    for (let i = 0; i < T; i++) {
        const k = array[i + 1];
        console.log(arr[k - 1]);
    }
}

let inputString = '';

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

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

    main(inputString);
});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    var a = [];
    for(l = 1; l < 1667; l++){
        if(l % 10 == 3 || l % 3 === 0){

        }else{
            a.push(l);
        }
    }
    for(j = 1; j <= n; j++){
        var k = lines[j];
        console.log(a[k - 1]);
    }
});

let data = "";

function solve(){

    let polycarp = [];
    let input = data.split(/ |\n/);
    let testCaseNumber = parseInt(input[0]);
    let k = 1;

    for (let i = 1; k <= 1000; i++){

        if (i % 3 != 0 && i%10 !=3){
            polycarp[k] = i;
            k++;
        }

    }

    for (let i = 1; i <= testCaseNumber; i++){
        let a = input[i];
        a = parseInt(a);
        console.log(polycarp[a]);
    }

}

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

process.stdin.on('end', function(chunk){
    solve();
})

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

let c = 0;
const k = [];

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

    let i = 1;
    while (k.length <= 1000) {
      if (i % 3 === 0 || i % 10 === 3) {
        i++;
        continue;
      }

      k.push(i);
      i++;
    }
    return;
  }

  console.log(k[Number(d - 1)]);

  c++;
});

rl.on("close", () => {});

// Common Template Starts //
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let inputString = ""
let currentLine = 0

process.stdin.on("data", inputStdin => inputString += inputStdin)

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

const readline = () => inputString[currentLine++]
// Common Template Ends //

// Driver Function Starts //
const main = () => {
    console.clear()

    let n   = 0
    let arr = []
    let str = ''

    let nums = generateUptoNwithoutK(1000, 3)

    // with testcases
    //*
    let t = parseInt( readline() )
    while (t--) {
        n   = parseInt( readline() )
        // arr = readline().split(' ').map(Number)
        // str = readline()
        console.log( solve(n, nums, arr, str) )
    }
    //*/

    // without testcases
    /*
        n   = parseInt( readline() )
        arr = readline().split(' ').map(Number)
        str = readline()
        console.log( solve(n, arr, str) )
    //*/
}
// Driver Function Ends //

const generateUptoNwithoutK = (n, k) => {
    let a = [], i = 1
    while( a.length <= n ){
        // if( i%k != 0 && !stringHasCharacter(i.toString(), k ) ) a.push( i )
        if( i%k != 0 && i%10 != k ) a.push( i )
        i++
    }
    return a
}

// MAIN LOGIC
const solve = (n, nums, arr, str) => {

    return nums[n-1]
}

const isOdd         = (num) => num & 1
const isEven        = (num) => !(num & 1)
const minOfArray    = (arr) => Math.min.apply(null, arr)
const maxOfArray    = (arr) => Math.max.apply(null, arr)
const uniqueArray   = (arr) => [...new Set(arr)]
const sortArray     = (arr) => arr.sort((a, b) => a - b)
const sortDesc      = (arr) => arr.sort( (a, b) =>  b - a )
const isSorted      = (arr) => arr.every((v, i, a) => !i || a[i - 1] <= v)
const sumOfArray    = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)
const splitAt       = index => x => [x.slice(0, index), x.slice(index)]
const elemFrequency = (arr) => arr.reduce( (acc, curr) => { return acc[curr] ? ++acc[curr] : acc[curr] = 1, acc }, {})

const reverseText            = (str)        =>  str.split('').reverse().join('')
const stringHasDuplicates    = (str)        => (/([a-z])\1/i).test(str)
const stringHasDuplicateChar = (str, char)  => str.indexOf(char) !== str.lastIndexOf(char)
const stringHasCharacter     = (str, char)  => str.indexOf(char) > -1 ? true : false

const findAllIndicesOfChar = (str, char) => {
    str = str.split('')
    let indices = [];
    for (let i = 0; i < str.length; i++) {
        if (str[i] === char) indices.push(i);
    }
    return indices
}

const isUpper       = str => !/[a-z]/.test(str) && /[A-Z]/.test(str)
const escapeRegExp  = (string) => string.replace(/[.*+\-?^$$${}()|[\]\\]/g, '\\$$$&')
const replaceAll    = (str, find, replace) => str.replace(new RegExp(escapeRegExp(find), 'g'), replace)

const findUnique = (str) => {
    return [...str].reduce((acc, curr) => {
        return acc.includes(curr) ? acc : acc + curr;
    }, "")
}

const unique = (str) => {
    const cleanStr = str.replace(/ /gi, '');
    const set = [...new Set(cleanStr)];
    return set;
}

process.stdin.resume();
process.stdin.setEncoding("utf8");
process.stdin.on("data", function(chunk) {
  let data = chunk.trim().split("\n");
  let times = parseInt(data[0]);
  let map = [...Array(10e3).keys()].filter(e => {
    return !(e % 3 === 0 || e % 10 === 3);
  }).slice(0, 1000);
  for(let i = 1; i <= times; i++) {
    let [ num ] = data[i].trim().split(" ").map(Number);
    console.log(map[num - 1]);
  }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function main() {
  let tests = parseInt(readline());
  while (tests--) {
    let k = parseInt(readline());
    let num = 0;
    for (let i = 0; i < k; i++) {
      num++;
      while (num % 10 === 3 || num % 3 === 0) num++;
    }
    console.log(num);
  }
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    var a = [];
    for(var l = 1; l < 1667; l++){
        if(l % 10 == 3 || l % 3 === 0){

        }else{
            a.push(l);
        }
    }
    for(var j = 1; j <= n; j++){
        var k = lines[j];
        console.log(a[k - 1]);
    }
});

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

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

let nl = nextLine();

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

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

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

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

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

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	let a = [];
	for(let i = 0; a.length <= 1000; i++){
		if (i % 3 != 0 && i % 10 != 3) {
			a.push(i);
		}
	}
	for(let i = 0; i < t; i++){
		let k = nl.num();
		ans.push(a[k-1]);
	}
	console.log(ans.join('\n'));
};

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

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

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

function main () {
	let T = rn();
	while (T--) {
		let k = rn();

		let nxt = 0;
		while (k) {
			nxt++;
			k -= nxt%3 && nxt%10 != 3;
		}

		const ans = nxt;

		console.log(ans);
	}
}

/**
 * Bismillahir Rahmanir Rahim
 * This code has been taken from: https://codeforces.com/blog/entry/69610
 */
 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++];
 }

 /****** BELOW HERE START WRITING YOUR CODE IN main() FUNCTION   ***************************************/
 /**
  * Use "readLine()" function for input, which will return a string consisting the entire line, so accordingly split the string
  * when required.
  *
  * I am using console.log() to output
  */
//  function main() {
//      let t = readLine();
//      t = parseInt(t);
//      console.log("mai yahan aaya")
//      while(t--) {
//          let line = readLine();
//          line = line.split(" ");
//          let n = parseInt(line[0]);
//          let m = parseInt(line[1]);
//          if(n === 1) {
//              console.log("0");
//          } else if (n === 2) {
//              console.log(m);
//          } else {
//              console.log(2*m);
//          }
//      }
//  }

function main() {

	let t = parseInt(readLine());
	results = []
	precompute(results);
	// t = parseInt(t);
	while(t--) {
		let n = readLine();
		n = parseInt(n);
		//let s = readLine().split(" ").map(item=>parseInt(item));
		console.log(solve(n));

	}
    // console.log(t);
}

function solve(n) {
	return results[n-1];
}

function precompute(results) {
	k = 1 ;
	i = 1 ;
	while(k<=1000) {
		if (i%3===0 || i%10===3) i++;
		else {
			results.push(i);
			i++;
			k++;
		}
	}
}

const readline = require('readline')

const read = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const inputString = []

read.on('line', (input) => {
  inputString.push(input.trim());
})
read.on('close', () => {

  main(inputString.map(num => parseInt(num)).filter(Boolean));
})

function main(nums) {
  const total = nums[0];
  const remaining = nums.slice(1)
  const max = Math.max(...remaining.slice(0,total));
  const list = [];
  let i = 1;
  while(list.length < max){
    if(i%3 !== 0 && i%10 !== 3){
      list.push(i)
    }
    i++;
  }
  remaining.forEach(element => {
    console.log(list[element-1]);
  });
}

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

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ************************ Code Start ***************************

function main() {

  var t=parseInt(readline())

while(t--){
    var k=parseInt(readline())

    for(var i=1;;i++){
        if(i%3==0 ||(i%10==3)){
           continue;
        }
        k--;
        if(k==0){
            print(i)
            break;
        }

    }
}

}

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

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

function main(input) {
    input = input.split("\n");
    let z = 0;
    let testCases = +input[z++];

    while(testCases--){
        let index = +input[z++];
        let number = 0;
        for (let i = 1; i <= index; i++) {
            if((i % 3) == 0 || i.toString()[i.toString().length - 1] == '3'){
                index++;
            }
            number++;
        }
        if((number % 3) == 0 || number.toString()[number.toString().length - 1] == '3'){
            number++;
        }
        console.log(number);
    }
}

// define file test.inp
// npm install -D @types/node
process.stdin.resume();
process.stdin.setEncoding("utf8");
var jsin = "";
var input = [];
var jscur = 0;
var readLine = function () { return input[jscur++]; };
var readLines = function () { return readLine().split(' '); };
var readInt = function () { return +(readLine()); };
var readInts = function () { return readLine().split(' ').map(function (x) { return +(x); }); };
var debug = function () {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    console.log("[" + args.join(",") + "]");
};
process.stdin.on('data', function (chunk) { return jsin += chunk; });
process.stdin.on('end', function () {
    input = jsin.split('\n').filter(function (curline) { return curline !== ''; });
    // multitest
    var nTest = readInt();
    while (nTest--) {
        main();
    }
});
//// CODE BELOW
function main() {
    var k = readInt();
    var val = 1;
    for (; k > 0; ++val) {
        if (val % 3 == 0 || val % 10 == 3) {
            continue;
        }
        --k;
    }
    console.log(val - 1);
}

// var arr = [];
// for (var j = 1; arr.length <= 1000; j++) {
//     if (j % 3 == 0 || j % 10 == 3) {
//         continue;
//     } else {
//         arr.push(j);
//     }
//     //console.log(j);
// }

// //console.log((arr));
// var t = Number(readline());

// for (var i = 1; i <= t; i++) {
//     var n = Number(readline());
//     console.log(arr[n - 1]);

// }

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

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

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

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

// ************************ Code Start ***************************

function main() {
    var arr = [];
    for (var j = 1; arr.length <= 1000; j++) {
        if (j % 3 == 0 || j % 10 == 3) {
            continue;
        } else {
            arr.push(j);
        }
        //console.log(j);
    }

    //console.log((arr));
    var t = Number(readline());

    for (var i = 1; i <= t; i++) {
        var n = Number(readline());
        console.log(arr[n - 1]);

    }

}

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const assert = (condition) => { if (!condition) throw new Error("Assertion failed"); }
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const int = parseInt;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg2 = Math.log2;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };
const initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
const ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);
const isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 08/18/21 morning
 * https://codeforces.com/contest/1560/problem/A
 */
let dp = [];
const solve = (k) => {
    // pr(k);
    pr(dp[k - 1]);
};

const endWithThree = (x) => {
    let s = x + '';
    return s[s.length - 1] == '3';
};

const prepare = () => {
    let x = 1;
    while (dp.length < 1001) {
        if (x % 3 != 0 && !endWithThree(x)) dp.push(x);
        x++;
    }
};

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

main()

// pr(hasThree(13))

let inputs = []

function read() {
    return inputs.pop();
}

function readInt() {
    return parseInt(read());
}

function solve() {
    ar = []
    for (let i = 1; i < 1e4; i++) {
        if (i % 3 != 0 && i % 10 != 3) {
            ar.push(i);
        }
    }
    let test = readInt();
    while (test--) {
        let k = readInt();
        console.log(ar[k - 1]);
    }
}

function main() {
    inputs = inputString.replace(' ', '\n').trim().split('\n').map((string) => string.trim());
    inputs.reverse();
    solve();
}

let inputString = '';

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

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

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++]
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        console.log(solve(n))
    }
// })()
})

function solve(n) {
    let k = 0
    while (n--) {
        k++
        while ((k % 10) === 3 || !(k % 3)) {
            k++
        }
    }
    return k
}

'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++];
}

var maxN = 2 * 1e5 + 10
var mod = BigInt(1e9 + 7)

function main() {
  const xx = readline();
  var array = []
  var i=0
  while (true) {
    i++
    if (array.length === 1000) break
    if (i % 3 === 0 || i % 10 === 3) continue
    array.push(i)

  }
  // console.log(array)
  Array(Number(xx)).fill(1).map((t, i) => {
    var n = parseInt(readline());

    console.log(array[n - 1])
  })
}

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readLineAsNumber() {
    return Number(this.readLine())
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(String(e))
  }
  println(e) {
    stdout.write(String(e)), stdout.write('\n')
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
const nums = [0]
for (
  let e = 1;
  e < 1e7 && !(e % 3 != 0 && e % 10 != 3 && (nums.push(e), nums.length > 1010));
  ++e
);
function solve(e) {
  return nums[e]
}
__main__(function (e) {
  const n = e.readLineAsNumber()
  for (let t = 1; t <= n; ++t) {
    const n = solve(e.readLineAsNumber())
    e.print(n + '\n')
  }
})

const arr = [];
let i = 0;
while(arr.length < 1000) {
   i++;
   if (i % 10 === 3 || i % 3 === 0) {
      continue;
   }
   arr.push(i);
}

function solve() {
   const k = Number(read());
   write(arr[k - 1]);
}

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

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

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

function readArray(f) {
   return read().split(' ').map(f);
}

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

// var fs = new require('fs');
var arr = new Array();
var t = 0;
while(arr.length < 1000) {
  if(t % 10 != 3 && t % 3 != 0){
    arr.push(t);
  }
  t++;
}
var t = Number(readline()); // readline()
while(t > 0) {
  var a = Number(readline());
//   if(t != 0) { //
//     a = 10 - t; //
//   } //
//   else { //
//     a = 1000; //
//   } // redline()
  print(arr[a-1]);
  t--;
}

var nLoop = readline();
var dataArray = [];
var MAX_NUM = 2000;

for(var j = 1, indx = 0; j <= MAX_NUM; j++) {
    if ( j%3 !== 0 && j%10 !== 3 ) {
        dataArray[indx] = j;
        indx++;
    }
}

for(var i = 0; i < nLoop; i++) {
    inpUser = readline();
    print(dataArray[inpUser - 1]);
}

var input = readline();

function getSequense() {
    var seq = [];

    for (var i = 1; seq.length <= 1000; i++) {
      var isEnd3 = ("" + i).slice(-1) === "3"
      var isCratne = i % 3 === 0;

      if (!(isEnd3 || isCratne)) {
        seq.push(i);
      }
    }

    return seq;
}

var sequense = getSequense();
for(var i=0;i<=input;i++) {
    var value = readline();

    if(value) {
        print(sequense[value-1])
    }
}

// 1560 A -Dislike of Threes

// number tests
var numTests = parseInt( readline() );

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

    // input data
    var numMaxDislike = parseInt( readline() );
    var str = numMaxDislike.toString()

    // variable program
    var numDislike = 0;
    var numberReach = 0;

    // old version
    /*
    for (var i = 1; i < numMaxDislike; i++) {
        var str = i.toString();
        if( i % 3 != 0 && str.charAt( str.length-1 ) != '3' ){
            k++;
        }
    }
    */

    // new version
    while ( numDislike < numMaxDislike){

        // trasform integer to string
        var str = (numberReach+1).toString();

        // numero non divisibile per 3 e che non finisca con 3 alla fine
        if( (numberReach+1) % 3 != 0 && str.charAt( str.length-1 ) != '3' ){
            numDislike++;
        }

        // increment the couter
        numberReach++

    }

    // output - print number raggiunto da numeri like, arrivando a k numeri dislike same a numMaxDislike
    print(numberReach);

}

var a=[1]
var num=2
while(a.length<1000){
    if(num%3!==0&&num%10!==3)a.push(num)
    num++
}
var n=readline()
for(i=0;i<n;i++){
    var x=readline()
    print(a[x-1])
}

function run(){
    var n = readline();
    var ct = 0;
    for(var i = 1; ;i++){
        if(i % 3 == 0 || i % 10 == 3) continue;
        ct++;
        if(ct == n){
            print(i);
            return;
        }
    }
}

var tc = readline();
while(tc--) {
    run();
}

var t = parseInt(readline());

var list = [];

for(var i = 1; i < 2000; ++i) {
    if ((i % 10) === 3 || (i % 3) === 0) continue;
    list.push(i);
}

for (var i = 0; i < t; ++i) {
    var k = parseInt(readline());
    print(list[k-1]);
}

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL); /*your input text, split by lines*/

    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
      if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
        seq.push(i);
      }
    }

    let [count, ...entry] = lines;

    for(let z = 0; z < entry.length; z++) {
      console.log(seq[entry[z]-1])
    }
    process.exit();
    return;

});

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL); /*your input text, split by lines*/

    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
      if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
        seq.push(i);
      }
    }

    let [count, ...entry] = lines;

    for(let z = 0; z < entry.length; z++) {
      console.log(seq[entry[z]-1])
    }
    return 0;

});

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

var input= '', readline, print;

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

process.stdin.on('end', function() {
    input = input.split('\n');
    print = function(data) {process.stdout.write(data)};
    var inputLineIndex = 0;
    readline = function(){return inputLineIndex>=input.length?undefined:input[inputLineIndex++]};
    main();
});

function main()
{
  const lines = [...input]; /*your input text, split by lines*/

  const seq = [];

  for (let i = 1; seq.length <= 1000; i++) {
    if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
      seq.push(i);
    }
  }

  let [count, ...entry] = lines;

  for(let z = 0; z < entry.length; z++) {
    console.log(seq[entry[z]-1])
  }
}

const { EOL } = require("os");
let inp = "";
process.stdin.on("data", (c) => (inp+= c));
process.stdin.on("end", () => {
  const lines1 = inp.split(EOL); /*your input text, split by lines*/
m(lines1)
});

function m(lines) {

    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
      if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
        seq.push(i);
      }
    }

    let [count, ...entry] = lines;

    for(let z = 0; z < entry.length; z++) {
      console.log(seq[entry[z]-1])
    }
    return 0;
}

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL); /*your input text, split by lines*/

    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
      if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
        seq.push(i);
      }
    }

    let [count, ...entry] = lines;

    for(let z = 0; z < entry.length; z++) {
      console.log(seq[entry[z]-1],'\n')
    }
    return 0;

});

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL); /*your input text, split by lines*/

  function main() {
    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
      if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
        seq.push(i);
      }
    }

    let [count, ...entry] = lines;
    console.log(entry)

    for(let z = 0; z < entry.length; z++) {
      console.log(seq[entry[z]-1])
    }
    return 0;
  }
  main()
});

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL); /*your input text, split by lines*/

  function main() {
    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
      if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
        seq.push(i);
      }
    }

    let [count, ...entry] = lines;
    entry.forEach((k) => {
      console.log(seq[k-1])
    });
    return 0;
  }
  main()
});

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL); /*your input text, split by lines*/

  function main() {
    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
      if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
        seq.push(i);
      }
    }

    let [count, ...entry] = lines;

    entry.forEach((k) => {
      console.log(seq[k-1])
    });
  }
});

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL); /*your input text, split by lines*/

  function main() {
    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
      if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
        seq.push(i);
      }
    }

    let [count, ...entry] = lines;

    entry.forEach((k) => {
      console.log(seq[k-1])
    });
  }
  main()
});

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL); /*your input text, split by lines*/

  function main() {
    let out = [];
    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
      if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
        seq.push(i);
      }
    }

    let [count, ...entry] = lines;

    entry.forEach((k) => {
      out.push(seq[k]);
      console.log(seq[k])
    });
    // console.log(out)
    // return 0;
  }
  main()
});

let i = "";
process.stdin.on("data", (c) => (i += c));
process.stdin.on("end", () => {
  const { EOL } = require("os");
  const lines = i.split(EOL); /*your input text, split by lines*/

  function main() {
    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
      if (!(!(i % 3) || ("" + i).slice(-1) === "3")) {
        seq.push(i);
      }
    }

    let [count, ...entry] = lines;

    entry.forEach((k) => {
      console.log(seq[k]);
    });
    return 0;
  }
});

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

var input= '', readline, print;

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

process.stdin.on('end', function() {
    input = input.split('\n');
    print = function(data) {process.stdout.write(data+'\n')};
    var inputLineIndex = 0;
    readline = function(){return inputLineIndex>=input.length?undefined:input[inputLineIndex++]};
    process.exit(main() || 0);
});

function main()
{
    const seq = [];

    for (let i = 1; seq.length <= 1000; i++) {
        if(!(!(i % 3) || (''+i).slice(-1) === '3')) {
            seq.push(i)
        }
      }

    let [count, ...entry] =  input;

    entry.forEach(k => {
        console.log(seq[k])
    });
    return 0;
}

main()

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL); /*your input text, split by lines*/
        var s = 0
        var b = 0
        for(j = 1; j <= lines[0]; j ++){
            var a = lines[j]
            while(b <= lines[0]){
                b++
                if(b % 3 === 0 || b[b.length - 1] == 3){
                    b+=2
                    Number(lines[0]+3)

                }
                console.log(b)

            }

        }

})

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL); /*your input text, split by lines*/
    var s = 0
    var p = 0
    for(j = 1; j<=lines[0]; j++){
        var a = lines[j]
        if(a != 3 || a % 3 === 0){
            p++
        }
    }
    for(k = 0; k < p; k++){
        var ak = lines[j]
        console.log(ak)
        }
});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL); /*your input text, split by lines*/
    var s = 0
    for(j = 1; j<=lines[0]; j++){
        var a = lines[j]
        if(a != 3 || a % 3 === 0){
            s = a
            console.log(s)
        }
    }

});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL); /*your input text, split by lines*/
    var s = 0
    for(j = 1; j<=lines[0]; j++){
        var a = lines[j]
        if(a != 3 || a % 3 === 0){
            s = a
            console.log(a)
        }
    }

});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL); /*your input text, split by lines*/
    var s = 0
    for(j = 1; j<=lines[0]; j++){
        var a = lines[j]
        var b = a.split('')
        if(b != 3 || a % 3 === 0){
            s = a
        }
        console.log(a)
    }

});

let data = "";

function solve(){

    let polycarp = [];
    let input = data.split(/ |\n/);
    let testCaseNumber = parseInt(input[0]);
    let k = 1;

    for (let i = 1; k <= 1000; i++){

        if (i % 3 != 0 && i%10 !=3){
            polycarp[k] = i;
            k++;
        }

    }

    for (let i = 1; i <= testCaseNumber; i++){
        let a = input[i];
        console.log(parseInt(polycarp[a]));
    }

}

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

process.stdin.on('end', function(chunk){
    solve();
})

let data = "";

function solve(){

    let polycarp = [1001];
    let input = data.split(/ |\n/);
    let testCaseNumber = parseInt(input[0]);
    let k = 1;

    for (let i = 1; k <= 1000; i++){

        if (i % 3 != 0 && i%10 !=3){
            polycarp[k] = i;
            k++;
        }

    }

    for (let i = 1; i <= testCaseNumber; i++){
        let a = input[i];
        parseInt(a);
        console.log(polycarp[a]);
    }

}

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

process.stdin.on('end', function(chunk){
    solve();
})

let data = "";

function solve(){

    let polycarp = [1001];
    let input = data.split(/ |\n/);
    let testCaseNumber = parseInt(input[0]);
    let k = 1;

    for (let i = 1; k <= 1000; i++){

        if (i % 3 != 0 && i%10 !=3){
            polycarp[k] = i;
            k++;
        }

    }

    for (let i = 1; i <= testCaseNumber; i++){
        let a = input[i];
        console.log(polycarp[a]);
    }

}

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

process.stdin.on('end', function(chunk){
    solve();
})

let data = "";

function solve(){

    let polycarp = [1001];
    let input = data.split(/ |\n/);
    let testCaseNumber = parseInt(input[0]);
    let k = 1;
    let a = 1;

    for (let i = 1; k <= 1000; i++){

        if (i % 3 != 0 && i%10 !=3){
            polycarp[k] = i;
            k++;
        }

    }

    for (let i = 0; i < testCaseNumber; i++){
        console.log(polycarp[a]);
        a++;
    }

}

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

process.stdin.on('end', function(chunk){
    solve();
})

let data = "";

function solve(){

    let polycarp = [1001];
    let input = data.split(/ |\n/);
    let testCaseNumber = parseInt(input[0]);
    let k = 1;
    let a = 1;

    for (let i = 1; k <= 1000; i++){

        if (i % 3 != 0 && i%10 !=3){
            polycarp[k] = i;
            k++
        }

    }

    for (let i = 0; i < testCaseNumber; i++){
        console.log(polycarp[a]);
        a++;
    }

}

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

process.stdin.on('end', function(chunk){
    solve();
})

// var fs = new require('fs');
var arr = new Array();
var t = 0;
while(arr.length < 1000) {
  if(t % 10 != 3 && t % 3 != 0){
    arr.push(t);
  }
  t++;
}
var t = Number(readline()); // readline()
while(t > -1) {
  var a = Number(readline());
//   if(t != 0) { //
//     a = 10 - t; //
//   } //
//   else { //
//     a = 1000; //
//   } // redline()
  print(arr[a-1]);
  t--;
}

var nLoop = readline();
var dataArray = [];
var MAX_NUM = 10;

for(var j = 1, indx = 0; j <= MAX_NUM; j++) {
    if ( j%3 !== 0 && j%10 !== 3 ) {
        dataArray[indx] = j;
        indx++;
    }
}

for(var i = 0; i < nLoop; i++) {
    inpUser = readline();
    print(dataArray[inpUser - 1]);
}


'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n),
        m = rn(),
        res = new Array(m),
        f = new Array(n),
        g = new Array(n),
        max = [0, 0],
        s = new Array(n);
  for (let i = 0; i < n; i++) {
    let d = i - a[i] + 1;
    if (max[0] < d) {
      max[1] = max[0];
      max[0] = d;
    } else if (max[1] < d) {
      max[1] = d;
    }
    f[i] = Math.max(0, max[0]);
    g[i] = Math.max(0, max[1]);
    if (i) s[i] = [s[i - 1][0] + f[i], s[i - 1][1] + g[i]];else s[i] = [f[i], g[i]];
  }
  s[n] = s[n - 1];
  const search = (nums, l, r, d) => {
    while (l < r) {
      const m = l + r >> 1;
      if (nums[m] >= d) {
        r = m;
      } else {
        l = m + 1;
      }
    }
    return r;
  };
  let ans = n * (n + 1) / 2;
  for (let x = 0; x < m; x++) {
    var _f;
    let [i, v] = rns(2);
    i--;
    const d = Math.max(i - v + 1, (_f = f[i - 1]) !== null && _f !== void 0 ? _f : 0);
    if (d === f[i]) res[x] = ans - s[n - 1][0];else {
      if (d > f[i]) {
        const j = search(f, i + 1, n, d);
        res[x] = ans - (s[n - 1][0] - s[j - 1][0] + (j - i) * d);
        if (i) res[x] -= s[i - 1][0];
      } else {
        const j = search(g, i, n, d),
              k = search(g, j, n, f[i]);
        res[x] = ans - (s[n - 1][0] - s[k - 1][0] + (j - i) * d + (s[k - 1][1] - s[j - 1][1]));
        if (i) res[x] -= s[i - 1][0];
      }
    }
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n),
        m = rn(),
        res = new Array(m),
        f = new Array(n),
        g = new Array(n),
        max = [0, 0],
        s = new Array(n);
  for (let i = 0; i < n; i++) {
    let d = i - a[i] + 1;
    if (max[0] < d) {
      max[1] = max[0];
      max[0] = d;
    } else if (max[1] < d) {
      max[1] = d;
    }
    f[i] = Math.max(0, max[0]);
    g[i] = Math.max(0, max[1]);
    if (i) s[i] = [s[i - 1][0] + f[i], s[i - 1][1] + g[i]];else s[i] = [f[i], g[i]];
  }
  s[n] = s[n - 1];
  const search = (nums, l, r, d) => {
    while (l < r) {
      const m = l + r >> 1;
      if (nums[m] >= d) {
        r = m;
      } else {
        l = m + 1;
      }
    }
    return r;
  };
  const b = new Array(m);
  let ans = n * (n + 1) / 2;
  for (let x = 0; x < m; x++) {
    var _f;
    let [i, v] = rns(2);
    i--;
    b[x] = [i, v, x];
    const d = Math.max(i - v + 1, (_f = f[i - 1]) !== null && _f !== void 0 ? _f : 0);
    if (d === f[i]) res[x] = ans - s[n - 1][0];else {
      if (d > f[i]) {
        const j = search(f, i + 1, n, d);
        res[x] = ans - (s[n - 1][0] - s[j - 1][0] + (j - i) * d);
        if (i) res[x] -= s[i - 1][0];
      } else {
        const j = search(g, i, n, d),
              k = search(g, j, n, f[i]);
        res[x] = ans - (s[n - 1][0] - s[k - 1][0] + (j - i) * d + (s[k - 1][1] - s[j - 1][1]));
        if (i) res[x] -= s[i - 1][0];
      }
    }
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n),
        m = rn(),
        res = new Array(m),
        f = new Array(n),
        g = new Array(n),
        max = [0, 0],
        s = new Array(n);
  for (let i = 0; i < n; i++) {
    let d = i - a[i] + 1;
    if (max[0] < d) {
      max[1] = max[0];
      max[0] = d;
    } else if (max[1] < d) {
      max[1] = d;
    }
    f[i] = Math.max(0, max[0]);
    g[i] = Math.max(0, max[1]);
    if (i) s[i] = [s[i - 1][0] + f[i], s[i - 1][1] + g[i]];else s[i] = [f[i], g[i]];
  }
  s[n] = s[n - 1];
  const search = (nums, l, r, d) => {
    while (l < r) {
      const m = l + r >> 1;
      if (nums[m] >= d) {
        r = m;
      } else {
        l = m + 1;
      }
    }
    return r;
  };
  const b = new Array(m);
  let ans = n * (n + 1) / 2;
  for (let x = 0; x < m; x++) {
    var _f;
    let [i, v] = rns(2);
    i--;
    b[x] = [i, v, x];
    const d = Math.max(i - v + 1, (_f = f[i - 1]) !== null && _f !== void 0 ? _f : 0);
    if (d === f[i]) res[x] = ans - s[n - 1][0];else {
      if (d > f[i]) {
        const j = search(f, i + 1, n, d);
        res[x] = ans - (s[n - 1][0] - s[j - 1][0] + (j - i) * d);
        if (i) res[x] -= s[i - 1][0];
      } else {
        var _s$, _s;
        const j = search(g, i, n, d),
              k = search(g, j + 1, n, f[i]);
        res[x] = ans - (s[n - 1][0] - s[k - 1][0] + (j - i) * d + (s[k - 1][1] - ((_s$ = (_s = s[j - 1]) === null || _s === void 0 ? void 0 : _s[1]) !== null && _s$ !== void 0 ? _s$ : 0)));
        if (i) res[x] -= s[i - 1][0];
      }
    }
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n),
        m = rn(),
        b = new Array(m);
  for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];
  b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);
  const dp = new Array(n).fill(0),
        sum = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    var _dp, _sum;
    dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);
  }
  const st = [];
  const res = [];
  let pre = n - 1;
  for (let i = n - 1, j = m - 1; i >= 0 && j >= 0; i--) {
    if (i === n - 1 || dp[i + 1] <= dp[i]) {
      pre = i;
    }
    const d = dp[i] - i;
    while (st.length && st[st.length - 1][0] > d) {
      st.pop();
    }
    if (!st.length || d > st[st.length - 1][0]) st.push([d, i]);
    while (j >= 0 && b[j][0] === i) {
      if (b[j][1] < dp[i]) {
        var _sum2;
        const d = b[j][1] - i;
        let l = 0,
            r = st.length;
        while (l < r) {
          const m = l + r >> 1;
          if (st[m][0] < d) {
            l = m + 1;
          } else {
            r = m;
          }
        }
        const [, k] = st[l];
        const x = k - i + 1;
        res[b[j][2]] = ((_sum2 = sum[i - 1]) !== null && _sum2 !== void 0 ? _sum2 : 0) + (sum[n - 1] - sum[k]) + b[j][1] * x + x * (x - 1) / 2;
      } else {
        var _dp2;
        let d = Math.min((_dp2 = dp[i - 1]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1] - 1) + 1;
        if (dp[i] === d) res[b[j][2]] = sum[n - 1];else {
          const x = pre - i + 1;
          d -= dp[i];
          res[b[j][2]] = sum[n - 1] + x * d;
        }
      }
      j--;
    }
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n),
        m = rn(),
        b = new Array(m);
  for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];
  b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);
  const dp = new Array(n).fill(0),
        sum = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    var _dp, _sum;
    dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);
  }
  const st = [];
  const res = [];
  let pre = n - 1;
  for (let i = n - 1, j = m - 1; i >= 0; i--) {
    if (i === n - 1 || dp[i + 1] <= dp[i]) {
      pre = i;
    }
    const d = dp[i] - i;
    while (st.length && st[st.length - 1][0] > d) {
      st.pop();
    }
    if (!st.length || d > st[st.length - 1][0]) st.push([d, i]);
    while (j >= 0 && b[j][0] === i) {
      if (b[j][0] === n - 1) {
        var _sum2, _dp2;
        res[b[j][2]] = ((_sum2 = sum[n - 2]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Math.min((_dp2 = dp[n - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1] - 1) + 1;
        j--;
        continue;
      } else if (b[j][1] < dp[i]) {
        var _sum3;
        const d = b[j][1] - i;
        let l = 0,
            r = st.length;
        while (l < r) {
          const m = l + r >> 1;
          if (st[m][0] < d) {
            l = m + 1;
          } else {
            r = m;
          }
        }
        const [, k] = st[l];
        const x = k - i + 1;
        res[b[j][2]] = ((_sum3 = sum[i - 1]) !== null && _sum3 !== void 0 ? _sum3 : 0) + (sum[n - 1] - sum[k]) + b[j][1] * x + x * (x - 1) / 2;
      } else {
        var _dp3;
        if (dp[i] < a[i] || dp[i] === ((_dp3 = dp[i - 1]) !== null && _dp3 !== void 0 ? _dp3 : 0) + 1) res[b[j][2]] = sum[n - 1];else {
          const x = pre - i + 1,
                d = Math.min(b[j][1] - a[i], dp[i - 1] + 1 - dp[i]);
          res[b[j][2]] = sum[n - 1] + x * d;
        }
      }
      j--;
    }
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n),
        m = rn(),
        b = new Array(m);
  for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];
  b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);
  const dp = new Array(n).fill(0),
        sum = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    var _dp, _sum;
    dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);
  }
  const st = [];
  const res = [];
  let pre = n - 1;
  for (let i = n - 1, j = m - 1; i >= 0; i--) {
    if (i === n - 1 || dp[i + 1] <= dp[i]) {
      const d = dp[i] - i;
      pre = i;
      while (st.length && st[st.length - 1][0] >= d) {
        st.pop();
      }
      st.push([d, i]);
    }
    while (j >= 0 && b[j][0] === i) {
      if (b[j][0] === n - 1) {
        var _sum2, _dp2;
        res[b[j][2]] = ((_sum2 = sum[n - 2]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Math.min((_dp2 = dp[n - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1] - 1) + 1;
        j--;
        continue;
      } else if (b[j][1] < dp[i]) {
        var _sum3;
        const d = b[j][1] - i;
        let l = 0,
            r = st.length;
        while (l < r) {
          const m = l + r >> 1;
          if (st[m][0] < d) {
            l = m + 1;
          } else {
            r = m;
          }
        }
        const [, k] = st[l];
        const x = k - i + 1;
        res[b[j][2]] = ((_sum3 = sum[i - 1]) !== null && _sum3 !== void 0 ? _sum3 : 0) + (sum[n - 1] - sum[k]) + b[j][1] * x + x * (x - 1) / 2;
      } else {
        var _dp3;
        if (dp[i] < a[i] || dp[i] === ((_dp3 = dp[i - 1]) !== null && _dp3 !== void 0 ? _dp3 : 0) + 1) res[b[j][2]] = sum[n - 1];else {
          const x = pre - i + 1,
                d = Math.min(b[j][1] - a[i], dp[i - 1] + 1 - dp[i]);
          res[b[j][2]] = sum[n - 1] + x * d;
        }
      }
      j--;
    }
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n),
        m = rn(),
        b = new Array(m);
  for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];
  b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);
  const dp = new Array(n).fill(0),
        sum = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    var _dp, _sum;
    dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);
  }
  const st = [];
  const res = [];
  let pre = n - 1;
  for (let i = n - 1, j = m - 1; i >= 0; i--) {
    if (i === n - 1 || dp[i + 1] <= dp[i]) {
      const d = dp[i] - i;
      pre = i;
      while (st.length && st[st.length - 1][0] > d) {
        st.pop();
      }
      st.push([d, i]);
    }
    while (j >= 0 && b[j][0] === i) {
      if (b[j][0] === n - 1) {
        var _sum2, _dp2;
        res[b[j][2]] = ((_sum2 = sum[n - 2]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Math.min((_dp2 = dp[n - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1] - 1) + 1;
        j--;
        continue;
      } else if (b[j][1] < dp[i]) {
        var _sum3;
        const d = b[j][1] - i;
        let l = 0,
            r = st.length;
        while (l < r) {
          const m = l + r >> 1;
          if (st[m][0] < d) {
            l = m + 1;
          } else {
            r = m;
          }
        }
        const [, k] = st[l];
        const x = k - i + 1;
        res[b[j][2]] = ((_sum3 = sum[i - 1]) !== null && _sum3 !== void 0 ? _sum3 : 0) + (sum[n - 1] - sum[k]) + b[j][1] * x + x * (x - 1) / 2;
      } else {
        var _dp3;
        if (dp[i] < a[i] || dp[i] === ((_dp3 = dp[i - 1]) !== null && _dp3 !== void 0 ? _dp3 : 0) + 1) res[b[j][2]] = sum[n - 1];else {
          const x = pre - i + 1,
                d = Math.min(b[j][1] - a[i], dp[i - 1] + 1 - dp[i]);
          res[b[j][2]] = sum[n - 1] + x * d;
        }
      }
      j--;
    }
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

var fs = require('fs');

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

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

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n),
        m = rn(),
        b = new Array(m);
  for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];
  b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);
  const dp = new Array(n).fill(0),
        sum = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    var _dp, _sum;
    dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);
  }
  const tr = new BinarySearchTree((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);
  const res = [];
  let pre = n - 1;
  for (let i = n - 1, j = m - 1; i >= 0; i--) {
    if (dp[i + 1] <= dp[i]) {
      pre = i;
      tr.insert([dp[i] - i, i]);
    }
    while (j >= 0 && b[j][0] === i) {
      if (b[j][0] === n - 1) {
        var _sum2, _dp2;
        res[b[j][2]] = ((_sum2 = sum[n - 2]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Math.min((_dp2 = dp[n - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1] - 1) + 1;
        j--;
        continue;
      } else if (b[j][1] < dp[i]) {
        var _sum3;
        const [, k] = tr.ceiling([b[j][1] - i, i]);
        const x = k - i + 1;
        res[b[j][2]] = ((_sum3 = sum[i - 1]) !== null && _sum3 !== void 0 ? _sum3 : 0) + (sum[n - 1] - sum[k]) + b[j][1] * x + x * (x - 1) / 2;
      } else {
        var _dp3;
        if (dp[i] < a[i] || dp[i] === ((_dp3 = dp[i - 1]) !== null && _dp3 !== void 0 ? _dp3 : 0) + 1) res[b[j][2]] = sum[n - 1];else {
          const x = pre - i + 1,
                d = Math.min(b[j][1] - a[i], dp[i - 1] + 1 - dp[i]);
          res[b[j][2]] = sum[n - 1] + x * d;
        }
      }
      j--;
    }
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}
class BinarySearchTree {
  constructor(_compare = (a, b) => a - b) {
    _defineProperty(this, "root", null);
    _defineProperty(this, "length", 0);
    _defineProperty(this, "min", null);
    _defineProperty(this, "max", null);
    _defineProperty(this, "minCache", true);
    _defineProperty(this, "maxCache", true);
    _defineProperty(this, "deleteResult", false);
    this._compare = _compare;
    this.compare = this.compare.bind(this);
  }
  isT(t) {
    return t !== undefined && t !== null;
  }
  compare(a, b) {
    const {
      isT
    } = this;
    if (isT(a) && isT(b)) return this._compare(a, b);
    if (isT(a)) return 1;
    if (isT(b)) return -1;
    return 0;
  }
  isEmpty() {
    return !this.root;
  }
  size() {
    return this.root ? this.root.size : 0;
  }
  getRoot() {
    return this.root;
  }
  getMin() {
    if (this.minCache) {
      return this.min;
    }
    const min = this.searchKth(this.size());
    this.min = min;
    this.minCache = true;
    return min;
  }
  getMax() {
    if (this.maxCache) {
      return this.max;
    }
    const max = this.searchKth(1);
    this.max = max;
    this.maxCache = true;
    return max;
  }
  balance(node) {
    node.height = this.getHeight(node);
    const blance = this.getBalance(node);
    let res;
    if (Math.abs(blance) === 2) {
      if (blance > 0) {
        var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;
        const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);
        if (heightDif > 0) {
          res = this.rotateRight(node);
        } else if (heightDif < 0) {
          res = this.rotateLeftRight(node);
        }
      } else {
        var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;
        const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);
        if (heightDif > 0) {
          res = this.rotateRightLeft(node);
        } else if (heightDif < 0) {
          res = this.rotateLeft(node);
        }
      }
    }
    return res ? res : node;
  }
  rotateRight(node) {
    const left = node.left;
    const leftRight = left.right;
    left.right = node;
    node.left = leftRight;
    node.height = this.getHeight(node);
    left.height = this.getHeight(left);
    node.size = this.getSize(node);
    left.size = this.getSize(left);
    return left;
  }
  rotateLeft(node) {
    const right = node.right;
    const rightLeft = right.left;
    right.left = node;
    node.right = rightLeft;
    node.height = this.getHeight(node);
    right.height = this.getHeight(right);
    node.size = this.getSize(node);
    right.size = this.getSize(right);
    return right;
  }
  rotateLeftRight(node) {
    node.left = this.rotateLeft(node.left);
    return this.rotateRight(node);
  }
  rotateRightLeft(node) {
    node.right = this.rotateRight(node.right);
    return this.rotateLeft(node);
  }
  getBalance(node) {
    return this.getHeight(node.left) - this.getHeight(node.right);
  }
  getHeight(node) {
    var _node$left$height, _node$left3, _node$right$height, _node$right3;
    if (!node) return 0;
    return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;
  }
  getSize(node) {
    var _node$left$size, _node$left4, _node$right$size, _node$right4;
    if (!node) return 0;
    return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;
  }
  createNode(val) {
    return {
      id: Math.random() * new Date().valueOf(),
      val,
      left: null,
      right: null,
      size: 1,
      height: 1,
      count: 1
    };
  }
  insert(val) {
    let cur = this.createNode(val);
    if (this.isEmpty()) {
      this.root = cur;
      this.length++;
    } else {
      [, cur] = this.insertNode(this.root, cur);
    }
    if (this.min === null || this.compare(this.min, val) > 0) {
      this.min = val;
    }
    if (this.max === null || this.compare(this.max, val) < 0) {
      this.max = val;
    }
  }
  insertNode(node, cur, parent = null) {
    node.size++;
    const compareResult = this.compare(cur.val, node.val);
    let res;
    if (compareResult === 0) {
      node.count++;
      return [false, node];
    } else if (compareResult > 0) {
      if (node.right) {
        res = this.insertNode(node.right, cur, node);
        if (!res[0]) return res;
      } else {
        node.right = cur;
        this.length++;
        res = [true, cur];
      }
    } else {
      if (node.left) {
        res = this.insertNode(node.left, cur, node);
        if (!res[0]) return res;
      } else {
        node.left = cur;
        this.length++;
        res = [true, cur];
      }
    }
    let preHeight = node.height;
    const newNode = this.balance(node);
    if (newNode === node && node.height === preHeight) {
      res = [false, res[1]];
    } else if (newNode !== node) {
      if (parent) {
        parent.left === node ? parent.left = newNode : parent.right = newNode;
      } else {
        this.root = newNode;
      }
      res = [false, res[1]];
    }
    return res;
  }
  delete(val) {
    this.deleteResult = false;
    if (!this.root) return this.deleteResult;
    this.deleteNode(val, this.root, null);
    return this.deleteResult;
  }
  deleteNode(val, node, parent) {
    if (!node) return null;
    let res = this.compare(val, node.val);
    if (res === 0) {
      this.deleteResult = true;
      node.count--;
      node.size--;
      if (node.count > 0) return node;
      if (!node.left || !node.right) {
        if (this.min === val) {
          this.minCache = false;
        }
        if (this.max === val) {
          this.maxCache = false;
        }
        this.length--;
        if (!parent) {
          var _node$left5;
          this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;
          return this.root;
        } else {
          var _node$left6;
          return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;
        }
      } else {
        const selectLeft = node.left.height > node.right.height;
        let replaceNode = selectLeft ? this.pre(node) : this.next(node),
            name = selectLeft ? 'left' : 'right';
        node.val = replaceNode.val;
        node.count = replaceNode.count;
        replaceNode.count = 0;
        node[name] = this.deleteNode(replaceNode.val, node[name], node);
      }
    } else if (res > 0) {
      node.right = this.deleteNode(val, node.right, node);
    } else {
      node.left = this.deleteNode(val, node.left, node);
    }
    node.size = this.getSize(node);
    node.height;
    const newNode = this.balance(node);
    if (parent) {
      parent.left === node ? parent.left = newNode : parent.right = newNode;
    } else {
      this.root = newNode;
    }
    return newNode;
  }
  next(node) {
    let next = node.right;
    while ((_next = next) !== null && _next !== void 0 && _next.left) {
      var _next;
      next = next.left;
    }
    return next;
  }
  pre(node) {
    let pre = node.left;
    while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {
      var _pre;
      pre = pre.right;
    }
    return pre;
  }
  search(val, compare) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);
    return node.val;
  }
  searchCeilingNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        return this.searchCeilingNode(node.right, val, compare, node);
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        const [p, value] = this.searchCeilingNode(node.left, val, compare, node);
        if (compare(value.val, val) < 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    }
  }
  ceiling(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, this.compare);
    return this.compare(node.val, val) >= 0 ? node.val : null;
  }
  searchFloorNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        const [p, value] = this.searchFloorNode(node.right, val, compare, node);
        if (compare(value.val, val) > 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        return this.searchFloorNode(node.left, val, compare, node);
      } else {
        return [parent, node];
      }
    }
  }
  floor(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchFloorNode(this.root, val, this.compare);
    return this.compare(node.val, val) <= 0 ? node.val : null;
  }
  searchKth(k) {
    if (this.isEmpty()) {
      return null;
    }
    if (k <= 0 || k > this.size()) {
      return null;
    }
    const node = this.searchNodeKth(this.root, k);
    return node.val;
  }
  searchNodeKth(node, k) {
    var _node$right$size2, _node$right5, _node$right$size3, _node$right6;
    const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;
    if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;
    if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);
  }
  countGreaterThanEq(val) {
    if (!this.root) return 0;
    return this.countCompare(val, (a, b) => this._compare(a, b), this.root);
  }
  countCompare(val, compare, node, pre = 0) {
    const res = compare(val, node.val);
    if (res === 0) {
      var _node$right$size4, _node$right7;
      return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;
    } else if (res > 0) {
      if (node.right) {
        return this.countCompare(val, compare, node.right, pre);
      } else {
        return pre;
      }
    } else {
      var _node$right$size5, _node$right8;
      let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;
      if (node.left) {
        return this.countCompare(val, compare, node.left, count);
      } else {
        return count;
      }
    }
  }
  toArray() {
    if (!this.root) return [];
    const res = [];
    const dfs = node => {
      if (node.left) dfs(node.left);
      res.push(node.val);
      if (node.right) dfs(node.right);
    };
    dfs(this.root);
    return res;
  }
}

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

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns(n),
        m = rn(),
        b = new Array(m);
  for (let i = 0; i < m; i++) b[i] = [rn() - 1, rn(), i];
  b.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);
  const dp = new Array(n).fill(0),
        sum = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    var _dp, _sum;
    dp[i] = Math.min(a[i] - 1, (_dp = dp[i - 1]) !== null && _dp !== void 0 ? _dp : 0) + 1;
    sum[i] = dp[i] + ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0);
  }
  const st = [];
  const res = [];
  for (let i = n - 1, j = m - 1; i >= 0; i--) {
    if (!st.length || dp[st[st.length - 1]] <= dp[i]) st.push(i);
    while (j >= 0 && b[j][0] === i) {
      if (b[j][0] === n - 1) {
        var _sum2, _dp2;
        res[b[j][2]] = ((_sum2 = sum[n - 2]) !== null && _sum2 !== void 0 ? _sum2 : 0) + Math.min((_dp2 = dp[n - 2]) !== null && _dp2 !== void 0 ? _dp2 : 0, b[j][1]) + 1;
        j--;
        continue;
      }
      if (b[j][1] < dp[i]) {
        var _sum3;
        let len = dp[i] - b[j][1] - 1;
        let l = 0,
            r = st.length - 1;
        while (l < r) {
          const m = l + r + 1 >> 1;
          if (st[m] >= i + len) {
            l = m;
          } else {
            r = m - 1;
          }
        }
        const x = st[l] - i + 1;
        res[b[j][2]] = ((_sum3 = sum[i - 1]) !== null && _sum3 !== void 0 ? _sum3 : 0) + (sum[n - 1] - sum[st[l]]) + b[j][1] * x + x * (x - 1) / 2;
      } else {
        var _dp3;
        if (dp[i] < a[i] || dp[i] === ((_dp3 = dp[i - 1]) !== null && _dp3 !== void 0 ? _dp3 : 0) + 1) res[b[j][2]] = sum[n - 1];else {
          const x = st[st.length - 1] - i + 1,
                d = Math.min(b[j][1] - a[i], dp[i - 1] + 1 - dp[i]);
          res[b[j][2]] = sum[n - 1] + x * d;
        }
      }
      j--;
    }
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

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