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


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

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

//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)

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]))

}

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,
  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)


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;

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

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


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

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


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

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

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

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


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

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

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

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


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

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


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

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

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


function solve() {
    var letters = initValues();
    var [n, k] = readArray(Number);
    var s = read();
    var lettersCounter = new Map();
    letters.forEach((letter) => lettersCounter.set(letter, 0));
    for (var i = 0; i < n; i++) {
        lettersCounter.set(s[i], lettersCounter.get(s[i]) + 1);
    }
    const booksCounter = n / k;
    var ans = '';
    for (var i = 0; i < k; i++) {
        var MEXIndex = 0;
        for (MEXIndex = 0; MEXIndex < booksCounter; MEXIndex++) {
            var letter = letters[MEXIndex];
            if (lettersCounter.get(letter) === 0) {
                break;
            }
            lettersCounter.set(letter, lettersCounter.get(letter) - 1);
        }
        ans += letters[MEXIndex];
    }
    write(ans);
}

var initialValues;
function initValues() {
    if (initialValues) {
        return initialValues;
    }
    var letters = [];
    var aCode = 'a'.charCodeAt(0);
    var zCode = 'z'.charCodeAt(0);
    for (var i = aCode; i <= zCode; i++) {
        letters.push(String.fromCharCode(i));
    }
    initialValues = letters;
    return letters;
}

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

try {
    initInput(start);
} catch (e) {
    console.log(e);
}

var MEMORY;
var MEMORY_INDEX;
function readArray(f) {
    return read().split(' ').map(f);
}
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');
    ANS = '';
    MEMORY_INDEX = 0;
    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();
    });
}

var readline = require('readline');
var inputString = [], currentLine = 0;
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var rl = readline.createInterface(process.stdin);
rl.on('line', line => { inputString.push(line) });
process.stdin.on('end', () => {  main()  });

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

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        const n_k = readLine().split(' ').map(p => +p);
        const str = readLine();
        let result = myFunc(n_k[0], n_k[1], str);
        console.log(result);
    }
}

function myFunc(n, k, s){
    let sub = n/k;
    let map = [];
    const alfabeto = 'abcdefghijklmnopqrstuvwxyz';
    let resp = '';

    function _num(s){
        return s.charCodeAt(0)-97;
    }

    for(let i = 0; i < n; i++){
        if(map[_num(s[i])] == undefined) map[_num(s[i])] = 1;
        else map[_num(s[i])]++;
    }

    for(let j = 0; j < k; j++){
        for(let i = 0; i < sub; i++){
            if(map[i]){
                map[i]--;
                if(i == sub-1) resp += alfabeto[sub];
            }
            else{
                resp+= alfabeto[i];
                break;
            }

        }
    }
    return resp;

}

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        k = rn(),
        s = read();
  const chs = s.split('').sort((a, b) => a === b ? 0 : a < b ? -1 : 1);
  const res = [];
  const vis = new Array(n);
  for (let i = 0; i < k; i++) {
    let cnt = 0;
    let pre = 96;
    for (let j = 0; j < n && cnt < n / k; j++) {
      const num = chs[j].charCodeAt(0);
      if (vis[j] || num === pre) continue;
      vis[j] = 1;
      cnt++;
      if (num === pre + 1) {
        pre = num;
      } else {
        if (res[i] === undefined) res[i] = pre + 1;
      }
    }
    if (res[i] === undefined) res[i] = pre + 1;
  }
  return res.map(num => String.fromCharCode(num)).join('');
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    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) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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