Vasya is choosing a laptop. The shop has n laptops to all tastes.Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.If all three properties of a laptop are strictly less than those properties of some other laptop, then the first laptop is considered outdated by Vasya. Among all laptops Vasya does not consider outdated, he chooses the cheapest one.There are very many laptops, which is why Vasya decided to write a program that chooses the suitable laptop. However, Vasya doesn't have his own laptop yet and he asks you to help him.

The first line contains number n (1 ≤ n ≤ 100). Then follow n lines. Each describes a laptop as speed ram hdd cost. Besides,    speed, ram, hdd and cost are integers  1000 ≤ speed ≤ 4200 is the processor's speed in megahertz  256 ≤ ram ≤ 4096 the RAM volume in megabytes  1 ≤ hdd ≤ 500 is the HDD in gigabytes  100 ≤ cost ≤ 1000 is price in tugriks  All laptops have different prices.

Print a single number — the number of a laptop Vasya will choose. The laptops are numbered with positive integers from 1 to n in the order in which they are given in the input data.

NoteIn the third sample Vasya considers the first and fifth laptops outdated as all of their properties cannot match those of the third laptop. The fourth one is the cheapest among the laptops that are left. Thus, Vasya chooses the fourth laptop.


You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.

The first line of the input contains following integers:   n: the number of towers in the building (1 ≤ n ≤ 108),  h: the number of floors in each tower (1 ≤ h ≤ 108),  a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 ≤ a ≤ b ≤ h),  k: total number of queries (1 ≤ k ≤ 104).  Next k lines contain description of the queries. Each description consists of four integers ta, fa, tb, fb (1 ≤ ta, tb ≤ n, 1 ≤ fa, fb ≤ h). This corresponds to a query to find the minimum travel time between fa-th floor of the ta-th tower and fb-th floor of the tb-th tower.

For each query print a single integer: the minimum walking time between the locations in minutes.

function main() {
  const is = new Scanner();
  const [n, h, a, b, k] = is.nextArray(Number);
  let lengthPath, i, j, x, y;
  for (let q = 0; q < k; q += 1) {
    [i, j, x, y] = is.nextArray(Number);
    if (i === x) {
      console.log(Math.abs(y - j));
    } else {
      lengthPath = 0;
      if (j < a) {
        lengthPath += Math.abs(a - j);
        j = a;
      } else if (j > b) {
        lengthPath += Math.abs(b - j);
        j = b;
      }
      lengthPath += Math.abs(x - i);
      lengthPath += Math.abs(y - j);
      console.log(lengthPath);
    }
  }
}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = -1;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    this.index += 1;
    return this.lines[this.index].trim();
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

readline = require('readline')

rl = readline.createInterface({input: process.stdin})

let n, h, a, b, k, numLines = 0, queries = []
rl.on('line', line => {
    const integersList = line.split(' ').map(x => parseInt(x))
    if (++numLines == 1) {
        [n, h, a, b, k] = integersList
    } else {
        queries.push(integersList)
    }
}).on('close', () => {
    queries.forEach(query => {
        let [ta, fa, tb, fb] = query, clamp = (x, l, r) => x <= l ? l : (x >= r ? r : x)
        const steps = [
            ta != tb ? Math.abs(fa - clamp(fa, a, b)) : 0,
            Math.abs(ta - tb),
            ta != tb ? Math.abs(fb - clamp(fa, a, b)) : Math.abs(fb - fa)
        ]
        process.stdout.write(`${steps.reduce((a, x) => a + x)}\n`)
    })
})

/**
 * cf 1020a
 */
const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});

var data,n,h,a,b,k,ta,tb,fa,fb;
rl.on('line', (line) => {
  data=line.split(' ').map(i => parseInt(i));
  if(data.length===5){
    [n,h,a,b,k]=data;
  }
  else{
    [ta,fa,tb,fb]=data;
    var ans=Math.abs(ta-tb);
    if(ta!=tb){
      if(fa>b&&fb>b){
        ans+=fa-b+fb-b;
      }
      else if(fa<a&&fb<a){
          ans+=a-fa+a-fb;
      }
      else{
          ans+=Math.abs(fa-fb);
      }
    }
    else{
      ans+=Math.abs(fa-fb);
    }

    console.log(ans);
  }
});

/*
3 6 2 3 3
1 2 1 3
1 4 3 4
1 2 2 3
*/

var inputs = readline().split(' ').map(i => +i);
var towersCount = inputs[0]
var towerHeight = inputs[1]
var lowestPassage = inputs[2]
var highestPassage = inputs[3]
var queries = inputs[4];

for (i = 0; i < queries; i++) {
  var queryInputs = readline().split(' ').map(i => +i);
  var startingTower = queryInputs[0]
  var startingFloor = queryInputs[1]
  var targetTower = queryInputs[2]
  var targetFloor = queryInputs[3];
  var passageFloor = startingFloor > highestPassage ? highestPassage
    : startingFloor < lowestPassage ? lowestPassage : startingFloor;

  if (startingTower === targetTower)
    print(Math.abs(startingFloor - targetFloor));
  else
    print(Math.abs(startingTower - targetTower) + Math.abs(startingFloor - passageFloor) + Math.abs(targetFloor - passageFloor));
}

function main() {
  const is = new Scanner();
  const [n, h, a, b, k] = is.nextArray(Number);
  let lengthPath, i, j, x, y;
  for (let q = 0; q < k; q += 1) {
    [i, j, x, y] = is.nextArray(Number);
    if (i === x) {
      console.log(Math.abs(y - j));
    } else {
      lengthPath = 0;
      if (j < a) {
        console.log('a');
        lengthPath += Math.abs(a - j);
        j = a;
      } else if (j > b) {
        lengthPath += Math.abs(b - j);
        j = b;
      }
      lengthPath += Math.abs(x - i);
      lengthPath += Math.abs(y - j);
      console.log(lengthPath);
    }
  }
}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = -1;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    this.index += 1;
    return this.lines[this.index].trim();
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

readline = require('readline')

rl = readline.createInterface({input: process.stdin})

let n, h, a, b, k, numLines = 0, queries = []
rl.on('line', line => {
    const integersList = line.split(' ').map(x => parseInt(x))
    if (++numLines == 1) {
        [n, h, a, b, k] = integersList
    } else {
        queries.push(integersList)
    }
}).on('close', () => {
    queries.forEach(query => {
        let [ta, fa, tb, fb] = query, clamp = (x, l, r) => x <= l ? l : (x >= r ? r : x)
        const steps = [
            ta != fa ? Math.abs(fa - clamp(fa, a, b)) : 0,
            Math.abs(ta - tb),
            Math.abs(fb - clamp(fa, a, b))
        ]
        process.stdout.write(`${steps.reduce((a, x) => a + x)}\n`)
    })
})

/**
 * cf 1020a
 */
const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});

var data,n,h,a,b,k,ta,tb,fa,fb;
rl.on('line', (line) => {
  data=line.split(' ').map(i => parseInt(i));
  if(data.length===5){
    [n,h,a,b,k]=data;
  }
  else{
    [ta,fa,tb,fb]=data;
    var ans=Math.abs(ta-tb);
    if(fa>b&&fb>b){
      ans=eval(ans+fa-b+fb-b);
    }
    else if(fa<a&&fb<a){
        ans+=a-fa+a-fb;
    }
    else{
        ans+=Math.abs(fa-fb);
    }
    console.log(ans);
  }
});

/*
3 6 2 3 3
1 2 1 3
1 4 3 4
1 2 2 3
*/

var inputs = readline().split(' ').map(i => +i);
var towersCount = inputs[0]
var towerHeight = inputs[1]
var lowestPassage = inputs[2]
var highestPassage = inputs[3]
var queries = inputs[4];

for (i = 0; i < queries; i++) {
  var queryInputs = readline().split(' ').map(i => +i);
  var startingTower = queryInputs[0]
  var startingFloor = queryInputs[1]
  var targetTower = queryInputs[2]
  var targetFloor = queryInputs[3];
  var passageFloor = startingFloor > highestPassage ? highestPassage
    : startingFloor < lowestPassage ? lowestPassage : startingFloor;

  var moves = Math.abs(startingTower - targetTower) + Math.abs(startingFloor - passageFloor) + Math.abs(targetFloor - passageFloor);
  print(moves);
}

const inputs = readline().split(' ').map(i => +i);
const towersCount = inputs[0]
const towerHeight = inputs[1]
const lowestPassage = inputs[2]
const highestPassage = inputs[3]
const queries = inputs[4];

for (i = 0; i < queries; i++) {
  const queryInputs = readline().split(' ').map(i => +i);
  const startingTower = queryInputs[0]
  const startingFloor = queryInputs[1]
  const targetTower = queryInputs[2]
  const targetFloor = queryInputs[3];
  const passageFloor = startingFloor > highestPassage ? highestPassage
    : startingFloor < lowestPassage ? lowestPassage : startingFloor;

  const moves = Math.abs(startingTower - targetTower) + Math.abs(startingFloor - passageFloor) + Math.abs(targetFloor - passageFloor);
  print(moves);
}


Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.

The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.

For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.

NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.

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

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

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

  let t = parseInt(arr.shift())

  let i = 0
  while(t --) {
    const n = parseInt(arr[i++])
    // console.log('n', n)
    if(n == 1){
      i++
      console.log(0)
      continue
    }

    let flag = false
    let intervals = new Array(n)

    for(let j = 0; j < n; j++, i++) {
      // console.log(arr[i])
      intervals[j] = arr[i].split(' ').map(a => parseInt(a))
    }

    // console.log(intervals)
    intervals.sort((a, b) => a[0] - b[0])
    // console.log(intervals)

    let x = intervals[0]

    for(let j = 1; j < n; j++) {
      if(x[1] < intervals[j][0] && !flag){
        flag = true
        x[0] = x[1]
        x[1] = intervals[j][0]
      }
      else if(x[1] < intervals[j][0] && flag){
        x[1] = intervals[j][0]
      }
      else if(!flag){
        x[0] = Math.min(x[1], intervals[j][1])
        x[1] = Math.min(x[1], intervals[j][1])
      }
      else {
        x[1] = Math.min(x[1], intervals[j][1])
      }
      // console.log(x)
    }

    console.log(x[1] - x[0])
  }
})

'use strict'

var t=parseInt(readline());

while(t--)
{
    var mx=0,mm=1000000000;
    var n=parseInt(readline());

    for(var i=1;i<=n;i++){
        var s=readline().split(' ').map(Number);
        var a=s[0],b=s[1];
        mx=Math.max(mx,a);
        mm=Math.min(mm,b);
    }
    print((mx-mm<=0)?"0":mx-mm);
}

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

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

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

  let t = parseInt(arr.shift())

  let i = 0
  while(t --) {
    const n = parseInt(arr[i++])
    // console.log('n', n)
    if(n == 1){
      i++
      console.log(0)
      continue
    }

    let flag = false
    let intervals = new Array(n)

    for(let j = 0; j < n; j++, i++) {
      // console.log(arr[i])
      intervals[j] = arr[i].split(' ').map(a => parseInt(a))
    }

    intervals.sort((a, b) => a[0] - b[0])

    let x = intervals[0]

    for(let j = 1; j < n; j++) {
      if(x[1] < intervals[j][0] && !flag){
        flag = true
        x[0] = x[1]
        x[1] = intervals[j][0]
      }
      else if(x[1] < intervals[j][0] && flag){
        x[0] = x[0]
        x[1] = intervals[j][0]
      }
      else {
        x[0] = x[1]
      }
    }

    console.log(x[1] - x[0])
  }
})


The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times. When he came to the fruit stall of Ashot, he saw that the seller hadn't distributed price tags to the goods, but put all price tags on the counter. Later Ashot will attach every price tag to some kind of fruits, and Valera will be able to count the total price of all fruits from his list. But Valera wants to know now what can be the smallest total price (in case of the most «lucky» for him distribution of price tags) and the largest total price (in case of the most «unlucky» for him distribution of price tags).

The first line of the input contains two integer number n and m (1 ≤ n, m ≤ 100) — the number of price tags (which is equal to the number of different kinds of fruits that Ashot sells) and the number of items in Valera's list. The second line contains n space-separated positive integer numbers. Each of them doesn't exceed 100 and stands for the price of one fruit of some kind. The following m lines contain names of the fruits from the list. Each name is a non-empty string of small Latin letters which length doesn't exceed 32. It is guaranteed that the number of distinct fruits from the list is less of equal to n. Also it is known that the seller has in stock all fruits that Valera wants to buy.

Print two numbers a and b (a ≤ b) — the minimum and the maximum possible sum which Valera may need to buy all fruits from his list.

6 5
3 5 1 6 8 1
peach
grapefruit
banana
orange
orange

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var numPrices = integers[0], numFruits = integers[1];
	var prices = tokenizeIntegers(readline());

	var fruits = [], fruitCounts = {};
	for (var i = 0; i < numFruits; i += 1) {
		var fruit = trim(readline());
		if (fruitCounts[fruit] === undefined) {
			fruits.push(fruit);
			fruitCounts[fruit] = 1;
		}
		else {
			fruitCounts[fruit] += 1;
		}
	}

	var counts = [];
	for (var i = 0; i < fruits.length; i += 1) {
		counts.push(fruitCounts[fruits[i]]);
	}
	var cmp = function (a, b) {
		return a-b;
	};
	counts.sort(cmp);
	prices.sort(cmp);
	//print("counts: "+counts.join(" "));
	//print("prices: "+prices.join(" "));

	var best = 0, worst = 0;
	for (var i = 0; i < counts.length; i += 1) {
		best += counts[i] * prices[counts.length-1-i];
		worst += counts[counts.length-1-i] * prices[prices.length-1-i];
	}

	print([best, worst].join(' '));
}

main();


Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations?Help Yaroslav.

The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value.

In a single line print the answer to the problem — the maximum sum that Yaroslav can get.

NoteIn the first sample you do not need to change anything. The sum of elements equals 150.In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.

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

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

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

function main() {
	var n = parseInt(readline()),
		m = 2*n-1,
		data = tokenizeIntegers(readline()),
		minus = 0, zero = 0, sum = 0, smallest = 1000;
	for (var i = 0; i < m; ++i) {
		var x = data[i];
		if (x < 0) {
			++minus;
		} else if (x == 0) {
			++zero;
		}
		x = Math.abs(x);
		sum += x;
		smallest = Math.min(smallest, x);
	}
	if (minus > n) {
		minus -= n;
	}
	if (minus%2 == 1) {
		minus = n-minus;
	}
	if (minus%2 == 1 && zero == 0) {
		sum -= 2*smallest;
	}
	print(sum);
}

main();

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

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

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

function main() {
	var n = parseInt(readline()),
		m = 2*n-1,
		data = tokenizeIntegers(readline()),
		minus = 0, zero = 0, sum = 0, smallest = 1000;
	for (var i = 0; i < m; ++i) {
		var x = data[i];
		if (x < 0) {
			++minus;
		} else if (x == 0) {
			++zero;
		}
		x = Math.abs(x);
		sum += x;
		smallest = Math.min(smallest, x);
	}
	if (minus % 2 == 1 && zero == 0) {
		sum -= 2*smallest;
	}
	print(sum);
}

main();

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

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

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

function main() {
	var n = parseInt(readline()),
		m = 2*n-1,
		data = tokenizeIntegers(readline()),
		minus = 0, zero = 0, sum = 0, smallest = 1000;
	for (var i = 0; i < m; ++i) {
		var x = data[i];
		if (x < 0) {
			++minus;
		} else if (x == 0) {
			++zero;
		}
		x = Math.abs(x);
		sum += x;
		smallest = Math.min(smallest, x);
	}
	if (minus % 2 == 1 && zero == 0) {
		sum -= smallest;
	}
	print(sum);
}

main();

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

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

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

function main() {
	var n = parseInt(readline()),
		m = 2*n-1,
		data = tokenizeIntegers(readline()),
		minus = 0, zero = 0, sum = 0, smallest = 1000;
	for (var i = 0; i < m; ++i) {
		var x = data[i];
		if (x < 0) {
			++minus;
		} else if (x == 0) {
			++zero;
		}
		x = Math.abs(x);
		sum += x;
		smallest = Math.min(smallest, x);
	}
	if (minus % 2 == 1 && minus != n && zero == 0) {
		sum -= 2*smallest;
	}
	print(sum);
}

main();


In Berland, $$$n$$$ different types of banknotes are used. Banknotes of the $$$i$$$-th type have denomination $$$10^{a_i}$$$ burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly $$$1$$$.Let's denote $$$f(s)$$$ as the minimum number of banknotes required to represent exactly $$$s$$$ burles. For example, if the denominations of banknotes used in Berland are $$$1$$$, $$$10$$$ and $$$100$$$, then $$$f(59) = 14$$$: $$$9$$$ banknotes with denomination of $$$1$$$ burle and $$$5$$$ banknotes with denomination of $$$10$$$ burles can be used to represent exactly $$$9 \cdot 1 + 5 \cdot 10 = 59$$$ burles, and there's no way to do it with fewer banknotes.For a given integer $$$k$$$, find the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes (that is, $$$f(s) > k$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10; 1 \le k \le 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 = a_1 < a_2 < \dots < a_n \le 9$$$).

For each test case, print one integer — the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes.

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 [n, k] = rna();
		const a = rna();
		a.push(18);
		++n;

		++k;
		let ans = 0n;
		for (let i = 1; k && i < n; i++) {
			const most = 10**(a[i]-a[i-1]) - 1;
			const take = Math.min(most, k);
			k -= take;

			ans += BigInt(take)*BigInt(10**a[i-1]);
		}

		console.log(ans.toString());
	}
}

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 [n, k] = rna();
		const a = rna();
		a.push(1e20);
		++n;

		++k;
		let ans = 0n;
		for (let i = 1; k && i < n; i++) {
			const use = Math.min(k, 10**a[i]/10**a[i-1] - 1);
			k -= use;

			ans += BigInt(use)*BigInt(10**a[i-1]);
		}

		console.log(ans.toString());
	}
}

'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 foo(x) {

    console.log(x);
}

function bank_notes(n, arr, k){
  arr.sort(function(a, b) {
  return a - b;
});
  for(var i=0; i<n; i++){
    arr[i] = Math.pow(10,arr[i]);
  }
  var count = k+1;
  var ans = 0n;
  for(var i=0; i<n; i++){
    var cnt = count;
    if(i+1<n){
      cnt = Math.min(cnt, arr[i+1]/arr[i]-1);
    }
    ans = ans + BigInt(arr[i])*BigInt(cnt);
    count -= cnt;
    if(count==0)break;
  }
  return ans.toString();
}

function main() {
    const t = parseInt(readline());
    var inp;
    for (var i = 0; i<t; i++){
        inp = readline().split(" ");
        var n = parseInt(inp[0]);
        var k = parseInt(inp[1]);
        var arr = readline().split(" ").map(x=>parseInt(x));
        var ans = bank_notes(n,arr,k);
        foo(ans);
    }
}

const readline = require('readline')

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

function solve(n, ok, arr) {
    let ans = 0n
    let k = ok + 1
    for (let i = 0; i < arr.length; i++) {
        const cur = Math.pow(10, arr[i])
        const limit = i === n - 1 ? k : (Math.pow(10, arr[i + 1]) / cur - 1)
        // console.log(cur, limit)
        ans += mul(Math.min(k, limit), cur)
        k -= limit
        if (k <= 0) break
    }
    return ans
}
function mul(a, b) {
    return BigInt(a) * BigInt(b)
}

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 readLine = () => dataitr.next().value.trim();
function rl () {
	let ans = readLine().split(' ');
	if (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));
	return ans.length == 1 ? ans[0] : ans;
}

function main () {
	let t = rl();
	while (t--) {
		let [n, k] = rl();
		let a = rl();

		let m = k + 1, ans = 0, i = 0;
		a.push(Number.POSITIVE_INFINITY);
		while (m) {
			x = Math.pow(10, a[i + 1] - a[i]) - 1;
			let used = Math.min(m, x);
			m -= used;
			ans += used * Math.pow(10, a[i]);
			i++;
		}

		console.log(ans);
	}
}


Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are n cities in Berland and neighboring countries in total and exactly n - 1 two-way roads. Because of the recent financial crisis, the Berland Government is strongly pressed for money, so to build a new road it has to close some of the existing ones. Every day it is possible to close one existing road and immediately build a new one. Your task is to determine how many days would be needed to rebuild roads so that from each city it became possible to reach all the others, and to draw a plan of closure of old roads and building of new ones.

The first line contains integer n (2 ≤ n ≤ 1000) — amount of cities in Berland and neighboring countries. Next n - 1 lines contain the description of roads. Each road is described by two space-separated integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — pair of cities, which the road connects. It can't be more than one road between a pair of cities. No road connects the city with itself.

Output the answer, number t — what is the least amount of days needed to rebuild roads so that from each city it became possible to reach all the others. Then output t lines — the plan of closure of old roads and building of new ones. Each line should describe one day in the format i j u v — it means that road between cities i and j became closed and a new road between cities u and v is built. Cities are numbered from 1. If the answer is not unique, output any.

var pai = [];
var rank = [];
var cycles = [];
var leaders = [];

function find(cur)
{
	if( pai[cur] == cur ) return cur;

	pai[cur] = find( pai[cur] );
	return pai[cur];
}

function join(i , j)
{
	i = find( i );
	j = find( j );

	if( rank[i] < rank[j] ) swap( i , j );

	pai[j] = i;
	if( rank[i] == rank[j] ) rank[i]++;
}

var n = readline();

for(var i = 1 ; i <= n ; i++)
	pai[i] = i;

for(var i = 1 ; i < n ; i++)
{
    var edge = readline().split(' ');

    var U = edge[0];
    var V = edge[1];

    if( find(U) == find(V) ) cycles.push( edge );
    else join( U , V );
}

for(var i = 1 ; i <= n ; i++)
    if( pai[i] == i ) leaders.push( i );

var size = cycles.length;

print(size);

for(var i = 0 ; i < size ; i++)
    print(cycles[i][0] + " " + cycles[i][1] + " " + leaders[i] + " " + leaders[i + 1]);


Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!The only thing Mrs. Smith remembered was that any permutation of $$$n$$$ can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.The sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS). A subsequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ where $$$1\leq i_1 < i_2 < \ldots < i_k\leq n$$$ is called increasing if $$$a_{i_1} < a_{i_2} < a_{i_3} < \ldots < a_{i_k}$$$. If $$$a_{i_1} > a_{i_2} > a_{i_3} > \ldots > a_{i_k}$$$, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.For example, if there is a permutation $$$[6, 4, 1, 7, 2, 3, 5]$$$, LIS of this permutation will be $$$[1, 2, 3, 5]$$$, so the length of LIS is equal to $$$4$$$. LDS can be $$$[6, 4, 1]$$$, $$$[6, 4, 2]$$$, or $$$[6, 4, 3]$$$, so the length of LDS is $$$3$$$.Note, the lengths of LIS and LDS can be different.So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.

The only line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of permutation that you need to build.

Print a permutation that gives a minimum sum of lengths of LIS and LDS.  If there are multiple answers, print any.

NoteIn the first sample, you can build a permutation $$$[3, 4, 1, 2]$$$. LIS is $$$[3, 4]$$$ (or $$$[1, 2]$$$), so the length of LIS is equal to $$$2$$$. LDS can be ony of $$$[3, 1]$$$, $$$[4, 2]$$$, $$$[3, 2]$$$, or $$$[4, 1]$$$. The length of LDS is also equal to $$$2$$$. The sum is equal to $$$4$$$. Note that $$$[3, 4, 1, 2]$$$ is not the only permutation that is valid.In the second sample, you can build a permutation $$$[2, 1]$$$. LIS is $$$[1]$$$ (or $$$[2]$$$), so the length of LIS is equal to $$$1$$$. LDS is $$$[2, 1]$$$, so the length of LDS is equal to $$$2$$$. The sum is equal to $$$3$$$. Note that permutation $$$[1, 2]$$$ is also valid.

const vIn = [];
let itIn = 0;
const getNext = () => vIn[itIn++];
const getInt = () => parseInt(getNext(), 10);
const forEachN = (n, cb, flagInt = false) => {
  const nextItIn = itIn + n;
  const fn = flagInt ? getInt : getNext;
  while (itIn !== nextItIn) cb(fn());
};

class SolveProblemClass {
  constructor() {
  }

  solveAll() {
    const n = getInt();
    const m = parseInt(Math.sqrt(n), 10);
    const g = Math.ceil(n / m);
    const v = [];
    for (let i = m; i >= 1 ; i--) v.push([]);
    let it = 0;
    let j = 0;
    for (let i = 1; i <= n ; i++) {
      v[it][j++] = i;
      if (j === g) {
        j = 0;
        it++;
      }
    }
    let res = [];
    v.forEach((l) => {
      for (let i = l.length - 1; i >= 0 ; i--) {
        res.push(l[i]);
      }
    });
    console.log(res.join(' '));
  }
}

const processData = (input) => {
  input.split('\n').forEach(line => {
    // vIn.push(line);
    line.split(' ').forEach(item => { vIn.push(item); });
  });
};

const solveP = new SolveProblemClass();
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", (input) => {
  _input += input;
});
process.stdin.on("end", () => {
  processData(_input);
  solveP.solveAll();
});


Let's consider all integers in the range from $$$1$$$ to $$$n$$$ (inclusive).Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $$$\mathrm{gcd}(a, b)$$$, where $$$1 \leq a < b \leq n$$$.The greatest common divisor, $$$\mathrm{gcd}(a, b)$$$, of two positive integers $$$a$$$ and $$$b$$$ is the biggest integer that is a divisor of both $$$a$$$ and $$$b$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^6$$$).

For each test case, output the maximum value of $$$\mathrm{gcd}(a, b)$$$ among all $$$1 \leq a < b \leq n$$$.

NoteIn the first test case, $$$\mathrm{gcd}(1, 2) = \mathrm{gcd}(2, 3) = \mathrm{gcd}(1, 3) = 1$$$.In the second test case, $$$2$$$ is the maximum possible value, corresponding to $$$\mathrm{gcd}(2, 4)$$$.

'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(){
    var t=readline();
    while (t--)
    {
        var n=readline();
        console.log(Math.floor(n/2));
    }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (inputStd) => {
  inputString += inputStd;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    let high = +readLine();
    console.log(solve(high));
  }

  function solve(high) {
    return Math.floor(high / 2);
  }
}

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

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    output[i] = Math.floor(N / 2);
  }
  myout(myconv(output, 9));
}

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

let stdinInput = '';

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

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

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 1;
    let t = 1;
    outer:
    while (t <= testCases) {
        const n = data[t] * 1;
        let high = n;
        let count = Array(high + 1).fill(0);
        for (let i = 2; i <= n; i += 1) count[i]++;
        let counter = 0;
        for (let i = high; i >= 1; i -= 1) {
          let j = i;
          while(j <= high) {
            if (count[j] > 0) counter += count[j];
            j += i;
            if (counter === 2) {
              console.log(i);
              t += 1;
              continue outer;
            }
          }
          counter = 0;
        }
        console.log(1);
        t += 1;
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let input = '';
process.stdin.on('data', (line) => {
    input += line;
});
process.stdin.on('end', () => {
    const lines = input.split('\n');
    let tests = parseInt(lines.shift(), 10);
    while (tests--) {
        const n = parseInt(lines.shift(), 10);
        console.log(Math.floor(n / 2));
    }
});
// input helper
function lineToNumArray(line) {
    return line.split(' ').map(element => parseInt(element, 10));
}

const testInput = [
    '2',
    '23423',
    '12312',
    '543534',
    '24223',
    '43534543',
    '43856092',
    '6598392'
];

const {EOL} = require('os')
function getInput(test = false) {
    return new Promise((res,rej) => {
        if (test) res(testInput);
        let i = ''
        process.stdin.on('data', c => i += c)
        process.stdin.on('end', () => {
            res(i.split(EOL));
        })
    })
}

function output(lines) {
    process.stdout.write(lines.join(EOL));
}

getInput(false).then(lines => {
    lines.pop();
    const amount = lines.shift();
    const inputs = lines.map(element => parseInt(element));
    const answer = [];
    inputs.forEach(num => {
        answer.push(greatestGCF(num));
    })
    output(answer);
})

const greatestGCF = (n) => {
    n-=n%2;
    return n/2;
}

const processData = (lines) => {
  let acc = 0
  const n = +lines[acc]
  acc++
  for (let i=0; i<n; i++) {
    const a = +lines[acc]
    acc++
    if (a > 3) {
      console.log(Math.floor(a/2))
    } else {
      console.log(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*/
  processData(lines)
})

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

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

const s2i = s => parseInt(s, 10);

function main() {
  const T = s2i(readLine());
  for(let i = 0; i < T; i++) {
    const x = s2i(readLine());

    console.log(Math.floor(x/2));
  }
}

'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++];
}
/**
2
3
5

**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function main() {
    let n = parseInt(readline());

    for(let i=0;i<n;i++) {
        solve();
    }

}

function solve() {
    let a = parseInt(readline());

    if(a % 2 === 0) {
        console.log(a / 2);
    } else {
        console.log((a-1) / 2);
    }

}

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var x = +readline();
    print(x % 2 ? (x - 1) / 2 : x / 2);
  }

}

main();

"use strict";

//readline().split(' ').map(Number);

function sec(){
    var n = readline();
    n -= n%2;
    print(parseInt(n/2));
}

function main(){
    var t = readline();
    while(t--){
        sec();
    }
}

main();

function solve(n) {
    return n === 1 ? n : Math.floor(n/2);
}
var t = Number(readline());
while (t--) {
    var n = Number(readline());
    print(solve(n));
}

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

let stdinInput = '';

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

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

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 1;
    let t = 1;
    outer:
    while (t <= testCases) {
        const n = data[t] * 1;
        let high = n;
        let count = Array(high + 1).fill(0);
        for (let i = 2; i <= n; i += 1) count[i]++;
        let counter = 0;
        for (let i = high; i >= 1; i -= 1) {
          let j = i;
          while(j <= high) {
            if (count[j] > 0) counter += count[j];
            j += i;
            if (counter === 2) {
              console.log(i);
              t += 1;
              continue outer;
            }
          }
          counter = 0;
        }
        console.log(1);
        console.log(count);
        t += 1;
    }
}

const testInput = [
    '2',
    '3',
    '5'
];

const {EOL} = require('os')
function getInput(test = false) {
    return new Promise((res,rej) => {
        if (test) res(testInput);
        let i = ''
        process.stdin.on('data', c => i += c)
        process.stdin.on('end', () => {
            res(i.split(EOL));//.map(line => line.split(' ')));
        })
    })
}

function output(lines) {
    process.stdout.write(lines.join(EOL));
}

getInput(true).then(lines => {
    const amount = lines.shift();
    const sortedNs = lines.map(element => parseInt(element)).sort((a,b) => a - b);
    const answer = [];
    sortedNs.forEach(num => {
        answer.push(greatestGCF(num));
    })
    output(answer);
})

const greatestGCF = (n) => {
    n-=n%2;
    return n/2;
}

const testInput = [
    '2',
    '1'
];

const {EOL} = require('os')
function getInput(test = false) {
    return new Promise((res,rej) => {
        if (test) res(testInput);
        let i = ''
        process.stdin.on('data', c => i += c)
        process.stdin.on('end', () => {
            res(i.split(EOL));//.map(line => line.split(' ')));
        })
    })
}

function output(lines) {
    console.log(lines.join(EOL));
}

getInput(false).then(lines => {
    const amount = lines.shift();
    const sortedNs = lines.map(element => parseInt(element)).sort((a,b) => a - b);
    const answer = [];
    sortedNs.forEach(num => {
        answer.push(greatestGCF(num));
    })
    output(answer);
})

const greatestGCF = (n) => {
    n-=n%2;
    return n/2;
}

const testInput = [
    '2',
    '23423',
    '12312',
    '543534',
    '24223',
    '43534543',
    '43856092',
    '6598392'
];

const {EOL} = require('os')
function getInput(test = false) {
    return new Promise((res,rej) => {
        if (test) res(testInput);
        let i = ''
        process.stdin.on('data', c => i += c)
        process.stdin.on('end', () => {
            res(i.split(EOL));
        })
    })
}

function output(lines) {
    process.stdout.write(lines.join(EOL));
}

getInput(false).then(lines => {
    const amount = lines.shift();
    const inputs = lines.map(element => parseInt(element));
    const answer = [];
    inputs.forEach(num => {
        answer.push(greatestGCF(num));
    })
    output(answer);
})

const greatestGCF = (n) => {
    n-=n%2;
    return n/2;
}

const testInput = [
    '2',
    '3',
    '5'
];

const {EOL} = require('os')
function getInput(test = false) {
    return new Promise((res,rej) => {
        if (test) res(testInput);
        let i = ''
        process.stdin.on('data', c => i += c)
        process.stdin.on('end', () => {
            res(i.split(EOL));//.map(line => line.split(' ')));
        })
    })
}

function output(lines) {
    console.log(lines.join(EOL)+EOL);
}

getInput(false).then(lines => {
    const amount = lines.shift();
    const sortedNs = lines.map(element => parseInt(element)).sort((a,b) => a - b);
    const answer = [];
    sortedNs.forEach(num => {
        answer.push(greatestGCF(num));
    })
    output(answer);
})

const greatestGCF = (n) => {
    n-=n%2;
    return n/2;
}

const testInput = [
    '2',
    '23423',
    '12312',
    '543534',
    '24223',
    '43534543',
    '43856092',
    '6598392'
];

const {EOL} = require('os')
function getInput(test = false) {
    return new Promise((res,rej) => {
        if (test) res(testInput);
        let i = ''
        process.stdin.on('data', c => i += c)
        process.stdin.on('end', () => {
            res(i.split(EOL));//.map(line => line.split(' ')));
        })
    })
}

function output(lines) {
    process.stdout.write(lines.join(EOL));
}

getInput(false).then(lines => {
    const amount = lines.shift();
    const Ns = lines.map(element => parseInt(element));
    const answer = [];
    Ns.forEach(num => {
        answer.push(greatestGCF(num));
    })
    output(answer);
})

const greatestGCF = (n) => {
    n-=n%2;
    return n/2;
}

const testInput = [
    '2',
    '3',
    '5'
];

const {EOL} = require('os')
function getInput(test = false) {
    return new Promise((res,rej) => {
        if (test) res(testInput);
        let i = ''
        process.stdin.on('data', c => i += c)
        process.stdin.on('end', () => {
            res(i.split(EOL));//.map(line => line.split(' ')));
        })
    })
}

function output(lines) {
    process.stdout.write(lines.join(EOL));
}

getInput(false).then(lines => {
    const amount = lines.shift();
    const sortedNs = lines.map(element => parseInt(element)).sort((a,b) => a - b);
    const answer = [];
    sortedNs.forEach(num => {
        answer.push(greatestGCF(num));
    })
    output(answer);
})

const greatestGCF = (n) => {
    n-=n%2;
    return n/2;
}

const testInput = [
    '2',
    '3',
    '5'
];

const {EOL} = require('os')
function getInput(test = false) {
    return new Promise((res,rej) => {
        if (test) res(testInput);
        let i = ''
        process.stdin.on('data', c => i += c)
        process.stdin.on('end', () => {
            res(i.split(EOL));//.map(line => line.split(' ')));
        })
    })
}

function output(lines) {
    console.log(lines.join(EOL));
}

getInput(false).then(lines => {
    const amount = lines.shift();
    const sortedNs = lines.map(element => parseInt(element)).sort((a,b) => a - b);
    const answer = [];
    sortedNs.forEach(num => {
        answer.push(greatestGCF(num));
        console.log(greatestGCF(num));
    })
    //console.log(answer);
})

const greatestGCF = (n) => {
    n-=n%2;
    return n/2;
}


You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.

The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.

Print the only number — distance between two nearest minimums in the array.

'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 n = parseInt(readline());
    let arr = readline().split(' ');

    let a = 10e9;
    let r = 10e9;
    let k = 10e9;

    for (let i = 0; i < arr.length; i++) {
        arr[i] = parseInt(arr[i]);

        if (arr[i] < a) {
            a = arr[k = i];
            r = 10e9;
        } else if (arr[i] === a) {
            r = Math.min(r, i - k);
            k = i;
        }
    }

    console.log(r);
}

const getMinDistanceBetweenMins = (nums) => {
  var lastIndexOfMin = 0;
  var minDistanceBetweenMins = Infinity;

  for (var i = 1; i < nums.length; i++) {
    if (nums[i] < nums[lastIndexOfMin]) {
      lastIndexOfMin = i;
      minDistanceBetweenMins = Infinity;
    } else if (nums[i] === nums[lastIndexOfMin]) {
      minDistanceBetweenMins = Math.min(
        minDistanceBetweenMins,
        i - lastIndexOfMin
      );
      lastIndexOfMin = i;
    }
  }

  return minDistanceBetweenMins;
};

const main = () => {
  readline();

  const nums = readline()
    .split(" ")
    .map((i) => Number(i));

  return getMinDistanceBetweenMins(nums);
};

print(main());

var row = readline().split(" ").map(function(x) { return parseInt(x); });
var n = row[0];

var a = [];
row = readline().split(" ").map(function(x) { return parseInt(x); });
for(var i = 0; i < n; i++) {
	a.push(row[i]);
}

var result = 0;
var min = a[0];
var resultMin = -1;
for(var i = 1; i < n; i++) {
	if(a[i] < min) {
		min = a[i];
		result = 0;
                resultMin = -1;
	} else if (a[i] > min) {
		result++;
	} else {
		if(resultMin == -1) {
			resultMin = result + 1;
		} else {
			if(resultMin > result + 1) {
				resultMin = result + 1;
			}
		}
		result = 0;
	}
}

write(resultMin);

var min
var distance = 1
var n=Number(readline())
var data = readline().split(" ")
var savedDistance = data.length
for (var i=0;i<data.length;i++) {
    var x = Number(data[i])
    if(min === undefined) {
        min = x
    } else {
        if (min > x) {
            min = x
            distance = 1
            savedDistance = n
        } else if (min === x) {
            if(savedDistance > distance){
                savedDistance = distance
            }
            distance = 1
        } else {
            distance++
        }
    }
}

print(savedDistance)

readline()
A=readline().split(' ').map(Number)
m1=Math.min.apply(null,A)
var i1=-1,i2=-1;
m2=2000000000;
for (i=0;i<A.length;++i) {
  if (A[i]===m1) {
    if (i1>=0) {
      i2=i;
      m2 = Math.min(m2, i2-i1)
      i1=i2;
    }else{
      i1=i;
    }
  }
}
print(m2)

var n = parseInt(readline());
var aa = readline().split(' ').map(parseFloat);
var m = Math.min.apply(null, aa);
var j = -n, r = n;
for (var i = 0; i < n; i++) {
    if (aa[i] === m) {
        if (r > i - j) r = i - j;
        j = i;
    }
}
print(r);

'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 n = parseInt(readline());
    let arr = readline().split(' ');

    let a = 10e9;
    let r = 10e9;
    let k = 10e9;

    for (let i = 0; i < arr.length; i++) {
        arr[i] = parseInt(arr[i]);

        if (arr[i] < a) {
            a = arr[k = i];
        } else if (arr[i] === a) {
            r = Math.min(r, i - k);
            k = i;
        }
    }

    console.log(r);
}

'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 n = parseInt(readline());
    let arr = readline().split(' ');

    let a = 10e5;
    let b = 10e5;
    let c = 0;
    let d = 10e5;
    let e = 10e5;

    for (let i = 0; i < arr.length; i++) {
        arr[i] = parseInt(arr[i]);

        if (arr[i] < a) {
            e = Math.abs((c = i) - d);
            a = arr[i];
        } else if (arr[i] < b) {
            e = Math.abs(c - (d = i));
            b = arr[i];
        } else if (arr[i] === a && Math.abs(i - d) < e) {
            e = Math.abs((c = i) - d);
            a = arr[i];
        } else if (arr[i] === b && Math.abs(c - i) < e) {
            e = Math.abs(c - (d = i));
            b = arr[i];
        }
    }

    console.log(e);
}

'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 n = parseInt(readline());
    let arr = readline().split(' ');

    let a = 10e5;
    let b = 10e5;
    let c = 0;
    let d = 0;
    let e = 10e5;

    for (let i = 0; i < arr.length; i++) {
        arr[i] = parseInt(arr[i]);

        if (arr[i] < a) {
            e = Math.abs((c = i) - d);
            a = arr[i];
        } else if (arr[i] < b) {
            e = Math.abs(c - (d = i));
            b = arr[i];
        } else if (arr[i] === a && Math.abs(i - d) < e) {
            e = Math.abs((c = i) - d);
            a = arr[i];
        } else if (arr[i] === b && Math.abs(c - i) < e) {
            e = Math.abs(c - (d = i));
            b = arr[i];
        }
    }

    console.log(e);
}

'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 n = parseInt(readline());
    let arr = readline().split(' ');

    let a = 10e5;
    let r = 10e5;
    let k = 0;

    for (let i = 0; i < arr.length; i++) {
        arr[i] = parseInt(arr[i]);

        if (arr[i] < a) {
            a = arr[i];
            k = i;
        } else if (arr[i] === a) {
            r = Math.min(r, i - k);
            k = i;
        }
    }

    console.log(r);
}

'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 n = parseInt(readline());
    let arr = readline().split(' ');

    let a = 10e9;
    let r = 10e9;
    let k = 0;

    for (let i = 0; i < arr.length; i++) {
        arr[i] = parseInt(arr[i]);

        if (arr[i] < a) {
            a = arr[k = i];
        } else if (arr[i] === a) {
            r = Math.min(r, i - k);
            k = i;
        }

        console.log(a, arr[i]);
    }

    console.log(r);
}

'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 n = parseInt(readline());
    let arr = readline().split(' ');

    let a = 10e9;
    let r = 10e9;
    let k = 0;

    for (let i = 0; i < arr.length; i++) {
        arr[i] = parseInt(arr[i]);

        if (arr[i] < a) {
            a = arr[k = i];
        } else if (arr[i] === a) {
            r = Math.min(r, i - k);
            k = i;
        }
    }

    console.log(r);
}

var row = readline().split(" ").map(function(x) { return parseInt(x); });
var n = row[0];

var a = [];
row = readline().split(" ").map(function(x) { return parseInt(x); });
for(var i = 0; i < n; i++) {
	a.push(row[i]);
}

var result = 0;
var min = a[0];
var resultMin = -1;
for(var i = 1; i < n; i++) {
	if(a[i] < min) {
		min = a[i];
		result = 0;
	} else if (a[i] > min) {
		result++;
	} else {
		if(resultMin == -1) {
			resultMin = result + 1;
		} else {
			if(resultMin > result + 1) {
				resultMin = result + 1;
			}
		}
		result = 0;
	}
}

write(resultMin);

var min
var distance = 1
n=Number(readline())
var savedDistance = n
for (var i=0;i<n;i++) {
    var x=Number(readline())
    if(min === undefined) {
        min = x
    } else {
        if (min > x) {
            min = x
            distance = 1
            savedDistance = n
        } else if (min === x) {
            if(savedDistance > distance){
                savedDistance = distance
            }
            distance = 1
        } else {
            distance++
        }
    }
}

print(savedDistance)

var min
var distance = 0
n=Number(readline())
var savedDistance = n
for (var i=0;i<n;i++) {
    var x=Number(readline())
    if(min === undefined) {
        min = x
    } else {
        if (min > x) {
            min = x
            distance = 0
            savedDistance = n
        } else if (min === x) {
            if(savedDistance > distance){
                savedDistance = distance
            }
            distance = 0
        } else {
            distance++
        }
    }
}

print(savedDistance)


The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order.We'll say that the secret is safe if the following conditions are hold:  for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets Ui and Uj is an empty set;  the union of sets U1, U2, ..., Uk is set (1, 2, ..., n);  in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| ≥ 3 should hold). Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition.

The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 106) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.

If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret. If there are multiple solutions, print any of them.

print(function(n, k) {

	if (n / k < 3) {
		return -1;
	}

	var i, ret = [];

	ret.push(k);
	for (i = 1; i < k; i++)
		ret.push(i);

	for (i = k; i < n; i++)
		ret.push(i % k + 1);

	return ret.join(' ');

}.apply(0, readline().split(' ').map(Number)));

print(function(n, k) {

	if (n / k < 3) {
		return -1;
	}

	var i, ret = [];

	ret.push(k);
	for (i = 1; i < k; i++)
		ret.push(i);

	for (i = k; i <= n; i++)
		ret.push(i % k + 1);

	return ret.join(' ');

}.apply(0, readline().split(' ').map(Number)));


Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied:  Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj ≤ bi.  Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj > ai.  The total height of all rings used should be maximum possible.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of rings in factory's stock. The i-th of the next n lines contains three integers ai, bi and hi (1 ≤ ai, bi, hi ≤ 109, bi > ai) — inner radius, outer radius and the height of the i-th ring respectively.

Print one integer — the maximum height of the tower that can be obtained.

NoteIn the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4.

n = Number(readline());
Ar = [];
Stack = [];
ans = 0;
current = 0;
for(var i = 0;i < n; i++) {
	Ar.push(readline().split(' ').map(Number));
}
Ar.sort((x,y) => {
	if(x[1] > y[1]) {
		return -1;
	}
	else if(x[1] < y[1]) {
		return 1;
	}
	else if(x[0] > y[0]) {
		return -1;
	}
	else if(x[0] < y[0]) {
		return 1;
	}
	else {
		return 0;
	}
});

for(var i = 0;i < n; i++) {
	while(Stack.length > 0 && Stack[Stack.length-1][0] >= Ar[i][1]) {
		current = current - Stack[Stack.length-1][2];
		Stack.pop();
	}
	Stack.push(Ar[i]);
	current += Ar[i][2];
	ans = max(ans,current);
}
print(ans);

function min(a,b) {
	return a > b ? b : a;
}
function max(a,b) {
	return a > b ? a : b;
}

function getLine(){
    return readline().split(' ').map((a) => parseInt(a));
}
function getInt(){
    return parseInt(readline());
}
function SegmentTree(n){
    this.n = n;
    var P = [];
    P.length = n * 4 + 1;
    var self = this;

    function Fun(x, y){
        return Math.max(x, y);
    }

    function build(v, l, r){
        if(l == r){
            P[v] = 0;
            return;
        }
        var s = (l + r) >> 1;
        build(v * 2, l, s);
        build(v * 2 + 1, s + 1, r);
        P[v] = Fun(P[v * 2], P[v * 2 + 1]);
    }
    build(1, 0, n - 1);

    var get = function(v, l, r, lq, rq){
        if(lq > rq){
            return 0;
        }
        if(lq == l && rq == r){
            return P[v];
        }
        var s = (l + r) >> 1;
        return Fun(get(v * 2, l, s, lq, Math.min(rq, s)),
                get(v * 2 + 1, s + 1, r, Math.max(lq, s + 1), rq));
    }

    this.get = function(l, r){
        return get(1, 0, self.n - 1, l, r);
    };

    var upd = function(v, l, r, x, t){
        if(l == r){
            P[v] = Fun(P[v], t);
            return;
        }
        var s = (l + r) >> 1;
        if(x <= s){
            upd(v * 2, l, s, x, t);
        }
        else{
            upd(v * 2 + 1, s + 1, r, x, t);
        }
        P[v] = Fun(P[v * 2], P[v * 2 + 1]);
    }
    this.upd = function(x, t){
        upd(1, 0, self.n - 1, x, t);
    };
}

var n = getInt();
var P = [];
for(var i = 0; i < n; i++){
    P.push(getLine());
}

P.sort(function(a, b){
    if(a[1] == b[1]){
        return a[0] - b[0];
    }
    return a[1] - b[1];
});
var W = P.map((x) => x[1]).concat(P.map((x) => x[0]));
var Z = W.sort((a, b) => a - b).filter((x, ind, self) => ind === 0 || self[ind - 1] != x);
var Go = {};
Z.forEach((x, ind) => Go[x] = ind);

var m = Z.length;
var dp = new SegmentTree(m);

for(var i = 0; i < n; i++){
    var up = Go[P[i][0]];
    var t = dp.get(up + 1, m - 1);
    var s = Go[P[i][1]];
    dp.upd(s, t + P[i][2]);
}

print(dp.get(0, m - 1));

function getLine(){
    return readline().split(' ').map(a => parseInt(a));
}
function getInt(){
    return parseInt(readline());
}
function SegmentTree(n){
    this.n = n;
    var P = [];
    P.length = n * 4 + 1;
    var self = this;

    function Fun(x, y){
        return Math.max(x, y);
    }

    function build(v, l, r){
        if(l == r){
            P[v] = 0;
            return;
        }
        var s = (l + r) >> 1;
        build(v * 2, l, s);
        build(v * 2 + 1, s + 1, r);
        P[v] = Fun(P[v * 2], P[v * 2 + 1]);
    }
    build(1, 0, n - 1);

    var get = function(v, l, r, lq, rq){
        if(lq > rq){
            return 0;
        }
        if(lq == l && rq == r){
            return P[v];
        }
        var s = (l + r) >> 1;
        return Fun(get(v * 2, l, s, lq, Math.min(rq, s)),
                get(v * 2 + 1, s + 1, r, Math.max(lq, s + 1), rq));
    }

    this.get = function(l, r){
        return get(1, 0, self.n - 1, l, r);
    };

    var upd = function(v, l, r, x, t){
        if(l == r){
            P[v] = Fun(P[v], t);
            return;
        }
        var s = (l + r) >> 1;
        if(x <= s){
            upd(v * 2, l, s, x, t);
        }
        else{
            upd(v * 2 + 1, s + 1, r, x, t);
        }
        P[v] = Fun(P[v * 2], P[v * 2 + 1]);
    }
    this.upd = function(x, t){
        upd(1, 0, self.n - 1, x, t);
    };
}

var n = getInt();
var P = [];
for(var i = 0; i < n; i++){
    P.push(getLine());
}

P.sort(function(a, b){
    if(a[1] == b[1]){
        return a[0] - b[0];
    }
    return a[1] - b[1];
});
var W = P.map(x => x[1]).concat(P.map(x => x[0]));
var Z = W.sort((a, b) => a - b).filter((x, ind, self) => ind === 0 || self[ind - 1] != x);
var Go = {};
Z.forEach((x, ind) => Go[x] = ind);

var m = Z.length;
var dp = new SegmentTree(m);

for(var i = 0; i < n; i++){
    var up = Go[P[i][0]];
    var t = dp.get(up + 1, m - 1);
    var s = Go[P[i][1]];
    dp.upd(s, t + P[i][2]);
}

print(dp.get(0, m - 1));

function min(a,b) {
	if(a<b) {
		return a;
	}
	else {
		return b;
	}
}
function max(a,b) {
	if(a>b) {
		return a;
	}
	else {
		return b;
	}
}
n = Number(readline());
Ar = [];
Stack = [];
ans = 0;
now = 0;
for(var i=0;i<n;i++) {
	Ar.push(readline().split(' ').map(Number));
}
Ar.sort((x,y) => {
	if(x[1] > y[1]) {
		return -1;
	}
	else if(x[1] < y[1]) {
		return 1;
	}
	else if(x[0] > y[0]) {
		return -1;
	}
	else if(x[0] < y[0]) {
		return 1;
	}
	else {
		return 0;
	}
});
for(var i = 0;i < n;i++) {
	while(Stack.length > 0 && Stack[Stack.length-1][0] >= Ar[i][1]) {
		now = now - Stack[Stack.length-1][2];
		Stack.pop();
	}
	Stack.push(Ar[i]);
	now = now + Ar[i][2];
	ans = max(ans,now);
}
print(ans);

function getLine(){
    return readline().split(' ').map((a) => parseInt(a));
}
function getInt(){
    return parseInt(readline());
}
function SegmentTree(n){
    this.n = n;
    var P = [];
    P.length = n * 4 + 1;
    var self = this;

    function Fun(x, y){
        return Math.max(x, y);
    }

    function build(v, l, r){
        if(l == r){
            P[v] = 0;
            return;
        }
        var s = (l + r) >> 1;
        build(v * 2, l, s);
        build(v * 2 + 1, s + 1, r);
        P[v] = Fun(P[v * 2], P[v * 2 + 1]);
    }
    build(1, 0, n - 1);

    var get = function(v, l, r, lq, rq){
        if(lq > rq){
            return 0;
        }
        if(lq == l && rq == r){
            return P[v];
        }
        var s = (l + r) >> 1;
        return Fun(get(v * 2, l, s, lq, Math.min(rq, s)),
                get(v * 2 + 1, s + 1, r, Math.max(lq, s + 1), rq));
    }

    this.get = function(l, r){
        return get(1, 0, self.n - 1, l, r);
    };

    var upd = function(v, l, r, x, t){
        if(l == r){
            P[v] = Fun(P[v], t);
            return;
        }
        var s = (l + r) >> 1;
        if(x <= s){
            upd(v * 2, l, s, x, t);
        }
        else{
            upd(v * 2 + 1, s + 1, r, x, t);
        }
        P[v] = Fun(P[v * 2], P[v * 2 + 1]);
    }
    this.upd = function(x, t){
        upd(1, 0, self.n - 1, x, t);
    };
}

var n = getInt();
var P = [];
for(var i = 0; i < n; i++){
    P.push(getLine());
}

P.sort(function(a, b){
    if(a[1] == b[1]){
        return a[0] - b[0];
    }
    return a[1] - b[1];
});
var W = P.map((x) => x[1]).concat(P.map((x) => x[0]));
var Z = W.sort((a, b) => a - b).filter((x, ind, self) => ind === 0 || self[ind - 1] != x);
var Go = {};
Z.forEach((x, ind) => Go[x] = ind);

var m = Z.length;
var dp = new SegmentTree(m);

for(var i = 0; i < n; i++){
    var up = Go[P[i][0]];
    var t = dp.get(up + 1, m - 1);
    var s = Go[P[i][1]];
    dp.upd(s, t + P[i][2]);
    print(s, t + P[i][2]);
}

print(dp.get(0, m - 1));

function getLine(){
    return readline().split(' ').map((a) => parseInt(a));
}
function getInt(){
    return parseInt(readline());
}
function SegmentTree(n){
    this.n = n;
    var P = [];
    P.length = n * 4 + 1;
    var self = this;

    function Fun(x, y){
        return Math.max(x, y);
    }

    function build(v, l, r){
        if(l == r){
            P[v] = 0;
            return;
        }
        var s = (l + r) >> 1;
        build(v * 2, l, s);
        build(v * 2 + 1, s + 1, r);
        P[v] = Fun(P[v * 2], P[v * 2 + 1]);
    }
    build(1, 0, n - 1);

    var get = function(v, l, r, lq, rq){
        if(lq > rq){
            return 0;
        }
        if(lq == l && rq == r){
            return P[v];
        }
        var s = (l + r) >> 1;
        return Fun(get(v * 2, l, s, lq, Math.min(rq, s)),
                get(v * 2 + 1, s + 1, r, Math.max(lq, s + 1), rq));
    }

    this.get = function(l, r){
        return get(1, 0, self.n - 1, l, r);
    };

    var upd = function(v, l, r, x, t){
        if(l == r){
            P[v] = Fun(P[v], t);
            return;
        }
        var s = (l + r) >> 1;
        if(x <= s){
            upd(v * 2, l, s, x, t);
        }
        else{
            upd(v * 2 + 1, s + 1, r, x, t);
        }
        P[v] = Fun(P[v * 2], P[v * 2 + 1]);
    }
    this.upd = function(x, t){
        upd(1, 0, self.n - 1, x, t);
    };
}

var n = getInt();
var P = [];
for(var i = 0; i < n; i++){
    P.push(getLine());
}

P.sort((a, b) => a[1] - b[1]);
var W = P.map((x) => x[1]).concat(P.map((x) => x[0]));
var Z = W.sort().filter((x, ind, self) => ind === 0 || self[ind - 1] != x);
var Go = {};
Z.forEach((x, ind) => Go[x] = ind);

var m = Z.length;
var dp = new SegmentTree(m);

for(var i = 0; i < n; i++){
    var up = Go[P[i][0]];
    var t = dp.get(up + 1, m - 1);
    var s = Go[P[i][1]];
    dp.upd(s, t + P[i][2]);
}

print(dp.get(0, m - 1));

function min(a,b) {
	if(a<b) {
		return a;
	}
	else {
		return b;
	}
}
function max(a,b) {
	if(a>b) {
		return a;
	}
	else {
		return b;
	}
}
n = Number(readline());
Ar = [];
Stack = [];
ans = 0;
now = 0;
for(var i=0;i<n;i++) {
	Ar.push(readline().split(' ').map(Number));
}
Ar.sort((x,y) => {
	if(x[1] > y[1]) {
		return -1;
	}
	else if(x[1] < y[1]) {
		return 1;
	}
	else if(x[0] > y[0]) {
		return 1;
	}
	else if(x[0] < y[0]) {
		return -1;
	}
	else {
		return 0;
	}
});
for(var i = 0;i < n;i++) {
	while(Stack.length > 0 && Stack[Stack.length-1][0] >= Ar[i][1]) {
		now = now - Stack[Stack.length-1][2];
		Stack.pop();
	}
	Stack.push(Ar[i]);
	now = now + Ar[i][2];
	ans = max(ans,now);
}
print(ans);


Nauuo is a girl who loves playing chess.One day she invented a game by herself which needs $$$n$$$ chess pieces to play on a $$$m\times m$$$ chessboard. The rows and columns are numbered from $$$1$$$ to $$$m$$$. We denote a cell on the intersection of the $$$r$$$-th row and $$$c$$$-th column as $$$(r,c)$$$.The game's goal is to place $$$n$$$ chess pieces numbered from $$$1$$$ to $$$n$$$ on the chessboard, the $$$i$$$-th piece lies on $$$(r_i,\,c_i)$$$, while the following rule is satisfied: for all pairs of pieces $$$i$$$ and $$$j$$$, $$$|r_i-r_j|+|c_i-c_j|\ge|i-j|$$$. Here $$$|x|$$$ means the absolute value of $$$x$$$.However, Nauuo discovered that sometimes she couldn't find a solution because the chessboard was too small.She wants to find the smallest chessboard on which she can put $$$n$$$ pieces according to the rules.She also wonders how to place the pieces on such a chessboard. Can you help her?

The only line contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$) — the number of chess pieces for the game.

The first line contains a single integer — the minimum value of $$$m$$$, where $$$m$$$ is the length of sides of the suitable chessboard. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$r_i$$$ and $$$c_i$$$ ($$$1\le r_i,c_i\le m$$$) — the coordinates of the $$$i$$$-th chess piece. If there are multiple answers, print any.

NoteIn the first example, you can't place the two pieces on a $$$1\times1$$$ chessboard without breaking the rule. But you can place two pieces on a $$$2\times2$$$ chessboard like this:In the second example, you can't place four pieces on a $$$2\times2$$$ chessboard without breaking the rule. For example, if you place the pieces like this:then $$$|r_1-r_3|+|c_1-c_3|=|1-2|+|1-1|=1$$$, $$$|1-3|=2$$$, $$$1<2$$$; and $$$|r_1-r_4|+|c_1-c_4|=|1-2|+|1-2|=2$$$, $$$|1-4|=3$$$, $$$2<3$$$. It doesn't satisfy the rule.However, on a $$$3\times3$$$ chessboard, you can place four pieces like this:

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    };

    var n = read.number();
    var m = Math.ceil((n - 1) / 2) + 1;

    var res = m + '\n';

    var count = 0;
    for(var i = 0; i < m && count < n; i++) {
        res+= '1 ' + (i + 1) + '\n';
        count++;
    }
    for(var i = 1; i < m && count < n; i++) {
        res+= (i + 1) + ' ' + m + '\n';
         count++;
    }
    print(res);
}());

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    };

    var n = read.number();
    var m = Math.ceil((n - 1) / 2) + 1;

    var res = m + '\n';

    for(var i = 0; i < m; i++) {
        res+= '1 ' + (i + 1) + '\n';
    }
    for(var i = i; i < m; i++) {
        res+= (i + 1) + ' ' + m + '\n';
    }
    print(res);
}());


Vasya has found a piece of paper with a coordinate system written on it. There are n distinct squares drawn in this coordinate system. Let's number the squares with integers from 1 to n. It turned out that points with coordinates (0, 0) and (ai, ai) are the opposite corners of the i-th square.Vasya wants to find such integer point (with integer coordinates) of the plane, that belongs to exactly k drawn squares. We'll say that a point belongs to a square, if the point is located either inside the square, or on its boundary. Help Vasya find a point that would meet the described limits.

The first line contains two space-separated integers n, k (1 ≤ n, k ≤ 50). The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109). It is guaranteed that all given squares are distinct.

In a single line print two space-separated integers x and y (0 ≤ x, y ≤ 109) — the coordinates of the point that belongs to exactly k squares. If there are multiple answers, you are allowed to print any of them.  If there is no answer, print "-1" (without the quotes).

print(function(n,k){
	var a = readline().split(' ').map(Number).sort(function(a,b){return b-a;});
	return a[k-1] ? a[k-1]+' 0' : -1;
}.apply(0, readline().split(' ').map(Number)))

var inp = readline().split(' ');
var n = Number(inp[0]);
var k = Number(inp[1]);
var A = readline().split(' ').map((x)=>Number(x));
A.sort((x,y) => x-y);

if(n-k < 0 || A[n-k]==A[n-k-1])print(-1);
else print(A[n-k] + " " + A[n-k]);

;(function () {

	var n = readline().split(' ');
	var k = +n[1];
	n = +n[0];

	if (k > n) {
		print(-1);
		return;
	}

	var s = readline().split(' ').map(Number)
		.filter(function (e, i, a) { return i == a.lastIndexOf(e); })
		.sort(function (a, b) { return a - b; });

	print( s[s.length - k] + ' 0' );

}).call(this);


Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.

The first line contains number n — the number of techniques that the wrestlers have used (1 ≤ n ≤ 2·105).  The following n lines contain integer numbers ai (|ai| ≤ 109, ai ≠ 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points. The techniques are given in chronological order.

If the first wrestler wins, print string "first", otherwise print "second"

NoteSequence x  =  x1x2... x|x| is lexicographically larger than sequence y  =  y1y2... y|y|, if either |x|  >  |y| and x1  =  y1,  x2  =  y2, ... ,  x|y|  =  y|y|, or there is such number r (r  <  |x|, r  <  |y|), that x1  =  y1,  x2  =  y2,  ... ,  xr  =  yr and xr  +  1  >  yr  +  1.We use notation |a| to denote length of sequence a.

function main() {
    var n = nextInt();

    var p1 = [], p2 = [];
    var res = '';
    var s1 = 0, s2 = 0;
    var i;

    for (i = 0; i < n; i++) {
        var a = nextInt();
        if (a > 0) {
            p1.push(a);
            s1 += a;
        } else {
            p2.push(-a);
            s2 += -a;
        }
        if (i === n - 1) {
            res = a > 0 ? 'first' : 'second';
        }
    }

    if (s1 != s2) {
        res = s1 > s2 ? 'first' : 'second';
    } else {
        var found = false;
        for (i = 0; i < Math.min(p1.length, p2.length); i++) {
            if (p1[i] != p2[i]) {
                res = p1[i] > p2[i] ? 'first' : 'second';
                found = true;
                break;
            }
        }
        if (!found && p1.length !== p2.length) {
            res = p1.length > p2.length ? 'first' : 'second';
        }
    }

    print(res);
}

// auxiliary code
var curTokens = [], curToken = 0;

function next() {
    while (curToken >= curTokens.length) {
        curTokens = readline().split(' ');
        curToken = 0;
    }
    return curTokens[curToken++];
}

function nextInt() {
    return parseInt(next());
}

main();

var n = parseInt(readline()),
    first = [], second = [], total = [],
    firstSum = 0, secondSum = 0,
    result = '';

for(var i = 0; i < n; i++)    {
    var value = parseInt(readline());

    if(value > 0)    {
        first.push(Math.abs(value));
        firstSum += value;
    } else    {
        second.push(Math.abs(value));
        secondSum += value;
    }

    total.push(value);
}

firstSum = Math.abs(firstSum);
secondSum = Math.abs(secondSum);

if(firstSum > secondSum)    result = 'first';
else if(firstSum < secondSum)    result = 'second';
else    {
    if(second.length > first.length)    {
        first.some(function(fv, idx)    {
            var sv = second[idx];

            if(fv > sv)    {
                result = 'first';
                return true;
            } else if(fv < sv)    {
                result = 'second';
                return true;
            }
        });
    } else if(second.length <= first.length)    {
        second.some(function(sv, idx)    {
            var fv = first[idx];

            if(fv > sv)    {
                result = 'first';
                return true;
            } else if(fv < sv)    {
                result = 'second';
                return true;
            }
        });
    }

    if(result == '')    total[total.length - 1] < 0 ? result = 'second' : result = 'first';
}

print(result);

function main() {
    var n = nextInt();

    var a = [], p1 = [], p2 = [];
    var res = '';
    var s1 = 0, s2 = 0;
    var i;

    for (i = 0; i < n; i++) {
        a[i] = nextInt();
        if (a[i] > 0) {
            p1.push(a[i]);
            s1 += a[i];
        } else {
            p2.push(-a[i]);
            s2 += -a[i];
        }
        if (i == a.length - 1) {
            res = a[i] > 0 ? 'first' : 'second';
        }
    }

    if (s1 != s2) {
        res = s1 > s2 ? 'first' : 'second';
    } else {
        res = null;
        for (i = 0; i < Math.min(p1.length, p2.length); i++) {
            if (p1[i] != p2[i]) {
                res = p1[i] > p2[i] ? 'first' : 'second';
                break;
            }
        }
        if (res === null) {
            res = p1.length > p2.length ? 'first' : 'second';
        }
    }

    print(res);
}

// auxiliary code
var curTokens = [], curToken = 0;

function next() {
    while (curToken >= curTokens.length) {
        curTokens = readline().split(' ');
        curToken = 0;
    }
    return curTokens[curToken++];
}

function nextInt() {
    return parseInt(next());
}

main();

var n = parseInt(readline()),
			fa, sa;

		for(var i = 0; i < n; i++)	{
			var value = parseInt(readline());

			value < 0 ? sa = value : fa = value;
		}

		fa = Math.abs(fa);
		sa = Math.abs(sa);

		if(Math.abs(fa) > Math.abs(sa))	print('first');
		if(Math.abs(fa) < Math.abs(sa))	print('second');
		if(Math.abs(fa) == Math.abs(sa))	{
			fa < 0 ? print('first') : print('second');
		}

var n = parseInt(readline()),
			fa = [], sa = [];

		for(var i = 0; i < n; i++)	{
			var value = parseInt(readline());

			value < 0 ? sa.push(value) : fa.push(value);
		}

		var faLast = fa[fa.length - 1],
			saLast = sa[sa.length - 1];

		if(Math.abs(faLast) > Math.abs(saLast))	print('first');
		else if(Math.abs(faLast) < Math.abs(saLast))	print('second');
		else if(Math.abs(faLast) == Math.abs(saLast))	{
			var result = loopFunc(2);
		}

		function loopFunc(v)	{
			var faNum = Math.abs(fa[fa.length - v]),
				saNum = Math.abs(sa[sa.length - v]);

			!faNum ? faNum = -1 : false;
			!saNum ? saNum = 0 : false;

			if(faNum > saNum)	{
				print('first');
				return;
			} else if(faNum < saNum)	{
				print('second');
				return;
			} else if(faNum == saNum)	{
				loopFunc(v + 1);
			}
		};


You are given two integers $$$x$$$ and $$$y$$$ (it is guaranteed that $$$x > y$$$). You may choose any prime integer $$$p$$$ and subtract it any number of times from $$$x$$$. Is it possible to make $$$x$$$ equal to $$$y$$$?Recall that a prime number is a positive integer that has exactly two positive divisors: $$$1$$$ and this integer itself. The sequence of prime numbers starts with $$$2$$$, $$$3$$$, $$$5$$$, $$$7$$$, $$$11$$$.Your program should solve $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ lines follow, each describing a test case. Each line contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le y < x \le 10^{18}$$$).

For each test case, print YES if it is possible to choose a prime number $$$p$$$ and subtract it any number of times from $$$x$$$ so that $$$x$$$ becomes equal to $$$y$$$. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).

NoteIn the first test of the example you may choose $$$p = 2$$$ and subtract it once.In the second test of the example you may choose $$$p = 5$$$ and subtract it twice. Note that you cannot choose $$$p = 7$$$, subtract it, then choose $$$p = 3$$$ and subtract it again.In the third test of the example you may choose $$$p = 3$$$ and subtract it $$$333333333333333333$$$ times.

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

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

  const [x, y] = d.split(' ').map(BigInt);

  if (y + 1n === x) {
    console.log('NO');
  }
  else {
    console.log('YES');
  }

  c++;
});

function solve() {
    var T = Number(read());
    for (var t = 0; t < T; ++t) {
       var xy = read().split(' ');
       var x = xy[0];
       var y = xy[1];
       var xl = x.length;
       var yl = y.length;
       if (xl - yl > 2) {
          write('yes');
          continue;
       }
       if (xl < 10) {
          write(Number(x) - Number(y) > 1 ? 'yes' : 'no');
          continue;
       }
       var bx = Number(x.substr(0, xl - 9));
       var lx = Number(x.substr(xl - 9));
       var by = Number(y.substr(0, yl - 9));
       var ly = Number(y.substr(yl - 9));
       var d = (bx - by) * 1000000000;
       write(d + lx - ly > 1 ? 'yes' : 'no')
    }
}

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;
   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');
         solve();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', solve);
   }
} else {
   solve();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

'use strict'

const q = parseInt(readline());

const fn = (x, y) => {
    y = ('0' + y).slice(-x.length);
    if ((x.length > y.length)) return 'YES'
    let i = 0;
    while (x[i] === y[i]) i++;
    if (x[i] - y[i] > 1) return 'YES';
    const j = x.length - i - 1;
    if (j === 0) return 'NO';
    if (x.slice(-j) === '0'.repeat(j) && y.slice(-j) === '9'.repeat(j)) return 'NO';
    return 'YES';
}

for(let i = 0; i < q; i++) {
    const xy = readline().split(' ');
    print(fn(xy[0],xy[1]));
}

function solve() {
    var T = Number(read());
    for (var t = 0; t < T; ++t) {
       var xy = read().split(' ').map(Number);
       write(xy[0] - xy[1] > 1 ? 'YES' : 'NO');
    }
}

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;
   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');
         solve();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', solve);
   }
} else {
   solve();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

'use strict'

const q = parseInt(readline());

const fn = (x, y) => {
    y = ('0' + y).slice(-x.length);
    if ((x.length > y.length)) return 'YES'
    let i = 0;
    while (x[i] === y[i]) i++;
    if (x[i] - y[i] > 1) return 'YES';
    i++;
    const j = x.length - i;
    if (x.slice(-i) === '0'.repeat(j) && y.slice(-i) === '9'.repeat(j)) return 'NO';
    return 'YES';
}
for(let i = 0; i < q; i++) {
    const xy = readline().split(' ');
    print(fn(xy[0],xy[1]));
}

'use strict'

const eratosthenes = n => {
    const array = Array(n).fill(true);
    const upperLimit = Math.sqrt(n);
    const output = [];

    for (var i = 2; i <= upperLimit; i++) {
        if (array[i]) {
            for (var j = i * i; j < n; j += i) {
                array[j] = false;
            }
        }
    }
    for (var i = 2; i < n; i++) {
        if(array[i]) output.push(i);
    }

    return output;
};

const q = parseInt(readline());
const isPrime = num => {
    for(let i = 2, s = Math.sqrt(num); i <= s; i++)
        if(num % i === 0) return false;
    return num > 1;
}

const primes = eratosthenes(1000000);
const fn = d => {
    if (d < 2) return 'NO';
    if (isPrime(d)) return 'YES';
    const last = primes.findIndex(i => i > Math.sqrt(d));
    if (last === -1) return 'YS'
    for (let i = 0; i < last; i++) {
        if (d%primes[i] === 0) return 'YES';
    }
    return 'NO';
}
for(let i = 0; i < q; i++) {
    const xy = readline().split(' ').map(Number);
    print(fn(xy[0] - xy[1]));
}

'use strict'

const eratosthenes = n => {
    const array = Array(n).fill(true);
    const upperLimit = Math.sqrt(n);
    const output = [];

    for (var i = 2; i <= upperLimit; i++) {
        if (array[i]) {
            for (var j = i * i; j < n; j += i) {
                array[j] = false;
            }
        }
    }
    for (var i = 2; i < n; i++) {
        if(array[i]) output.push(i);
    }

    return output;
};

const q = parseInt(readline());
const isPrime = num => {
    for(let i = 2, s = Math.sqrt(num); i <= s; i++)
        if(num % i === 0) return false;
    return num > 1;
}

const primes = eratosthenes(1000000);
const fn = d => {
    if (d < 2) return 'NO';
    if (isPrime(d)) return 'YES';
    const last = primes.findIndex(i => i > Math.sqrt(d));
    if (last === -1) return 'YES'
    for (let i = 0; i < last; i++) {
        if (d%primes[i] === 0) return 'YES';
    }
    return 'NO';
}
for(let i = 0; i < q; i++) {
    const xy = readline().split(' ').map(Number);
    print(fn(xy[0] - xy[1]));
}

'use strict'

const q = parseInt(readline());

for(let i = 0; i < q; i++) {
    const xy = readline().split(' ');
    const x = xy[0];
    const y = xy[1];
    if ((x.length > y.length)) print('YES');
    else if (x.slice(0, -2) !== y.slice(0, -2)) print('YES');
    else print((x.slice(-2) - y.slice(-2) > 1) ? 'YES' : 'NO');
}

'use strict'

const q = parseInt(readline());

for(let i = 0; i < q; i++) {
    const xy = readline().split(' ');
    const x = xy[0];
    const y = xy[1];
    if ((x.length > y.length)) print('YES');
    else if (x.slice(0, -1) !== y.slice(0, -1)) print('YES');
    else print((x.slice(-1) - y.slice(-1) > 1) ? 'YES' : 'NO');
}

'use strict'

const q = parseInt(readline());

for(let i = 0; i < q; i++) {
    const xy = readline().split(' ');
    const x = xy[0];
    const y = xy[1];
    if (x.length > y.length || x.split('').slice(0, -1).join('') !== y.split('').slice(0, -1).join('') ) print('YES');
    else print(parseInt(x[x.length - 1]) - parseInt(y[y.length - 1]) > 1 ? 'YES' : 'NO');
}

'use strict'

const q = parseInt(readline());

for(let i = 0; i < q; i++) {
    const xy = readline().split(' ').map(Number);
    print(xy[0] - xy[1] > 1 ? 'YES' : 'NO');
}

function solve() {
    var T = Number(read());
    for (var t = 0; t < T; ++t) {
       var xy = read().split(' ');
       write(xy[0].length - xy[1].length > 1 || Number(xy[0]) - Number(xy[1]) > 1 ? 'YES' : 'NO');
    }
}

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;
   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');
         solve();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', solve);
   }
} else {
   solve();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

function solve() {
    var T = Number(read());
    for (var t = 0; t < T; ++t) {
       var xy = read().split(' ');
       var x = xy[0];
       var y = xy[1];
       var xl = x.length;
       var yl = y.length;
       if (xl - yl > 2) {
          write('yes');
          continue;
       }
       if (xl < 10) {
          write(Number(x) - Number(y) > 1 ? 'yes' : 'no');
          continue;
       }
       var bx = x.substr(0, xl - 9);
       var lx = x.substr(xl - 9);
       var by = y.substr(0, yl - 9);
       var ly = y.substr(yl - 9);
       write(bx > by ? 'yes' : lx - ly > 1 ? 'yes' : 'no')
    }
}

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;
   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');
         solve();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', solve);
   }
} else {
   solve();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}