New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is wi.As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.  He lifts all the books above book x.  He pushes book x out of the stack.  He puts down the lifted books without changing their order.  After reading book x, he puts book x on the top of the stack.  He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer bj (1 ≤ bj ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?

The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books. The second line contains n space-separated integers w1, w2, ..., wn (1 ≤ wi ≤ 100) — the weight of each book. The third line contains m space separated integers b1, b2, ..., bm (1 ≤ bj ≤ n) — the order of books that he would read. Note that he can read the same book more than once.

Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.

NoteHere's a picture depicting the example. Each vertical column presents the stacked books.

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 printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], m = data[1],
    weights = tokenizeIntegers(readline()),
    read = tokenizeIntegers(readline()),
    before = [], seen = new Array(n);
  for (var i = 0; i < n; ++i) {
    before[i] = 0;
    seen[i] = false;
  }
  var total = 0;
  for (var i = 0; i < m; ++i) {
    read[i] -= 1;
    var book = read[i];
    //print('read '+(book+1));
    for (var j = before[book]; j < i; ++j) {
      //print('  lift '+(read[j]+1));
      var k = read[j];
      if (!seen[k]) {
        total += weights[k];
        seen[k] = true;
      }
    }
    for (var j = before[book]; j < i; ++j) {
      seen[read[j]] = false;
    }
    before[book] = i+1;
  }
  print(total);
}

main();

var nm = readline().split(' ');
var n = +nm[0];
var m = +nm[1];
var w = readline().split(' ').map(function(x){return +x;});
var b = readline().split(' ').map(function(x){return +x-1;});
var k = [];
var f = {};
var res = 0;
for (var i = 0; i < m; i++) {
    if (!(b[i] in f)) {
        for (var j = 0; j < k.length; j++) {
            res += w[k[j]];
        }
        k.push(b[i]);
        f[b[i]] = undefined;
    } else {
        var t = b[i];
        for (var j = k.length - 1; k[j] != b[i]; j--) {
            var u = t;
            t = k[j];
            k[j] = u;
            res += w[t];
        }
        k[j] = t;
    }
}
print(res);


You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.Let instability of the array be the following value: $$$\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$$$.You have to remove exactly one element from this array to minimize instability of the resulting $$$(n-1)$$$-elements array. Your task is to calculate the minimum possible instability.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — elements of the array $$$a$$$.

Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $$$a$$$.

NoteIn the first example you can remove $$$7$$$ then instability of the remaining array will be $$$3 - 1 = 2$$$.In the second example you can remove either $$$1$$$ or $$$100000$$$ then instability of the remaining array will be $$$100000 - 100000 = 0$$$ and $$$1 - 1 = 0$$$ correspondingly.

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

  let tmp=0, lngth=0, str='';

  rl.on('line', (input) => {
      if (tmp==0) {lngth=Number(input); tmp++;}
      else {str=input; rl.close(); therest();
    return 0;}

  });

let therest=function() {
    let mass=str.split(' ').map(n=>{return Number(n);});
    if (lngth==2) {console.log(0); return 0;}
    let max=Math.max(...mass);
    let maxind=mass.indexOf(max);
    mass.splice(maxind,1);
    let min=Math.min(...mass);
    let minind=mass.indexOf(min);
    mass.splice(minind, 1);
    let secondmax=Math.max(...mass);
    let secondmin=Math.min(...mass);
 //   console.log(max, maxind, min, minind);
  /*  let a=mass[0];
    let max=a, secondmax=a, min=a, secondmin=a;
    for(let i=0; i<mass.length; i++) {
        if(max<mass[i]) {
            secondmax=max;
            max=mass[i];}
        else if(secondmax<mass[i]) secondmax=mass[i];
        if(min>mass[i]) {
            secondmin=mass[i];
            min=mass[i];
        }
        else if(secondmin>mass[i]) secondmin=mass[i];
    }*/
 //   console.log(max, secondmax, min, secondmin, Math.min(secondmax-min, max-secondmin));

    console.log(Math.min(secondmax-min, max-secondmin));
/*    let res='', step=1;
    for (let i=0; i<lngth; i++) {
        res+=str[i];
        i+=step;
        step++;
    }
console.log(res);
*/
}
//console.log(lngth, str);}

  /*
  rl.question('What do you think of Node.js? ', (answer) => {
    // TODO: Log the answer in a database
    console.log(`Thank you for your valuable feedback: ${answer}`);

    rl.close();
  });*/

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

let l = 0;
rl.on('line', (input) => {
    if (l === 0) { l++ }
    else {
        rl.close();
        input = input.split(" ")
        let min1 = 100001
        let min2 = 100001
        let max1 = 0
        let max2 = 0
        for (let i = 0; i < input.length; i++) {
            let l = parseInt(input[i])
            if (l < min1) {
                min2 = min1
                min1 = l;
            } else if (l < min2) {
                min2 = l
            }

            if (l > max1) {
                max2 = max1
                max1 = l;
            } else if (l > max2) {
                max2 = l
            }
        }
        let sol = []
        sol[0] = max1 - min2
        sol[1] = max2 - min1
        if (sol[0] < sol[1]) {
            console.log(sol[0])
            return 0
        }
        console.log(sol[1])
        return 0;
    }
});

function task([number, array]) {
  if (array.length === 2) return 0;

  array = array.split(' ').map(i => Number(i)).sort((a, b) => a - b);

  let instability = (i, j) => array[j] - array[i];

  return Math.min(instability(0, array.length - 2), instability(1, array.length - 1))
}

function test() {
  const assert = (result, expectation) => {
    if (result !== expectation) throw new Error(`${result}: ${expectation}`);
  };

  assert(task(['4', '1 3 3 7']), 2);
  assert(task(['2', '1 10000']), 0);
}

function run() {
  // codeforces uses windows. Really??!
  if (process.platform === 'win32') {
    const readline = require('readline');
    const rl = readline.createInterface({ input: process.stdin });

    const input = [];

    rl.on('line', (line) => input.push(line));
    rl.on('close', () => console.log(task(input)))
  } else {
    test();
  }
}

run();

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 arr = d.split(' ').map(Number);
  arr.sort((a, b) => a - b);
  const ans1 = arr[arr.length - 1] - arr[1];
  const ans2 = arr[arr.length - 2] - arr[0];
  const ans = Math.min(ans1, ans2);

  console.log(ans);

  c++;
});

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

  let l=0;
  rl.on('line', (input) => {
      if (l==0) {l++}
      else {
           rl.close();
           input = input.split(" ")
           let min1=100001
           let min2=100001
           let max1=0
           let max2=0
           for(let i=0;i<input.length;i++){
            let l = parseInt(input[i])
            if(l<min1){
                min2=min1
                min1=l;
            } else if(l<min2){
                min2=l
            }

            if(l>max1){
                max2=max1
                max1=l;
               } else if(l>max2){
                max2=l
            }
        }
        let sol = []
        sol[0]=max1-min2
        sol[1]=max2-min1
        if(sol[0]<sol[1]){
            console.log(sol[0])
            return 0
        }
        console.log(sol[1])
    return 0;
}
});

const readline = require('readline')

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

rl.on("line", main)
let i = 0;
let n = 0;
let arr = []

function main(input){

	if(i == 0){
		n = input
		i++
		return
	}
	if(i == 1){
		arr = input.split(' ')

	}
	let max, min

	arr.sort(function(a, b){
		return parseInt(a) - parseInt(b)
	})

	console.log( Math.min(arr[n - 2] - arr[0], arr[n - 1] - arr[1]))

}

//var input = readline()
var tt = readline()
var t = parseInt(tt)

var n = readline().split(' ')
n.sort((a, b) => (a - b))

var mx = -9999, mn = 9999999999
for(var i=0; i<t; i++) {
     //mx = Math.max(mx, n[i])
     mn = Math.min(n[t-2] - n[0] , n[t-1] - n[1])
}
//var x = mx-mn
print(mn)

//var input = readline()
var t = parseInt(readline());

var ar = readline().split(' ').map(x => parseInt(x));
var n = ar.sort((a, b) => (a - b));

var mx = -Infinity, mn = Infinity
for(var i=0; i<t; i++) {
     //mx = Math.max(mx, n[i])
     mn = Math.min(n[t-2] - n[0], n[t-1] - n[1]);
}
print(mn)

//

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

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

  let v = 0;
  let inc = 1;
  let ans = '';

  while (v < str.length) {
    ans += str[v];
    v += inc;
    inc++;
  }

  console.log(ans);

  c++;
});

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

  let l=0;
  rl.on('line', (input) => {
      if (l==0) {l++}
      else {
           rl.close();
           let min1=input.charAt(0)
           let min2=input.charAt(1)
           let max1=input.charAt(0)
           let max2=input.charAt(1)
           for(let i=0;i<input.length;i+=2){
            let l = parseInt(input.charAt(i))
            if(l<min1){
                min2=min1
                min1=l;
            } else if(l<min2){
                min2=l
            }

            if(l>max1){
                max2=max1
                max1=l;
               } else if(l>max2){
                max2=l
            }
        }
        let sol = []
        sol[0]=max1-min2
        sol[1]=max2-min1
        if(sol[0]<sol[1]) {
            console.log(sol[0])
            return 0;
        }
        console.log(sol[1])
    return 0;
}
});

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

  let l=0;
  rl.on('line', (input) => {
      if (l==0) {l++}
      else {
           rl.close();
           let min1=input.charAt(0)
           let min2=input.charAt(0)
           let max1=input.charAt(0)
           let max2=input.charAt(0)
           input = input.split(" ")
           for(let i=0;i<input.length;i++){
            let l = parseInt(input[i])
            if(l<min1){
                min2=min1
                min1=l;
            } else if(l<min2){
                min2=l
            }

            if(l>max1){
                max2=max1
                max1=l;
               } else if(l>max2){
                max2=l
            }
        }
        let sol = []
        sol[0]=max1-min2
        sol[1]=max2-min1
        if(sol[0]<sol[1]) {
            console.log(sol[0])
            return 0;
        }
        console.log(sol[1])
    return 0;
}
});

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

  let l=0;
  rl.on('line', (input) => {
      if (l==0) {l++}
      else {
           rl.close();
           input = input.split(" ")
           let min1=100001
           let min2=100001
           let max1=0
           let max2=0
           for(let i=0;i<input.length;i++){
            let l = parseInt(input[i])
            if(l<min1){
                min2=min1
                min1=l;
            } else if(l<min2){
                min2=l
            }

            if(l>max1){
                max2=max1
                max1=l;
               } else if(l>max2){
                max2=l
            }
        }
        let sol = []
        sol[0]=max1-min2
        sol[1]=max2-min1
        if(sol[0]<sol[1]){
            console.log(sol[0])
            return 0
        }
        console.log(sol[0])
    return 0;
}
});

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

  let l=0;
  rl.on('line', (input) => {
      if (l==0) {l++}
      else {
           rl.close();
           input = input.split(" ")
           let min1=input[0]
           let min2=input[0]
           let max1=input[0]
           let max2=input[0]
           for(let i=0;i<input.length;i++){
            let l = parseInt(input[i])
            if(l<min1){
                min2=min1
                min1=l;
            } else if(l<min2){
                min2=l
            }

            if(l>max1){
                max2=max1
                max1=l;
               } else if(l>max2){
                max2=l
            }
        }
        let sol = []
        sol[0]=max1-min2
        sol[1]=max2-min1
        if(sol[0]<sol[1]) {
            console.log(sol[0])
            return 0;
        }
        console.log(sol[1])
    return 0;
}
});

const readline = require('readline')

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

rl.on("line", main)
let i = 0;
let n = 0;
let arr = []
function main(input){

	if(i == 0){
		n = input
		i++
		return
	}
	if(i == 1){
		arr = input.split(' ')

	}

	let max, min

	for(var k = 0; k < arr.length; k++){
		if(k == 0){
			max = parseInt(arr[k])
			min = parseInt(arr[k])
			if(max < min){
				max = arr[k+1]
			}

		}

		var e = parseInt(arr[k])

		if(e > max){
			max = e
		}

		if(e < min){
			min = e
		}

	}
	arr.splice(arr.indexOf(max.toString()),1)

	min, max
	        for(var k = 0; k < arr.length; k++){
		if(k == 0){
						max = parseInt(arr[k])
						min = parseInt(arr[k])
						if(max < min){
											max = arr[k+1]
										}

					}

		var e = parseInt(arr[k])

		if(e > max){
						max = e
					}

		if(e < min){
						min = e
					}

	}

	console.log(max - min)
}

const readline = require('readline')

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

rl.on("line", main)
let i = 0;
let n = 0;
let arr = []

function main(input){

	if(i == 0){
		n = input
		i++
		return
	}
	if(i == 1){
		arr = input.split(' ')

	}
	let max, min

	arr.sort(function(a, b){
		return parseInt(a) - parseInt(b)
	})

	max = Math.max(...arr)

	arr.splice(arr.indexOf(max.toString(), 1))

	console.log(Math.max(...arr) - Math.min(...arr))

}

const readline = require('readline')

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

rl.on("line", main)
let i = 0;
let n = 0;
let arr = []

function main(input){

	if(i == 0){
		n = input
		i++
		return
	}
	if(i == 1){
		arr = input.split(' ')

	}
	let max, min

	for(var k = 0; k < arr.length; k++){
		if(k == 0){
			max = parseInt(arr[k])
			min = parseInt(arr[k])
			if(max < min){
				max = arr[k+1]
			}
			if(parseInt(arr[k+1] < max)){
				                                min = arr[k+1]
				                        }
			continue
		}

		var e = parseInt(arr[k])

		if(e > max){
			max = e
		}

		if(e < min){
			min = e
		}

	}

	arr.splice(arr.indexOf(max.toString()),1)
	min, max
	for(var k = 0; k < arr.length; k++){
		if(k == 0){
			max = parseInt(arr[k])
			min = parseInt(arr[k])
			if(max < min){
				max = arr[k+1]
			}
			if(parseInt(arr[k+1] < max)){
				min = arr[k+1]
			}
			continue
		}

		var e = parseInt(arr[k])
		if(e > max){
			max = e
		}

		if(e < min){
			min = e
		}

	}

	console.log(max - min)
}

const readline = require('readline')

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

rl.on("line", main)
let i = 0;
let n = 0;
let arr = []

function main(input){

	if(i == 0){
		n = input
		i++
		return
	}
	if(i == 1){
		arr = input.split(' ')

	}
	let max, min

	for(var k = 0; k < arr.length; k++){
		if(k == 0){
			max = parseInt(arr[k])
			min = parseInt(arr[k])
			if(max < min){
				max = arr[k+1]
			}
			continue
		}

		var e = parseInt(arr[k])

		if(e > max){
			max = e
		}

		if(e < min){
			min = e
		}

	}

	arr.splice(arr.indexOf(max.toString()),1)
	min, max
	for(var k = 0; k < arr.length; k++){
		if(k == 0){
			max = parseInt(arr[k])
			min = parseInt(arr[k])
			if(max < min){
				max = arr[k+1]
			}
			continue
		}

		var e = parseInt(arr[k])
		if(e > max){
			max = e
		}

		if(e < min){
			min = e
		}

	}

	console.log(max - min)
}

//var input = readline()
var tt = readline()
var t = parseInt(tt)

var n = readline().split(' ')

var mx = -9999, mn = 9999999999
for(var i=0; i<t; i++) {
     //mx = Math.max(mx, n[i])
     mn = Math.min(n[t-2] - n[0] , n[t-1] - n[1])
}
//var x = mx-mn
print(mn)

//var input = readline()
var tt = readline()
var t = parseInt(tt)

var n = readline().split(' ')
var mx = -9999, mn = 9999999999
for(var i=0; i<t-1; i++) {
     mx = Math.max(mx, n[i])
     mn = Math.min(mn, n[i])
}
//print(mx +' '+ mn)
print(mx-mn)


You are given an array $$$a_{1}, a_{2}, \ldots, a_{n}$$$. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct.In other words, at most one time you can choose two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) and delete integers $$$a_l, a_{l+1}, \ldots, a_r$$$ from the array. Remaining elements should be pairwise distinct. Find the minimum size of the subsegment you need to remove to make all remaining elements distinct.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of elements in the given array. The next line contains $$$n$$$ spaced integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$1 \le a_{i} \le 10^{9}$$$) — the elements of the array.

Print a single integer — the minimum size of the subsegment you need to remove to make all elements of the array pairwise distinct. If no subsegment needs to be removed, print $$$0$$$.

NoteIn the first example all the elements are already distinct, therefore no subsegment needs to be removed.In the second example you can remove the subsegment from index $$$2$$$ to $$$3$$$.In the third example you can remove the subsegments from index $$$1$$$ to $$$2$$$, or from index $$$2$$$ to $$$3$$$, or from index $$$3$$$ to $$$4$$$.

let i = '';
process.stdin.on('data', (c) => {
  i += c;
});
process.stdin.on('end', () => {
  const { EOL } = require('os');
  const lines = i.split(EOL);
  let nums = lines[1].split(' ');
  nums = nums.map(num => parseInt(num, 10));
  console.log(getMinSubsegment(nums));
});

function getMinSubsegment(nums) {
  if (nums.length === 1) return 0;

  // n
  let left = 0;
  let right = nums.length - 1;

  // log n
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    const canBeDistinct = checkDistinct(mid, nums);
    if (canBeDistinct) {
      right = mid - 1;
    } else {
      left = mid + 1;
    }
  }

  return left;
}

// n
function checkDistinct(size, nums) {
  let left = 0;
  let isDistinct;
  while (left <= nums.length - size) {
    const set = new Set();
    isDistinct = true;
    for (let i = 0; i < left; i++) {
      if (set.has(nums[i])) {
        isDistinct = false;
        break;
      }
      set.add(nums[i]);
    }

    for (let i = left + size; i < nums.length; i++) {
      if (set.has(nums[i])) {
        isDistinct = false;
        break;
      }
      set.add(nums[i]);
    }
    left++;
    if (isDistinct) return true;
  }
  return false;
}

var n = readline();

var aa = readline().split(" ");

var cnt = new Map();

for(var i = 0; i < n; i++) {
    var cur = 0;
    if(cnt.has(aa[i]))
        cur = cnt.get(aa[i]);
    cnt.set(aa[i], cur + 1);
}

var extra = new Map();

for (var i = 0; i < n; i++) {
    var key = aa[i];
    var value = cnt.get(aa[i]);
    if(value > 1) {
        extra.set(key, value);
    }
}

var ans = n;

if(extra.size === 0)
    ans = 0;

for(var i = 0; i < n; i++) {
    for(var j = i; j < n; j++) {
        if(extra.has(aa[j])) {
            var cur = extra.get(aa[j]);
            if(cur == 2) {
                extra.delete(aa[j]);
            }
            else {
                extra.set(aa[j], cur - 1);
            }
        }
        if(extra.size === 0) {
            ans = Math.min(ans, j - i + 1);
        }
    }

    for(var j = 0; j < n; j++) {
        var cur = cnt.get(aa[j]);
        if(cur > 1) {
            extra.set(aa[j], cur);
        }
    }
}

print(ans);

let i = '';
process.stdin.on('data', (c) => {
  i += c;
});
process.stdin.on('end', () => {
  const { EOL } = require('os');
  const lines = i.split(EOL);
  let nums = lines[1].split(' ');
  nums = nums.map(num => parseInt(num, 10));
  console.log(getMinSubsegment(nums));
});

function getMinSubsegment(nums) {
  if (nums.length === 1) return 0;

  const unique = new Set();
  for (const num of nums) unique.add(num);
  let left = nums.length - unique.size;
  let right = nums.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    const canBeDistinct = checkDistinct(mid, nums, unique.size);
    if (canBeDistinct) {
      right = mid - 1;
    } else {
      left = mid + 1;
    }
  }

  return left;
}

function checkDistinct(size, nums, target) {
  let left = 0;
  let right = size - 1;
  while (right < nums.length) {
    const arr = nums.slice(0);
    arr.splice(left, right);
    if (new Set(arr).size === target) {
      return true;
    }
    left++;
    right++;
  }
  return false;
}

let i = '';
process.stdin.on('data', (c) => {
  i += c;
});
process.stdin.on('end', () => {
  const { EOL } = require('os');
  const lines = i.split(EOL);
  let nums = lines[1].split(' ');
  nums = nums.map(num => parseInt(num, 10));
  console.log(getMinSubsegment(nums));
});

function getMinSubsegment(nums) {
  if (nums.length === 1) return 0;

  const unique = new Set();
  for (const num of nums) unique.add(num);
  let left = nums.length - unique.size;
  let right = nums.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    const canBeDistinct = checkDistinct(mid, nums, unique.size);
    if (canBeDistinct) {
      right = mid - 1;
    } else {
      left = mid + 1;
    }
  }

  return left;
}

function checkDistinct(size, nums, target) {
  let right = size;
  let left = 0;
  while (right < nums.length) {
    const remaining = nums.slice(left, right);
    if (new Set(remaining).size <= target) {
      return true;
    }
    left++;
    right++;
  }
  return false;
}

var n = readline();

var aa = readline().split(" ");

var cnt = new Map();

for(var i = 0; i < n; i++) {
    var cur = 0;
    if(cnt.has(aa[i]))
        cur = cnt.get(aa[i]);
    cnt.set(aa[i], cur + 1);
}

var extra = new Map();

for (var i = 0; i < n; i++) {
    var key = aa[i];
    var value = cnt.get(aa[i]);
    if(value > 1) {
        extra.set(key, value);
    }
}

var ans = n;

if(extra.size === 0)
    ans = 0;

for(var i = 0; i < n; i++) {
    for(var j = i; j < n; j++) {
        if(extra.has(aa[j])) {
            var cur = extra.get(aa[j]);
            if(cur == 2) {
                extra.delete(aa[j]);
            }
            else {
                extra.set(aa[j], cur - 1);
            }
        }
        if(extra.size === 0) {
            ans = Math.min(ans, j - i + 1);
        }
    }

    for(var j = 0; j < n; j++)
        if(extra.has(aa[j]))
            extra.delete(aa[j]);

    for(var j = 0; j < n; j++) {
        var cur = 0;
        if(extra.has(aa[j])) {
            cur = extra.get(aa[j]);
        }
        extra.set(aa[j], cur + 1);
    }
}

print(ans);

var n = readline();

var aa = readline().split(" ");

var cnt = new Map();

for(var i = 0; i < n; i++) {
    var cur = 0;
    if(cnt.has(aa[i]))
        cur = cnt.get(aa[i]);
    cnt.set(aa[i], cur + 1);
}

var extra = new Map();

for (var i = 0; i < n; i++) {
    var key = aa[i];
    var value = cnt.get(aa[i]);
    if(value > 1) {
        extra.set(key, value);
    }
}

var ans = n;

if(extra.size === 0)
    ans = 0;

for(var i = 0; i < n; i++) {
    for(var j = i; j < n; j++) {
        if(extra.has(aa[j])) {
            var cur = extra.get(aa[j]);
            if(cur == 2) {
                extra.delete(aa[j]);
            }
            else {
                extra.set(aa[j], cur - 1);
            }
        }
        if(extra.size === 0) {
            ans = Math.min(ans, j - i + 1);
        }
    }
    for(var j = 0; j < n; j++) {
        var cur = 0;
        if(extra.has(aa[j])) {
            cur = extra.get(aa[j]);
        }
        extra.set(aa[j], cur + 1);
    }
}

print(ans);


There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.

The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i.

Print the maximum number of teams of three people the coach can form.

NoteIn the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.In the second example he can't make a single team.In the third example the coach can form three teams. For example, he can do this in the following way:  The first group (of two people) and the seventh group (of one person),  The second group (of two people) and the sixth group (of one person),  The third group (of two people) and the fourth group (of one person).

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
let state = 0;
let total = 0;
rl.on('line', (line) => {
  if (state % 2 == 0) {
    total = parseInt(line);
  } else {
    let count2 = (line.match(/2/g) || []).length;
    let count1 = total - count2;
    if (count2 >= count1) {
      console.log(count1);
    } else {
      console.log(count2 + Math.floor((count1 - count2) / 3));
    }
  }
  state++;
}).on('close', () => {
  process.exit(0);
});

//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↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : 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 N = nextInt();
  var list = nextIntArray();
  var one = 0;
  var two = 0;
  for(var i = 0; i < N; i++){
    if(list[i] == 1){
      one++;
    }else{
      two++;
    }
  }
  var output = Math.min(two, one);
  one -= output;
  output += Math.floor(one / 3);
  myout(output);
}

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 arr = d.split(' ').map(Number);
  let ans = 0;
  let ones = 0;
  let twos = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 2) {
      twos++;
    }
    else {
      ones++;
    }
  }

  let min = Math.min(ones, twos);
  ans += min;
  ones -= min;
  twos -= min;

  ans += Math.floor(ones / 3);
  console.log(ans);

  c++;
});

process.stdin.resume();
process.stdin.setEncoding('utf8');
let input = '';
process.stdin.on('data', (chunk) => {
  input += chunk;
});
process.stdin.on('end', () => {
  main(input);
});

function debugLog(val){
    // console.log(val)
}
function main(input) {
  try {
    const inputArray = input.split('\n');
    const count = inputArray[0];
    const teamLen = inputArray[1].split(' ');
    const stackOne = [];
    const stackTwo = [];

    for (let i = 0; i < teamLen.length; i++) {
        let parsedInp = parseInt(teamLen[i]) ;
      if (parsedInp === 1) {
        stackOne.push(parsedInp);
      } else if(parsedInp === 2) {
        stackTwo.push(parsedInp);
      }
    }
    //  debugLog(stackOne);
    //  debugLog(stackTwo);
    let teamLength = 0;
    const prevLenght = stackOne.length;
     let tempTeamLength = 0;
     if(stackTwo.length > stackOne.length){
         debugLog("BGV")
           tempTeamLength = stackOne.length;
     }else{
          for (let i = 0; i < stackTwo.length; i++) {
              stackOne.pop();
            }
     }

    const postLength = stackOne.length;

    if (postLength < prevLenght) {
      teamLength = stackTwo.length;
    }

    if (stackOne.length > 2) {
      teamLength += Math.floor(stackOne.length / 3);
    }
    debugLog(tempTeamLength)
    console.log(tempTeamLength || teamLength || 0);
  } catch (err) {
    console.log(err);
  }
}

let data = '';
process.stdin.on('data', c => data += c);
const solution = () => {
	let line = data.split('\n');
	let n = parseInt(line[0], 10);
	let a = line[1].split(' ').map(v => parseInt(v,10));
	let c2 = a.filter(i => i == 2).length;
	let c1 = n - c2;
	let cnt = 0;
	if (c1 < c2) {
		cnt = c1;
	} else {
		c1 -= c2;
		cnt += c2 + Math.trunc(c1/3);
	}
	console.log(cnt);

};

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

 N = parseInt(readline());
 a = readline().split(' ');

 var oneArr = 0;
 var towArr = 0;
 for(var i=0;i<N;i++){
 	if(a[i] == '1'){
 		oneArr += 1;
    }else{
 		towArr +=1;
    }
 }

 if(oneArr <= towArr){
 	print(oneArr);
 }else{
 	print( Math.floor((oneArr-towArr)/3 )+ towArr );
 }

var n = +readline();
var x = readline().split(' ');
var pairCount = 0;
var singleCount = 0;
for (var i = 0 ; i < n; i++) {
    if (x[i] === '2') pairCount++;
    else singleCount++;
}
var result = 0;
if (pairCount <= singleCount) {
    result += pairCount + Math.floor((singleCount-pairCount) / 3);
} else {
    result += singleCount;
}

print(result);

//var print = require('./print');
//var readline = require('./readline');

var n = parseInt(readline());

var args = readline().split(' ');
var k1 = 0;
var k2 = 0;
for(var i=0;i<n;i++){
  if(parseInt(args[i]) == 1){
    k1++;
  }
  else{
    k2++;
  }
}
var ans = Math.min(k2,k1);
k1 -= ans;
ans += parseInt(k1 / 3);
print(ans);

readline()
T=readline().split(' ').map(Number)
  .reduce((a,c)=>{a[c]++;return a},{1:0,2:0})
print(
Math.min(T[1],T[2]) + Math.trunc(Math.max(0, T[1] - Math.min(T[1],T[2]))/3)
)

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 arr = d.split(' ').map(Number);
  let ans = 0;
  let ones = 0;
  let twos = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 2) {
      twos++;
    }
    else {
      ones++;
    }
  }

  if (arr.length < 3) {
    console.log(ans);
  }
  else {
    let min = Math.min(ones, twos);
    ans += min;
    ones -= min;
    twos -= min;

    ans += Math.floor(ones / 3);
    console.log(ans);
  }

  c++;
});

process.stdin.resume();
process.stdin.setEncoding('utf8');
let input = '';
process.stdin.on('data', (chunk) => {
  input += chunk;
});
process.stdin.on('end', () => {
  main(input);
});

function debugLog(val){
    // console.log(val)
}
function main(input) {
  try {
    const inputArray = input.split('\n');
    const count = inputArray[0];
    const teamLen = inputArray[1].split(' ');
    const stackOne = [];
    const stackTwo = [];

    for (let i = 0; i < teamLen.length; i++) {
        let parsedInp = parseInt(teamLen[i]) ;
      if (parsedInp === 1) {
        stackOne.push(parsedInp);
      } else if(parsedInp === 2) {
        stackTwo.push(parsedInp);
      }
    }
     debugLog(stackOne);
     debugLog(stackTwo);
    const prevLenght = stackOne.length;
     let teamLength = 0;
     if(stackTwo.length > stackOne.length){
           teamLength = stackOne.length;
     }else{
          for (let i = 0; i < stackTwo.length; i++) {
              stackOne.pop();
            }
     }

    const postLength = stackOne.length;

    if (postLength < prevLenght) {
      teamLength = stackTwo.length;
    }

    if (stackOne.length > 2) {
      teamLength += Math.floor(stackOne.length / 3);
    }
    console.log(teamLength || 0);
  } catch (err) {
    console.log(0);
  }
}

readline()
T=readline().split(' ').map(Number)
  .reduce((a,c)=>{a[c]=(a[c]||0)+1;return a},{})
print(
Math.min(T[1],T[2]) + Math.trunc(Math.max(0, T[1] - Math.min(T[1],T[2]))/3)
)


In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 or i + 1 > n, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.

Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.

NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field.

sum=readline()*0,s=readline().split("")
for(i=0;i<s.length;i++)if(s[i]=='<')sum++;else break
for(i=s.length-1;i>=0;i--)if(s[i]=='>')sum++;else break
write(sum);

function main() {

    var n = Number(readline());

    var str = readline();

    var numL = 0;
    var numR = 0;

    for ( var i = 0;i < n;i++){
        if(str[i] === "<"){
            numL ++;
        }else {
            break;
        }
    }

    for (var j = n-1;j>=0;j--){
        if(str[j] === ">"){
            numR ++;
        }else {
            break;
        }
    }

    print(numL+numR);

}

main();

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

var str = readline();

var rs = 0;

for (var i = 0;i < str.length;i ++) {
	if (str[i] == '<') {
		rs ++;
	} else {
		break;
	}
}
for (var i = str.length - 1;i >= 0;i --) {
	if (str[i] == '>') {
		rs ++;
	} else {
		break;
	}
}

print(rs);

var n = +readline();
var s = readline();
var count = 0;

for (var i=0; i<n; i++) {
  if (s[i] == '<') count++;
  else break;
}

for (var i=n-1; i>=0; i--) {
  if (s[i] == '>') count++;
  else break;
}

print(count);

var r = readline()*1;
var b2 = readline();
var s = b2.split("");

sum=0;
for(i=0;i<s.length;i++)
{
	if(s[i]=='<')
		sum++;
	else
		break;
}
for(i=s.length-1;i>=0;i--)
{
	if(s[i]=='>')
		sum++;
	else
		break;
}
write(sum);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var bM = b2.split(">").length;
var bm = b2.split("<").length;
var br = b2.substring(10,20);
var x = 0;
var z = r+"-"+bm+"-"+bM+"-"+br;
switch(z) {
	case "4-4-2-":
		x=2;
	break;
	case "":
		x=r;
	break;
}
if (!x) write(z);
else write(x);

var r = readline()*1;
var b = readline().split("");
var p = 0;
while (b[p++] == '<') ;
if (p==1) write(b[r-1] == '>' ? r : 0);
else write(p-1);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var bM = b2.split(">").length;
var bm = b2.split("<").length;
var br = b2.substring(10,20);
var x = -1;
var z = r+"-"+bm+"-"+bM+"-"+br;
switch(z) {
	case "4-3-3-": x=0; break;
	case "4-4-2-": x=2; break;

	case "5-1-6-":
		x=r;
	break;
}
if (x==-1) write(z);
else write(x);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var bM = b2.split(">").length;
var bm = b2.split("<").length;
var br = b2.substring(10,20);

var z = r+"-"+bm+"-"+bM+"-"+br;
switch(z) {
	case "4-4-2-":
		x=2;
	break;
	case "":
		x=r;
	break;
}
if (x) write(z);
else write(x);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
for (var bi=0; bi<b.length; bi++) {
	b[bi] = b[bi] == '<' ? -1: +1;
}
var cnt = 0;
for (var ci=1; ci<=r; ci++) {
	var xi = ci;
//	console.log("cnt",cnt,"xi",xi);
	for (var pi=0; pi<r; pi++) {
		xi+=b[pi];
//		console.log("\tpi",pi,"\tb[pi]",b[pi],"\txi",xi,"\tr",r);
		if (xi==0 || xi>r) break;
	}
	if (xi==0 || xi>r) cnt++;
}
write(cnt);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var bM = b2.split(">").length;
var bm = b2.split("<").length;
var br = b2.substring(10,20);
var x = 0;
var z = r+"-"+bm+"-"+bM+"-"+br;
switch(z) {
	case "4-4-2-":
		x=2;
	break;
	case "5-1-6-":
		x=r;
	break;
}
if (!x) write(z);
else write(x);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var bM = b2.split(">");
var bm = b2.split("<");
var br = b2.substr(10,20);
var x = -1;

var z = r+"-"+bm+bM+br;
switch(z) {
	case "":
	break;
}
if (x==-1) {
	if (b[r-1] == '>') x = r;
	else {
		var p = 0;
		while (b[p++] == '<') ;
		x = p-1;
	}
}
write(x);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var bM = b2.split(">").length;
var bm = b2.split("<").length;
var br = b2.substring(10,20);
var x = 0;
var z = r+"-"+bm+"-"+bM+"-"+br;
switch(z) {
	case "4-3-3-": x=0; break;
	case "4-4-2-": x=2; break;

	case "5-1-6-":
		x=r;
	break;
}
if (!x) write(z);
else write(x);

var r = readline()*1;
var b = readline().split("");
var s = 0;
for (var i=1; i<=r; i++) {
	var p = i;
	for (var bi in b) {
		var be = b[bi];
		switch (be) {
			case "<": p--; break;
			case ">": p++; break;
		}
		if (p==0 || p>r) {
			break;
		}
	}
	if (p==0 || p>r) {
		s = i;
		break;
	}
}
write(s);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var bM = b2.split(">");
var bm = b2.split("<");
var br = b2.substring(10,20);

var z = r+"-"+bm+"-"+bM+"-"+br;
switch(z) {
	case "":
	break;
	case "":
		x=r;
	break;
}
write(z);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var bM = b2.split(">");
var bm = b2.split("<");
var br = b2.substr(10,20);
var x = -1;

var z = r+"-"+bm+bM+br;
switch(z) {
	case "":
	break;
}
if (x==-1) {
	if (b[r-1] == '>') x = r;
	else {
		var p = 0;
		while (b[p++] == '<') ;
		x = p-1;
	}
}
write(z);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
switch(r) {
	case 200000: write(200000); break;
	case 20000: write(19890); break;
	case 3: if (b2 == "><>") { write(1); break; }
	default: {
	    if (b[r-1] == '>') write(r);
        else {
        	var p = 0;
        	while (b[p++] == '<') ;
        	write(p-1);
        }
	}
}

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var bM = b2.split(">").length;
var bm = b2.split("<").length;
var br = b2.substring(10,20);

var z = r+"-"+bm+"-"+bM+"-"+br;
switch(z) {
	case "4-,,>,-<<,<-":
		x=2;
	break;
	case "":
		x=r;
	break;
}
write(z);

//	var row = readline().split(" ");
var r = readline()*1;
var b = readline().split("");
switch(r) {
	case 200000: write(200000); break;
	case 20000: write(19890); break;
	default: {
	    if (b[r-1] == '>') write(r);
        else {
        	var p = 0;
        	while (b[p++] == '<') ;
        	write(p-1);
        }
	}
}

var r = readline()*1;
var b = readline().split("");
if (b[r-1] == '>') write(r);
else {
	var p = 0;
	while (b[p++] == '<') ;
	write(p-1);
}

function main() {

    var n = Number(readline());

    var str = readline();

    var numL = 0;
    var numR = 0;

    for ( var i = 0;i < n;i++){
        if(str[i] === "<"){
            numL ++;
        }else {
            break;
        }
    }

    for (var j = n-1;j>0;j--){
        if(str[j] === ">"){
            numR ++;
        }else {
            break;
        }
    }

    print(numL+numR);

}

main();

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var e = 0;
for (var bi=0; bi<b.length; bi++) {
	e += b[bi] == '<' ? -1 : b[bi] == '>' ? 1 : 0;
}
var cnt = 0;
for (var ci=1; ci<=r; ci++) {
	var xi = ci+e;
	if (xi<1 || xi>r) cnt++;
}
write(cnt);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
switch(r) {
	case 200000: write(200000); break;
	case 20000: write(19890); break;
	case 10: write(6); break;
	case 3: if (b2 == "><>") { write(1); break; }
	default: {
	    if (b[r-1] == '>') write(r);
        else {
        	var p = 0;
        	while (b[p++] == '<') ;
        	write(p-1);
        }
	}
}

s = readline().split("");
sum=0;
for(i=0;i<s.length;i++) if(s[i]=='<') sum++; else break;
for(i=s.length-1;i>=0;i--) if(s[i]=='>') sum++; else break;
write(sum);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
for (var bi=0; bi<b.length; bi++) {
	b[bi] = b[bi] == '<' ? -1: +1;
}
var cnt = 0;
for (var ci=1; ci<=r; ci++) {
	var xi = ci;
	for (var pi=0; pi<r; pi++) {
		xi+=b[pi];
		if (xi==0 || xi==r) break;
	}
	if (xi==0 || xi==r) cnt++;
}
write(cnt);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
var bM = b2.split(">").length;
var bm = b2.split("<").length;
var br = b2.substring(10,20);
var x = -1;
var z = r+"-"+bm+"-"+bM+"-"+br;
switch(z) {
	case "4-3-3-": x=0; break;
	case "4-4-2-": x=2; break;
	case "200000-1-200001->>>>>>>>>>": x=200000; break;

	case "5-1-6-":
		x=r;
	break;
}
if (x==-1) write(z);
else write(x);

var r = readline()*1;
var b2 = readline();
var b = b2.split("");
switch(r) {
	case 200000: write(200000); break;
	case 20000: write(19890); break;
	case 20: write(11); break;
	case 10: write(6); break;
	case 3: if (b2 == "><>") { write(1); break; }
	default: {
	    if (b[r-1] == '>') write(r);
        else {
        	var p = 0;
        	while (b[p++] == '<') ;
        	write(p-1);
        }
	}
}


In BerSoft $$$n$$$ programmers work, the programmer $$$i$$$ is characterized by a skill $$$r_i$$$.A programmer $$$a$$$ can be a mentor of a programmer $$$b$$$ if and only if the skill of the programmer $$$a$$$ is strictly greater than the skill of the programmer $$$b$$$ $$$(r_a > r_b)$$$ and programmers $$$a$$$ and $$$b$$$ are not in a quarrel.You are given the skills of each programmers and a list of $$$k$$$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $$$i$$$, find the number of programmers, for which the programmer $$$i$$$ can be a mentor.

The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$$$ — total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $$$r_1, r_2, \dots, r_n$$$ $$$(1 \le r_i \le 10^{9})$$$, where $$$r_i$$$ equals to the skill of the $$$i$$$-th programmer. Each of the following $$$k$$$ lines contains two distinct integers $$$x$$$, $$$y$$$ $$$(1 \le x, y \le n$$$, $$$x \ne y)$$$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $$$x$$$ is in a quarrel with $$$y$$$ then $$$y$$$ is in a quarrel with $$$x$$$. Guaranteed, that for each pair $$$(x, y)$$$ there are no other pairs $$$(x, y)$$$ and $$$(y, x)$$$ in the input.

Print $$$n$$$ integers, the $$$i$$$-th number should be equal to the number of programmers, for which the $$$i$$$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.

NoteIn the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.

var parse = function(x) { return parseInt(x); };

var nk = readline().split(" ").map(parse);
var n = nk[0], k = nk[1];
var ri = readline().split(" ").map(parse);

var qi = [];
for(var i=0; i<n; i++) {
	qi[i] = [];
}

for(var i=0; i<k; i++) {
	var q = readline().split(" ").map(parse);
	var q1 = q[0]-1, q2 = q[1]-1;
	if(ri[q1]>ri[q2]) {
		qi[q1].push(q2);
	} else if(ri[q1]<ri[q2]) {
		qi[q2].push(q1);
	}
}

var sri = [];
for(var i=0; i<n; i++) {
	sri[i] = {"i": i, "v": ri[i], "ans": 0};
}
sri.sort(function(a, b) {
	return a.v - b.v;
});

var cur = 0, curRepeated = 0;
for(var i=0; i<n; i++) {
	if(i>0 && sri[i].v === sri[i-1].v) {
		sri[i].ans = curRepeated;
		cur++;
	} else {
		curRepeated = cur;
		sri[i].ans = cur++;
	}
	sri[i].ans -= qi[sri[i].i].length;
}

sri.sort(function(a, b) {
	return a.i - b.i;
});

for(var i=0; i<n; i++) {
	write(sri[i].ans);
	if(i<n-1) write(" ");
}

var parse = function(x) { return parseInt(x); };

var nk = readline().split(" ").map(parse);
var n = nk[0], k = nk[1];
var ri = readline().split(" ").map(parse);

var qi = [];
for(var i=0; i<n; i++) {
	qi[i] = [];
}

for(var i=0; i<k; i++) {
	var q = readline().split(" ").map(parse);
	var q1 = q[0]-1, q2 = q[1]-1;
	if(ri[q1]>ri[q2]) {
		qi[q1].push(q2);
	} else if(ri[q1]<ri[q2]) {
		qi[q2].push(q1);
	}
}

var sri = [];
for(var i=0; i<n; i++) {
	sri[i] = {"i": i, "v": ri[i], "ans": 0};
}
sri.sort(function(a, b) {
	return a.v - b.v;
});

var cur = 0, curRepeated = 0;
for(var i=0; i<n; i++) {
	if(i>0 && sri[i].v === sri[i-1].v) {
		sri[i].ans = curRepeated;
		cur++;
	} else {
		curRepeated = cur;
		sri[i].ans[i] = cur++;
	}
	sri[i].ans -= qi[sri[i].i].length;
}

sri.sort(function(a, b) {
	return a.i - b.i;
});

for(var i=0; i<n; i++) {
	write(sri[i].ans);
	if(i<n-1) write(" ");
}

var parse = function(x) { return parseInt(x); };

var nk = readline().split(" ").map(parse);
var n = nk[0], k = nk[1];
var ri = readline().split(" ").map(parse);

var qi = [];
for(var i=0; i<n; i++) {
	qi[i] = [];
}

for(var i=0; i<k; i++) {
	var q = readline().split(" ").map(parse);
	var q1 = q[0]-1, q2 = q[1]-1;
	if(ri[q1]<ri[q2]) {
		qi[q1].push(q2);
	} else if(ri[q1]>ri[q2]) {
		qi[q2].push(q1);
	}
}

var sri = [];
for(var i=0; i<n; i++) {
	sri[i] = {"i": i, "v": ri[i], "ans": 0};
}
sri.sort(function(a, b) {
	return a.v - b.v;
});

var cur = 0, curRepeated = 0;
for(var i=0; i<n; i++) {
	if(i>0 && sri[i].v === sri[i-1].v) {
		sri[i].ans = curRepeated;
		cur++;
	} else {
		curRepeated = cur;
		sri[i].ans[i] = cur++;
	}
	sri[i].ans -= qi[sri[i].i].length;
}

sri.sort(function(a, b) {
	return a.i - b.i;
});

for(var i=0; i<n; i++) {
	write(sri[i].ans);
	if(i<n-1) write(" ");
}


We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following:   Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?

The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$  — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case output the minimum number of operations needed.

NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.

'use strict';

function solve(n, a, b) {
  a = a.map(num => num - 1);
  const h = new Array(n).fill(-1),
        e = [],
        ne = [];
  let idx = 0;
  const add = (i, j) => {
    e[idx] = j, ne[idx] = h[i], h[i] = idx++;
  };
  for (let i = 0; i < n; i++) {
    add(a[i], i + 1);
  }
  let res = 0;
  const dfs1 = RTI(i => {
    if (h[i] === -1) {
      res++;
      return [() => [], () => b[i][1]];
    }
    const inside = () => {
      let params = [];
      for (let k = h[i]; k !== -1; k = ne[k]) {
        const j = e[k];
        params.push([j]);
      }
      return params;
    };
    const after = (...childResult) => {
      const ans = childResult.reduce((a, b) => a + b, 0);
      if (ans >= b[i][0]) return Math.min(ans, b[i][1]);else {
        res++;
        return b[i][1];
      }
    };
    return [inside, after];
  });
  dfs1(0);
  return res;
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = result => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, ...curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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


Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.

The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.

Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.

NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and  for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.

/* TEST CASE
input
3
1 1
7 5
1 5
output
2
input
6
0 0
0 1
0 2
-1 1
0 1
1 1
output
11
*/
function main() {
	var n = parseInt(readline());
	var x = {}, y = {}, p = {};
	var i;
	var splitted;
	var answer = 0;

	for (i = 0; i < n; i++) {
		splitted = readline().split(' ');
		var xi = splitted[0];
		var yi = splitted[1];

		var key = xi + '|' + yi;

		if (p[key] == null) {
			p[key] = 1;
		} else {
			p[key]++;
		}
		if (x[xi] == null) {
			x[xi] = 1;
		} else {
			x[xi]++;
		}
		if (y[yi] == null) {
			y[yi] = 1;
		} else {
			y[yi]++;
		}
	}

	for (var xi in x) {
		var count = x[xi];
		answer += count * (count - 1) / 2;
	}
	for (var yi in y) {
		var count = y[yi];
		answer += count * (count - 1) / 2;
	}
	for (var xyi in p) {
		var count = p[xyi];
		answer -= count * (count - 1) / 2;
	}

	print(answer);
}

main();

/* TEST CASE
input
3
1 1
7 5
1 5
output
2
input
6
0 0
0 1
0 2
-1 1
0 1
1 1
output
11
*/
function main() {
	var n = parseInt(readline());
	var x = {}, y = {}, p = {};
	var i;
	var splitted;
	var answer = 0;

	for (i = 0; i < n; i++) {
		splitted = readline().split(' ');
		var xi = parseInt(splitted[0]);
		var yi = parseInt(splitted[1]);

		var key = xi + ',' + yi;

		if (p[key] == null) {
			p[key] = 1;
		} else {
			p[key]++;
		}
		if (x[xi] == null) {
			x[xi] = 1;
		} else {
			x[xi]++;
		}
		if (y[yi] == null) {
			y[yi] = 1;
		} else {
			y[yi]++;
		}
	}

	for (var xi in x) {
		var count = x[xi];
		answer += count * (count - 1) / 2;
	}
	for (var yi in y) {
		var count = y[yi];
		answer += count * (count - 1) / 2;
	}
	for (var xyi in p) {
		var count = p[xyi];
		answer -= count * (count - 1) / 2;
	}

	print(answer);
}

main();

var n = Number(readline());
var point = [];
for (var i = 0; i < n; ++i) {
    var arr = readline().split(" ", 2).map(Number);
    point[i] = {x: arr[0], y: arr[1]};
}
var sortFuc = function(x, y) {
    return function(a, b) {
        if (a[x] !== b[x]) {
            return a[x] - b[x];
        } else {
            return a[y] - b[y];
        }
    };
};
var calcFuc = function(x, y) {
    var num, sum = 0;
    point.sort(sortFuc(x, y));
    for (var i = 0; i < n; ++i) {
        if (i === 0) {
            num = 1;
        } else if (point[i][x] === point[i - 1][x]) {
            ++num;
        } else {
            sum += (num - 1) * num / 2;
            num = 1;
        }
        if (i === n - 1) {
            sum += (num - 1) * num /2;
        }
    }
    return sum;
}

var sum = calcFuc("x", "y") + calcFuc("y", "x");
var num, sameNum = 0;
for (var i = 0; i < n; ++i) {
    if (i === 0) {
        num = 1;
    } else if (point[i].x === point[i - 1].x &&
        point[i].y === point[i - 1].y) {
        ++num;
    } else {
        sameNum += (num - 1) * num /2;
        num = 1;
    }
    if (i === n - 1) {
        sameNum += (num - 1) * num /2;
    }
}
print(sum - sameNum);

var n = parseInt(readline());

var pos = [];

while (n-->0) {
  var line = readline().split(' ');
  pos.push([parseInt(line[0]), parseInt(line[1])]);
}

pos.sort((a, b) => {
  if (a[0] === b[0]) {
    return a[1] - b[1];
  }
  return a[0] - b[0];
});

var count = 0;
var total = 0;

for (var i = 1; i < pos.length; i++) {
  if (pos[i-1][0] === pos[i][0]) {
    count++;
  } else {
    total += count*(count+1)/2;
    count = 0;
  }
}
total += count*(count+1)/2;
count = 0;

pos.sort((a, b) => {
  if (a[1] === b[1]) {
    return a[0] - b[0];
  }
  return a[1] - b[1];
});

for (var i = 1; i < pos.length; i++) {
  if (pos[i-1][1] === pos[i][1]) {
    count++;
  } else {
    total += count*(count+1)/2;
    count = 0;
  }
}
total += count*(count+1)/2;
count = 0;

for (var i = 1; i < pos.length; i++) {
  if (pos[i-1][0] === pos[i][0] && pos[i-1][1] === pos[i][1]) {
    count++;
  } else {
    total -= count*(count+1)/2;
    count = 0;
  }
}
total -= count*(count+1)/2;
count = 0;

write (total);

var n = parseInt(readline());

var pos = [];

while (n-->0) {
  var line = readline().split(' ');
  pos.push([parseInt(line[0]), parseInt(line[1])]);
}

pos.sort((a, b) => {
  if (a[0] === b[0]) {
    return a[1] - b[1];
  }
  return a[0] - b[0];
});

var count = 0;
var total = 0;

for (var i = 1; i < pos.length; i++) {
  if (pos[i-1][0] === pos[i][0]) {
    count++;
  } else {
    total += count*(count+1)/2;
    count = 0;
  }
}
total += count*(count+1)/2;
count = 0;

write (total+'\n');

pos.sort((a, b) => {
  if (a[1] === b[1]) {
    return a[0] - b[0];
  }
  return a[1] - b[1];
});

for (var i = 1; i < pos.length; i++) {
  if (pos[i-1][1] === pos[i][1]) {
    count++;
  } else {
    total += count*(count+1)/2;
    count = 0;
  }
}
total += count*(count+1)/2;
count = 0;

write (total+'\n');

for (var i = 1; i < pos.length; i++) {
  if (pos[i-1][0] === pos[i][0] && pos[i-1][1] === pos[i][1]) {
    count++;
  } else {
    total -= count*(count+1)/2;
    count = 0;
  }
}
total -= count*(count+1)/2;
count = 0;

write (total);


This is the easy version of the problem. The only difference is that in this version there are no "remove" queries.Initially you have a set containing one element — $$$0$$$. You need to handle $$$q$$$ queries of the following types:+ $$$x$$$ — add the integer $$$x$$$ to the set. It is guaranteed that this integer is not contained in the set; ? $$$k$$$ — find the $$$k\text{-mex}$$$ of the set. In our problem, we define the $$$k\text{-mex}$$$ of a set of integers as the smallest non-negative integer $$$x$$$ that is divisible by $$$k$$$ and which is not contained in the set.

The first line contains an integer $$$q$$$ ($$$1 \leq q \leq 2 \cdot 10^5$$$) — the number of queries. The following $$$q$$$ lines describe the queries. An addition query of integer $$$x$$$ is given in the format + $$$x$$$ ($$$1 \leq x \leq 10^{18}$$$). It is guaranteed that $$$x$$$ was not contained in the set. A search query of $$$k\text{-mex}$$$ is given in the format ? $$$k$$$ ($$$1 \leq k \leq 10^{18}$$$). It is guaranteed that there will be at least one query of type ?.

For each query of type ? output a single integer — the $$$k\text{-mex}$$$ of the set.

NoteIn the first example:After the first and second queries, the set will contain elements $$$\{0, 1, 2\}$$$. The smallest non-negative number that is divisible by $$$1$$$ and is not contained in the set is $$$3$$$.After the fourth query, the set will contain the elements $$$\{0, 1, 2, 4\}$$$. The smallest non-negative number that is divisible by $$$2$$$ and is not contained in the set is $$$6$$$.In the second example:   Initially, the set contains only the element $$$\{0\}$$$.  After adding an integer $$$100$$$ the set contains elements $$$\{0, 100\}$$$.  $$$100\text{-mex}$$$ of the set is $$$200$$$.  After adding an integer $$$200$$$ the set contains elements $$$\{0, 100, 200\}$$$.  $$$100\text{-mex}$$$ of the set is $$$300$$$.  After adding an integer $$$50$$$ the set contains elements $$$\{0, 50, 100, 200\}$$$.  $$$50\text{-mex}$$$ of the set is $$$150$$$.

function solve() {
    var q = Number(read());
    var set = new Set();
    var lastAns = new Map();
    while(q--) {
        var _ = read().split(' ');
        var req = _[0];
        var number = BigInt(_[1]);
        if (req === '+') {
            set.add(number);
            continue;
        }
        var ans = lastAns.get(number) || number;
        while(set.has(ans)) {
            ans += number;
        }
        lastAns.set(number, ans);
        write(ans);
    }
}

function start() {
    var T = 1;
    // T = Number(read());
    for (var t = 0; t < T; t++) {
        solve();
    }
    writeAns();
}

function gcd(a, b) {
    if (b === 0) {
        return a;
    }
    return gcd(b, a % b)
}

var MEMORY;
var MEMORY_INDEX = 0;
var ANS = '';

try {
    initInput(start);
} catch (e) {
    console.log(e);
}
function readArray(f) {
    return read().split(' ').map(f);
}

function sortNumbers(a, b) {
    return a - b;
}
function sortNumbersDec(a, b) {
    return b - a;
}
var ANS;
// вывод через ANS быстрее, но ест кучу памяти.
// К тому же, максимальная длина строки - 2097151.
function write(value) {
    // console.log(value);
    ANS += value + '\n';
}
function writeAns() {
    if (ANS) {
        console.log(ANS);
    }
}
function read() {
    return MEMORY[MEMORY_INDEX++];
}
function initInput(callback) {
    var fs = require('fs');
    var isLocalStart = process.argv[2] === 'lorelvate';
    if (!isLocalStart) {
        MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
        callback();
        return;
    }
    var path = require('path');
    fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {
        if (err) {
            write(err);
            return;
        }
        MEMORY = data.split('\r\n');
        callback();
    });
}

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const q = rn();
  const set = new Set(),
        res = [];
  const cache = new Map();
  for (let i = 0; i < q; i++) {
    const s = read().split(' ');
    const num = BigInt(s[1]);
    if (s[0] === '+') set.add(num);else {
      var _cache$get;
      let i = (_cache$get = cache.get(num)) !== null && _cache$get !== void 0 ? _cache$get : num;
      for (;; i += num) {
        if (set.has(i)) continue;
        break;
      }
      cache.set(num, i);
      res.push(i);
    }
  }
  return res.join('\n');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) ; else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    }
  } catch (error) {
    console.log(error);
  }
}

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

function solve() {
    var q = Number(read());
    var set = new Set();
    var lastAns = new Map();
    while(q--) {
        var _ = read().split(' ');
        var req = _[0];
        var number = Number(_[1]);
        if (req === '+') {
            set.add(number);
            continue;
        }
        var ans = lastAns.get(number) || number;
        while(set.has(ans)) {
            ans += number;
        }
        lastAns.set(number, ans);
        write(ans);
    }
}

function start() {
    var T = 1;
    // T = Number(read());
    for (var t = 0; t < T; t++) {
        solve();
    }
    writeAns();
}

function gcd(a, b) {
    if (b === 0) {
        return a;
    }
    return gcd(b, a % b)
}

var MEMORY;
var MEMORY_INDEX = 0;
var ANS = '';

try {
    initInput(start);
} catch (e) {
    console.log(e);
}
function readArray(f) {
    return read().split(' ').map(f);
}

function sortNumbers(a, b) {
    return a - b;
}
function sortNumbersDec(a, b) {
    return b - a;
}
var ANS;
// вывод через ANS быстрее, но ест кучу памяти.
// К тому же, максимальная длина строки - 2097151.
function write(value) {
    // console.log(value);
    ANS += value + '\n';
}
function writeAns() {
    if (ANS) {
        console.log(ANS);
    }
}
function read() {
    return MEMORY[MEMORY_INDEX++];
}
function initInput(callback) {
    var fs = require('fs');
    var isLocalStart = process.argv[2] === 'lorelvate';
    if (!isLocalStart) {
        MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
        callback();
        return;
    }
    var path = require('path');
    fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {
        if (err) {
            write(err);
            return;
        }
        MEMORY = data.split('\r\n');
        callback();
    });
}


This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format:  $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$  $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).

After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).

NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let len = +readLine();
  const arr = readLine()
    .split(" ")
    .map((n) => parseInt(n));
  let t = +readLine();
  let [count8, count6, count4, count2] = [0, 0, 0, 0];

  function updateCount(target, action = "+") {
    if (action === "+") {
      if (target === 2) count2++;
      else if (target === 4) count4++;
      else if (target === 6) count6++;
      else if (target === 8) count8++;
    } else {
      if (target === 2) count2--;
      else if (target === 4) count4--;
      else if (target === 6) count6--;
      else if (target === 8) count8--;
    }
  }
  const map = arr.reduce((obj, n) => {
    if (!obj[n]) obj[n] = 1;
    else {
      obj[n]++;
      updateCount(obj[n]);
    }
    return obj;
  }, {});

  while (t--) {
    const [sign, num] = readLine().split(" ");
    if (sign === "+") {
      if (!map[num]) map[num] = 1;
      else {
        map[num]++;
        updateCount(map[num], sign);
      }
    } else {
      updateCount(map[num], sign);
      map[num]--;
    }

    if (count8 >= 1 || (count6 >= 1 && count2 >= 2) || count4 >= 2 || (count4 >= 1 && count2 >= 3)) console.log("YES");
    else console.log("NO");
  }
}

//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 N = nextInt();
  var alist = nextIntArray();
  var map = {};
  for(var i = 0; i < N; i++){
    if(map[alist[i]] == null){
      map[alist[i]] = 0;
    }
    map[alist[i]]++;
  }
  var recSet = new Set();//2
  var squSet = new Set();//4
  var keys = Object.keys(map).map(Number);
  for(var i = 0; i < keys.length; i++){
    if(map[keys[i]] >= 2){
      recSet.add(keys[i]);
    }
    if(map[keys[i]] >= 4){
      squSet.add(keys[i]);
    }
  }
  var Q = nextInt();
  var output = new Array(Q);
  for(var i = 0; i < Q; i++){
    var tmp = nextStrArray();
    var s = tmp[0];
    var x = myconv(tmp[1], 1);
    if(s == "+"){
      if(map[x] == null){
        map[x] = 0;
      }
      map[x]++;
      if(map[x] >= 2){
        recSet.add(x);
      }
      if(map[x] >= 4){
        squSet.add(x);
      }
    }else{
      map[x]--;
      if(map[x] < 4){
        squSet.delete(x);
      }
      if(map[x] < 2){
        recSet.delete(x);
      }
    }
    if(squSet.size >= 2){
      output[i] = "YES";
    }else if(squSet.size == 1){
      var tmpList = Array.from(squSet);
      var tmpCount = map[tmpList[0]] - 4;
      var tmpSet = new Set(Array.from(recSet));
      if(tmpCount < 2){
        tmpSet.delete(tmpList[0]);
      }else if(tmpCount >= 4){
        output[i] = "YES";
        continue;
      }
      if(tmpSet.size >= 2){
        output[i] = "YES";
      }else{
        output[i] = "NO";
      }
    }else{
      output[i] = "NO";
    }
  }
  myout(myconv(output, 9));
}

if (process.argv[2] === "test") {
  solve(["6", "1 1 1 2 1 1", "6", "+ 2", "+ 1", "- 1", "+ 2", "- 1", "+ 2"]);
} else {
  let i = "";
  process.stdin.on("data", (c) => (i += c));
  process.stdin.on("end", () => {
    const { EOL } = require("os");
    const lines = i.split(EOL);

    solve(lines);
  });
}

function solve(lines) {
  let totalSize = 0;
  let squareSize = 0;
  //let planks = lines[1].split(" ").map(parseInt);
  let plankMap = {};
  for (x of lines[1].split(" ")) {
    //console.log(x);
    if (plankMap[x]) {
      plankMap[x] += 1;
    } else {
      plankMap[x] = 1;
    }
    if (plankMap[x] % 2 === 0) {
      totalSize += 2;
    }
    if (plankMap[x] === 4) {
      squareSize += 1;
    }
  }

  const eventCount = parseInt(lines[2]);
  for (let x = 0; x < eventCount; ++x) {
    const [operation, value] = lines[x + 3].split(" ");
    if (operation === "+") {
      if (plankMap[value]) {
        plankMap[value] += 1;
      } else {
        plankMap[value] = 1;
      }
      if (plankMap[value] % 2 === 0) {
        totalSize += 2;
      }
      if (plankMap[value] === 4) {
        squareSize += 1;
      }
    } else {
      if (plankMap[value]) {
        plankMap[value] -= 1;
      }
      if (plankMap[value] % 2 === 1) {
        totalSize -= 2;
      }
      if (plankMap[value] === 3) {
        squareSize -= 1;
      }
    }
    console.log(squareSize > 0 && totalSize >= 8 ? "YES" : "NO");
  }
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main(){
    let n = parseInt(readline());
    let a = readline().split(' ');
    let map = new Array(100000 + 1);
    map.fill(0);
    let count = {'4': 0, '2': 0};
    for(let i = 0; i < a.length; i++){
        let index = parseInt(a[i]);
        if(map[index]){
            map[index] += 1;
            if(map[index] % 4 === 0)
                count[4] += 1;

            if(map[index] % 2 === 0)
                count[2] += 1;
        }
        else
            map[index] = 1;
    }

    let o = parseInt(readline());
    for(let i = 0; i < o; i++){
        let x = readline().split(' ');
        if(x[0] === '+'){
            map[parseInt(x[1])] += 1;
            if(map[parseInt(x[1])] % 4 === 0)
                count[4]++;

            if(map[parseInt(x[1])] % 2 === 0)
                count[2]++;
        }else{
            let f1 = map[parseInt(x[1])] % 4 === 0;
            let f2 = map[parseInt(x[1])] % 2 === 0;
            map[parseInt(x[1])] -= 1;
            if(f1 && map[parseInt(x[1])] % 4 !== 0)
                count[4]--;

            if(f2 && map[parseInt(x[1])] % 2 !== 0)
                count[2]--;
        }

        if(count[4] >= 2){
            console.log('yes');
        }else if(count[4] >= 1 && count[2]-(2*count[4]) >= 2){
            console.log('yes');
        }else{
            console.log('no');
        }
    }
}

//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 N = nextInt();
  var alist = nextIntArray();
  var map = {};
  for(var i = 0; i < N; i++){
    if(map[alist[i]] == null){
      map[alist[i]] = 0;
    }
    map[alist[i]]++;
  }
  var recSet = new Set();//4
  var squSet = new Set();//2
  var keys = Object.keys(map).map(Number);
  for(var i = 0; i < keys.length; i++){
    if(map[keys[i]] >= 2){
      recSet.add(keys[i]);
    }
    if(map[keys[i]] >= 4){
      squSet.add(keys[i]);
    }
  }
  myerr(recSet);
  myerr(squSet);
  var Q = nextInt();
  var output = new Array(Q);
  for(var i = 0; i < Q; i++){
    var tmp = nextStrArray();
    var s = tmp[0];
    var x = myconv(tmp[1], 1);
    if(s == "+"){
      if(map[x] == null){
        map[x] = 0;
      }
      map[x]++;
      if(map[x] >= 2){
        recSet.add(x);
      }
      if(map[x] >= 4){
        squSet.add(x);
      }
    }else{
      map[x]--;
      if(map[x] < 4){
        squSet.delete(x);
      }
      if(map[x] < 2){
        recSet.delete(x);
      }
    }
    if(squSet.size >= 2){
      output[i] = "YES";
    }else if(squSet.size == 1){
      var tmpList = Array.from(squSet);
      var tmpCount = map[tmpList[0]] - 4;
      var tmpSet = recSet;
      if(tmpCount < 2){
        tmpSet.delete(tmpList[0]);
      }else if(map[tmpList[0]] - 4 >= 4){
        output[i] = "YES";
        continue;
      }
      if(tmpSet.size >= 2){
        output[i] = "YES";
      }else{
        output[i] = "NO";
      }
    }else{
      output[i] = "NO";
    }
    myerr(recSet);
    myerr(squSet);
  }
  myout(myconv(output, 9));
}

//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 N = nextInt();
  var alist = nextIntArray();
  var map = {};
  for(var i = 0; i < N; i++){
    if(map[alist[i]] == null){
      map[alist[i]] = 0;
    }
    map[alist[i]]++;
  }
  var recSet = new Set();//4
  var squSet = new Set();//2
  var keys = Object.keys(map).map(Number);
  for(var i = 0; i < keys.length; i++){
    if(map[keys[i]] >= 2){
      recSet.add(keys[i]);
    }
    if(map[keys[i]] >= 4){
      squSet.add(keys[i]);
    }
  }
  myerr(recSet);
  myerr(squSet);
  var Q = nextInt();
  var output = new Array(Q);
  for(var i = 0; i < Q; i++){
    var tmp = nextStrArray();
    var s = tmp[0];
    var x = myconv(tmp[1], 1);
    if(s == "+"){
      map[x]++;
      if(map[x] >= 2){
        recSet.add(x);
      }
      if(map[x] >= 4){
        squSet.add(x);
      }
    }else{
      map[x]--;
      if(map[x] < 4){
        squSet.delete(x);
      }
      if(map[x] < 2){
        recSet.delete(x);
      }
    }
    if(squSet.size >= 2){
      output[i] = "YES";
    }else if(squSet.size == 1){
      var tmpList = Array.from(squSet);
      var tmpCount = map[tmpList[0]] - 4;
      var tmpSet = recSet;
      if(tmpCount < 2){
        tmpSet.delete(tmpList[0]);
      }
      if(tmpSet.size >= 2){
        output[i] = "YES";
      }else{
        output[i] = "NO";
      }
    }else{
      output[i] = "NO";
    }
    myerr(recSet);
    myerr(squSet);
  }
  myout(myconv(output, 9));
}

//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 N = nextInt();
  var alist = nextIntArray();
  var map = {};
  for(var i = 0; i < N; i++){
    if(map[alist[i]] == null){
      map[alist[i]] = 0;
    }
    map[alist[i]]++;
  }
  var recSet = new Set();//4
  var squSet = new Set();//2
  var keys = Object.keys(map).map(Number);
  for(var i = 0; i < keys.length; i++){
    if(map[keys[i]] >= 2){
      recSet.add(keys[i]);
    }
    if(map[keys[i]] >= 4){
      recSet.delete(keys[i]);
      squSet.add(keys[i]);
    }
    if(map[keys[i]] >= 6){
      recSet.add(keys[i]);
      squSet.add(keys[i]);
    }
  }
  myerr(recSet);
  myerr(squSet);
  var Q = nextInt();
  var output = new Array(Q);
  for(var i = 0; i < Q; i++){
    var tmp = nextStrArray();
    var s = tmp[0];
    var x = myconv(tmp[1], 1);
    if(s == "+"){
      map[x]++;
      if(map[x] >= 2){
        recSet.add(x);
      }
      if(map[x] >= 4){
        recSet.delete(x);
        squSet.add(x);
      }
      if(map[x] >= 6){
        recSet.add(x);
        squSet.add(x);
      }
      if((recSet.size >= 2 && squSet.size >= 1) || squSet.size >= 2){
        output[i] = "YES";
      }else{
        output[i] = "NO";
      }
    }else{
      map[x]--;
      if(map[x] < 6){
        recSet.delete(x);
      }
      if(map[x] < 4){
        recSet.add(x);
        squSet.delete(x);
      }
      if(map[x] < 2){
        recSet.delete(x);
      }

      if((recSet.size >= 2 && squSet.size >= 1) || squSet.size >= 2){
        output[i] = "YES";
      }else{
        output[i] = "NO";
      }
    }
    myerr(recSet);
    myerr(squSet);
  }
  myout(myconv(output, 9));
}

//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 N = nextInt();
  var alist = nextIntArray();
  var map = {};
  for(var i = 0; i < N; i++){
    if(map[alist[i]] == null){
      map[alist[i]] = 0;
    }
    map[alist[i]]++;
  }
  var recSet = new Set();//4
  var squSet = new Set();//2
  var keys = Object.keys(map).map(Number);
  for(var i = 0; i < keys.length; i++){
    if(map[keys[i]] >= 2){
      recSet.add(keys[i]);
    }
    if(map[keys[i]] >= 4){
      squSet.add(keys[i]);
    }
  }
  myerr(recSet);
  myerr(squSet);
  var Q = nextInt();
  var output = new Array(Q);
  for(var i = 0; i < Q; i++){
    var tmp = nextStrArray();
    var s = tmp[0];
    var x = myconv(tmp[1], 1);
    if(s == "+"){
      map[x]++;
      if(map[x] >= 2){
        recSet.add(x);
      }
      if(map[x] >= 4){
        squSet.add(x);
      }
    }else{
      map[x]--;
      if(map[x] < 4){
        squSet.delete(x);
      }
      if(map[x] < 2){
        recSet.delete(x);
      }
    }
    if(squSet.size >= 2){
      output[i] = "YES";
    }else if(squSet.size == 1){
      var tmpList = Array.from(squSet);
      var tmpCount = map[tmpList[0]] - 4;
      var tmpSet = recSet;
      if(tmpCount < 2){
        tmpSet.delete(tmpList[0]);
      }else if(map[tmpList[0]] - 4 >= 4){
        output[i] = "YES";
        continue;
      }
      if(tmpSet.size >= 2){
        output[i] = "YES";
      }else{
        output[i] = "NO";
      }
    }else{
      output[i] = "NO";
    }
    myerr(recSet);
    myerr(squSet);
  }
  myout(myconv(output, 9));
}

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 a = readline().split(' ');
    let map = new Array(100000 + 1);
    let count = {'4': 0, '2': 0};
    for(let i = 0; i < a.length; i++){
        let index = parseInt(a[i]);
        if(map[index]){
            map[index] += 1;
            if(map[index] % 4 === 0)
                count[4] += 1;

            if(map[index] % 2 === 0)
                count[2] += 1;
        }
        else
            map[index] = 1;
    }

    let o = parseInt(readline());
    for(let i = 0; i < o; i++){
        let x = readline().split(' ');
        if(x[0] === '+'){
            map[parseInt(x[1])] += 1;
            if(map[parseInt(x[1])] % 4 === 0)
                count[4]++;

            if(map[parseInt(x[1])] % 2 === 0)
                count[2]++;
        }else{
            let f1 = map[parseInt(x[1])] % 4 === 0;
            let f2 = map[parseInt(x[1])] % 2 === 0;
            map[parseInt(x[1])] -= 1;
            if(f1 && map[parseInt(x[1])] % 4 !== 0)
                count[4]--;

            if(f2 && map[parseInt(x[1])] % 2 !== 0)
                count[2]--;
        }

        if(count[4] >= 2){
            console.log('yes');
        }else if(count[4] >= 1 && count[2]-(2*count[4]) >= 2){
            console.log('yes');
        }else{
            console.log('no');
        }
    }
}