jiahuimbzuai/CoQuIR huggingface dataset:
//  [c]
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef long long int value_type; /* ソートするキーの型 */
typedef long long int lli;

value_type med3(value_type x, value_type y, value_type z)
/* x, y, z の中間値を返す */
{
  if (x < y)
    if (y < z)
      return y;
    else if (z < x)
      return x;
    else
      return z;
  else if (z < y)
    return y;
  else if (x < z)
    return x;
  else
    return z;
}

void quicksort(value_type a[], int left, int right)
/* クイックソート
 * a     : ソートする配列
 * left  : ソートするデータの開始位置
 * right : ソートするデータの終了位置
 */
{
  if (left < right) {
    int i = left, j = right;
    value_type tmp,
        pivot = med3(a[i], a[i + (j - i) / 2],
                     a[j]); /* (i+j)/2ではオーバーフローしてしまう */
    while (1) { /* a[] を pivot 以上と以下の集まりに分割する */
      while (a[i] < pivot) i++; /* a[i] >= pivot となる位置を検索 */
      while (pivot < a[j]) j--; /* a[j] <= pivot となる位置を検索 */
      if (i >= j) break;
      tmp = a[i];
      a[i] = a[j];
      a[j] = tmp; /* a[i],a[j] を交換 */
      i++;
      j--;
    }
    quicksort(a, left, i - 1);  /* 分割した左を再帰的にソート */
    quicksort(a, j + 1, right); /* 分割した右を再帰的にソート */
  }
}

int main() {
  int i, j;
  lli* d = (lli*)malloc(sizeof(lli) * 200001);
  int* dnum = (int*)malloc(sizeof(int) * 200001);
  lli* t = (lli*)malloc(sizeof(lli) * 200001);
  int* tnum = (int*)malloc(sizeof(int) * 200001);

  int N, M;
  lli temp;
  scanf("%d", &N);
  for (i = 0; i < N; i++) {
    scanf("%lld", &d[i]);
  }
  scanf("%d", &M);
  /*
  if(M>N) {
    printf("No");
  }
  */
  for (i = 0; i < M; i++) {
    scanf("%lld", &t[i]);
  }

  quicksort(d, 0, N - 1);
  quicksort(t, 0, M - 1);
  /*
  printf("N: \n");
  for (i = 0; i < N; i++) {
    printf("%lld\n", d[i]);
  }
  printf("M; \n");
  for (i = 0; i < M; i++) {
    printf("%lld\n", t[i]);
  }
  */
  int flag = 0;
  int nd_flag = 0;
  int cur = 0;
  for (i = 0; i < M; i++) {
    //printf("Go\n");
    flag = 0;
    for (j = cur; j < N; j++) {
      if (t[i] == d[j]) {
        cur = j + 1;
        d[j] = 0;
        flag = 1;
        //printf("t: %d, d: %d\n", t[i], d[j]);
        break;
      } else if (d[j] > t[i]) {
        break;
      }
    }
    if (flag == 0) {
      nd_flag = 1;
      break;
    }
  }
  /*
    for (i = 0; i < M; i++) {
      flag = 0;
      for (j = 0; j < N; j++) {
        if (t[i] == d[j]) {
          flag = 1;
          d[j] = 0;
          break;
        }
      }
      if (flag == 0) {
        nd_flag = 1;
        break;
      }
    }
    */

  if (nd_flag != 1) {
    printf("YES");
  } else {
    printf("NO");
  }
  return 0;
}
//  [c]
#include <stdio.h>
#define swap(type, x, y)  do{ type t = x; x = y; y = t; }while(0)

void quick(int array[], int left, int right){
  int pl = left, pr = right, x = array[(left + right) / 2];
  do{
    while(array[pl] < x)  pl++;
    while(array[pr] > x)  pr--;
    if(pl <= pr){
      swap(int, array[pl], array[pr]);
      pl++, pr--;
    }
  }while(pl <= pr);
  if(pl < right)  quick(array, pl, right);
  if(pr > left)  quick(array, left, pr);
}

int main(){
  int n, m, d[200005], t[200005];
  scanf("%d", &n);
  for(int i=0; i<n; i++)  scanf("%d", d+i);
  quick(d, 0, n-1);
  scanf("%d", &m);
  for(int i=0; i<m; i++)  scanf("%d", t+i);
  quick(t, 0, m-1);
    
  int flag = 1, start = 0;
  for(int i=0; i<m; i++){
    int notFound = 1;
    for(int j=start; (d[j]<=t[i] && j<n); j++)
      if(d[j] == t[i]){
	notFound = 0;
	start = j + 1;
	break;
      }
    if(notFound){
      flag = 0;
      break;
    }
  }
  if(flag)  printf("YES\n");
  else  printf("NO\n");
  return 0;
}
//  [c]
#include<stdio.h>

void quick(int a[],int left,int right);

int main(){
  int N,ans=1;
  scanf("%d",&N);
  int D[N];
  for (int i = 0; i < N; i++){ scanf("%d",&D[i]);}
  int M;
  scanf("%d",&M);
  int T[M];
  for (int i = 0; i < M; i++){ scanf("%d",&T[i]);}

  quick(D,0,N-1);
  quick(T,0,M-1);

  int i=0,j=0,k=0,count_T=0,count_D=0;
  while (i<M&&N>=M)
  {
    while (T[i]==T[k]&&k<M){ count_T++; k++;}
    while (T[i]!=D[j]&&j<N){ j++; }
    while (T[i]==D[j]&&j<N){ count_D++; j++; }
    if(count_D<count_T){
      ans=1;
      break;
    }else{
      ans=0;
    }
    
    i=k;
    count_D=0;
    count_T=0;
  }

  ans > 0 ? puts("NO") : puts("YES");
  
  return 0;
}

void quick(int a[],int left,int right)
{
    int s,t,i,j;

    if (left<right){
        s=a[left];            
        i=left; j=right+1;      
        while (1){              
            while (a[++i]<s);
            while (a[--j]>s);
            if (i>=j) break;
            t=a[i]; a[i]=a[j]; a[j]=t;
        }
        a[left]=a[j]; a[j]=s;

        quick(a,left,j-1);
        quick(a,j+1,right);
    }
}
//  [c]
#include<stdio.h>

void merge(long s[], int low, int middle, int high)
{
 int i;
 int j;
 long arr1[200005];
 long arr2[200005];
 int ind1=0;
 int ind2=0;

 for (i=low;i<=middle; i++) arr1[i-low]=s[i];
 for (i=middle+1; i<=high; i++) arr2[i-middle-1]=s[i];

 i=low;
 
 for(;;)
 {  
   if(arr1[ind1]<=arr2[ind2])
   {
     s[i++]=arr1[ind1++];
   }else{
     s[i++]=arr2[ind2++];
   }
   if(ind1>middle-low) break;
   if(ind2>high-middle-1) break;
 }
 for(j=ind1;j<=middle-low;j++) s[i++]=arr1[j];
 for(j=ind2;j<=high-middle-1;j++) s[i++]=arr2[j];

}


void mergesort(long s[], int low, int high)
{
 int middle;
 if(low<high)
 {
  middle=(low+high)/2;
  mergesort(s,low,middle);
  mergesort(s,middle+1,high);
  merge(s,low,middle,high);
 }
}

int main()
{
 int N;
 long D[200005];
 int M;
 long T[200005];
 int i;
 int start=0;
 int allfound=1;
 int found[200005];
 int j;

 scanf("%d",&N);
 for(i=0;i<N;i++) scanf("%ld",&D[i]);
 scanf("%d",&M);
 for(i=0;i<M;i++) scanf("%ld",&T[i]);
 for(i=0;i<M;i++) found[i]=0;

 mergesort(D,0,N-1);
 mergesort(T,0,M-1 );

 for(i=0;i<N;i++)
 {
  for(j=start;j<M;j++)
  {
   if(D[i]==T[j])
   {
    start=j+1;
    found[j]=1;
    break;
   }
   if(D[i]>T[j]) break;
  }
 }

 for(i=0;i<M;i++) 
 {
  if(found[i]!=1) 
  {
   allfound=0;  
   break;
  }
 }

 if(allfound==1)
 {
  printf("YES\n");
 }else{
  printf("NO\n");
 }

 return 0;
}
//  [c]
#include<stdio.h>
int R=1,C=1,H[2000010],N[2000010];
//評価関数（いまはMIN）
int hyouka(int a,int b){
  if(C<b)return 1;
  if(C<a||b==0)return 0;
  return N[H[a]]<N[H[b]]?1:0;
}
//挿入関数
void hin(int a){
  int i=C++;
  for(N[H[0]=R]=a;hyouka(0,i/2);i/=2)H[i]=H[i/2];
  H[i]=R++;
}
//取り出す関数
int hout(){
  int rt=H[1],i,j=2,k=H[--C];
  for(i=1;hyouka(i,C);i=j)H[i]=H[j=i*2+1-hyouka(i*2,i*2+1)];
  H[j/2]=k;
  return rt;
}
int main(){
  int n,m,a,d[200010],i,r=0;
  scanf("%d",&n);
  for(i=0;i<n;i++){
    scanf("%d",&a);
    hin(a);
  }
  for(i=0;i<n;i++)d[i]=N[hout()];
  R=C=1;
  scanf("%d",&m);
  for(i=0;i<m;i++){
    scanf("%d",&a);
    hin(a);
  }
  d[n]=-1;
  //for(i=0;i<=n;i++)printf("%d\n",d[i]);
  for(i=0;i<m;i++){
    a=N[hout()];//printf("%d\n",a);
    while(d[r]<a&&r<n)r++;
    if(d[r++]-a)goto END;
  }
  printf("YES\n");
  return 0;
 END:;
  printf("NO\n");
  return 0;
}
//  [javascript]
"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let n = nextInt()
    let d = nextIntArray()
    let m = nextInt()
    let t = nextIntArray()
    let map = {}
    for(let i = 0; i< d.length; i++){
        if(!map[d[i]]) map[d[i]] = 1
        else map[d[i]]++
    }
    for(let i = 0; i<t.length; i++){
        if(!map[t[i]]){
            console.log("NO")
            return
        }
        map[t[i]]--
        if(map[t[i]] < 0){
            console.log("NO")
            return
        }
    }
    console.log("YES")

}
Main()
//  [javascript]
console.log((args=>{
  const [[N],D,[M],T] = args.trim().split('\n').map(r=>r.split(' ').map(v=>v|0));
  D.sort((a,b)=>a-b);
  T.sort((a,b)=>a-b);
  let j = -1;
  Q: for ( let i = 0; i < M; i++ ) {
    while ( ++j < N ) {
      if ( D[j] > T[i] ) return 'NO';
      if ( D[j] === T[i] ) continue Q;
    }
    return 'NO';
  }
  return 'YES';
})(require('fs').readFileSync('/dev/stdin', 'utf8')));
//  [javascript]
function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){console.log(t);}//standard output
function myerr(t){console.error(t);}//standard error
//[no]param
//0:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));}}
function Main(input) {
  input = myconv(input,3);
  var N = myconv(input[0],1);
  var dlist = myconv(input[1],4);
  var dset = {};
  var M = myconv(input[2],1);
  var tlist = myconv(input[3],4);
  for(var i = 0; i < N; i++){
    if(dset[dlist[i]] == null){
       dset[dlist[i]] = 1;
    }else{
      dset[dlist[i]]++;
    }
  }
  for(var i = 0; i < M; i++){
    if(dset[tlist[i]] != null && dset[tlist[i]] > 0){
       dset[tlist[i]]--;
    }else{
      myout("NO");
      return;
    }
  }
  myout("YES");
}
Main(myin());
//  [javascript]
process.stdin.resume();
process.stdin.setEncoding('utf8');

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

process.stdin.on('end', function() {
    Main(g_input.split(/\r?\n/));
});

function Main(input) {

    var n = parseInt(input[0], 10);
    var dstr = input[1].split(' ');
    var d = new Array(n);
    for (var i = 0; i < n; i++) {
        d[i] = parseInt(dstr[i], 10);
    }
    var m = parseInt(input[2], 10);
    var tstr = input[3].split(' ');
    var t = new Array(m);
    for (var i = 0; i < m; i++) {
        t[i] = parseInt(tstr[i], 10);
    }

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

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

    for (var i = 0, j = 0; i < m; i++) {
        var found = false;
        for (; j < n; j++) {
            if (t[i] == d[j]) {
                found = true;
                j++;
                break;
            }
        }
        if (!found) {
            break;
        }
    }

    if (found) {
        console.log('YES');
    }
    else {
        console.log('NO');
    }

    return 0;
}
//  [javascript]
module.exports=function(e){var r={};function n(t){if(r[t])return r[t].exports;var o=r[t]={i:t,l:!1,exports:{}};return e[t].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=r,n.d=function(e,r,t){n.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,r){if(1&r&&(e=n(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(n.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)n.d(t,o,function(r){return e[r]}.bind(null,o));return t},n.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(r,"a",r),r},n.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},n.p="",n(n.s=0)}([function(e,r,n){n(1)(n(2).readFileSync("/dev/stdin","UTF-8"))},function(e,r){e.exports=function(e){var r=e.split("\n"),n=(Number(r[0]),{});r[1].split(" ").map(function(e){var r=Number(e);n[r]||(n[r]=0),n[r]+=1}),Number(r[2]);var t={};for(var o in r[3].split(" ").map(function(e){var r=Number(e);t[r]||(t[r]=0),t[r]+=1}),t)if(!n[o]||t[o]>n[o])return void console.log("NO");console.log("YES")}},function(e,r){e.exports=require("fs")}]);
//  [javascript]

// input に入力データが全部入る
function Main(input) {
    // 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split("\n");
    tmp1 = input[1].split(" ");
    tmp2 = input[3].split(" ");
    
    // 文字列から10進数に変換するときはparseIntを使います
    var N = parseInt(input[0], 10);
    var D = new Array();
    for(var i = 0; i<N;i++){
        var tmp = parseInt(tmp1[i],10);
        D.push(tmp);
    }
/*
    for(var i = 0; i<N;i++){
        console.log(D.join());
    }
*/
    var M = parseInt(input[2], 10);
    var T = new Array();
    for(var i=0;i<M;i++){
        tmp = parseInt(tmp2[i], 10);
        T.push(tmp);
    }
    
    var hash = new Object();
    for(var i=0;i<N;i++){
        hash[D[i]] = 0;
    }
    for(var i=0;i<N;i++){
        hash[D[i]]++;
    }
/*    
    for (var key in hash) {
        document.write (key + "の値：" + hash[key] + "<br>");
    }
*/
    var flag = true;
    for(var i=0;i<M;i++){
        if(!hash[T[i]]){
            flag=false;
            break;
        }
        if(hash[T[i]]==0){
            flag = false;
            break;
        }
        else{
            hash[T[i]]--;
        }
    }

    // 出力
    if(flag){
        console.log("YES");
    }
    else console.log("NO");
}

// "実行する"ボタンを押した時に実行される関数 (デバッグ用)
function debug(){
	var input = document.getElementById("input").value;
	Main(input);
}

//* この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	// Code for B - Problem Set
	var N int
	fmt.Scan(&N)

	sc.Split(bufio.ScanWords)
	var temp int
	D := make(map[int]int, N)
	for i := 0; i < N; i++ {
		temp = nextInt()
		D[temp]++
	}

	var M int
	M = nextInt()

	var T int
	for i := 0; i < M; i++ {
		T = nextInt()
		D[T]--
	}

	for _, v := range D {
		if v < 0 {
			fmt.Println("NO")
			return
		}
	}

	fmt.Println("YES")
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"reflect"
	"strconv"
)

const (
	maxBufSize = 1024 * 1024
)

var (
	sc = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, 1)
		sc.Buffer(buf, maxBufSize)
		sc.Split(bufio.ScanWords)
		return sc
	}()
	out = bufio.NewWriter(os.Stdout)
)

const yes = "YES"
const no = "NO"

func solve(n int64, ds []int64, m int64, ts []int64) bool {
	dMap := make(map[int64]int64, n)
	for _, d := range ds {
		dValue, exists := dMap[d]
		if exists {
			dMap[d] = dValue + 1
		} else {
			dMap[d] = 1
		}
	}
	for _, t := range ts {
		dValue, exists := dMap[t]
		if !exists || dValue == 0 {
			return false
		}
		dMap[t] = dValue - 1
	}
	return true
}

func main() {
	defer out.Flush()

	n := nextInt()
	ds := nextInts(n)
	m := nextInt()
	ts := nextInts(m)
	if solve(n, ds, m, ts) {
		fmt.Fprintln(out, yes)
	} else {
		fmt.Fprintln(out, no)
	}
}

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextStringAsBytes() []byte {
	sc.Scan()
	return []byte(sc.Text())
}

func nextInt() int64 {
	a, _ := strconv.ParseInt(next(), 10, 64)
	return a
}

func nextFloat() float64 {
	a, _ := strconv.ParseFloat(next(), 64)
	return a
}

func nextInts(n int64) []int64 {
	ret := make([]int64, n)
	for i := int64(0); i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}

func nextFloats(n int64) []float64 {
	ret := make([]float64, n)
	for i := int64(0); i < n; i++ {
		ret[i] = nextFloat()
	}
	return ret
}
func nextStrings(n int64) []string {
	ret := make([]string, n)
	for i := int64(0); i < n; i++ {
		ret[i] = next()
	}
	return ret
}

func containStr(arr []string, target string) bool {
	for _, v := range arr {
		if v == target {
			return true
		}
	}
	return false
}

func PrintOut(src interface{}, joinner string) {
	switch reflect.TypeOf(src).Kind() {
	case reflect.Slice:
		s := reflect.ValueOf(src)
		for idx := 0; idx < s.Len(); idx++ {
			fmt.Fprintf(out, "%v", s.Index(idx))
			if idx < s.Len()-1 {
				fmt.Fprintf(out, "%s", joinner)
			} else {
				fmt.Fprintln(out)
			}
		}
	default:
		fmt.Fprintln(out, "orz")
	}
}

// mapからkeysとvaluesを返す
func splitKeyValue(m map[interface{}]interface{}) (keys, values []interface{}) {
	switch reflect.TypeOf(m).Kind() {
	case reflect.Map:
		s := reflect.ValueOf(m)
		for _, v := range s.MapKeys() {
			keys = append(keys, v)
			values = append(values, s.MapIndex(v))
		}
	default:
		fmt.Fprintln(out, "orz")
	}
	return
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main(){
	r := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	var N, M int
	mp1 := make(map[int]int)
	fmt.Fscan(r, &N)
	for i := 0; i < N; i++{
		var D int
		fmt.Fscan(r, &D)
		mp1[D]++
	}
	fmt.Fscan(r, &M)
	var ans string = "YES"
	for i:=0; i < M; i++{
		var T int
		fmt.Fscan(r, &T)
		v, ok := mp1[T]
		if(v <= 0 || !ok){
			ans = "NO"
		}
		mp1[T]--
	}
	fmt.Println(ans)
}
//  [ruby]
n = gets.chomp.to_i
d = gets.chomp.split(" ").map(&:to_i)
m = gets.chomp.to_i
t = gets.chomp.split(" ").map(&:to_i)
count = 1
hash = Hash.new(0)
d.each do |i| 
    hash[i] += 1
end
t.each do |j|
    hash[j] -= 1
    count -= 1 if hash[j] < 0
end

puts count == 1 ? "YES" : "NO"
//  [ruby]
#input of int(split by space)
def get_i()
  return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
  return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
  return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
  return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
  return bool ? y : n 
end
#create of array
def array(size1,init=nil,size2=-1)
  if size2==-1
      return Array.new(size1){init}
  else
      return Array.new(size2){Array.new(size1){init}}
  end
end

def max(a,b)
    return a>b ? a : b
end

def min(a,b)
    return a>b ? b : a
end

INF=Float::INFINITY

N=gets.to_i
D=get_i
kind=Hash.new(0)
D.each do|d|
    kind[d]+=1
end
M=gets.to_i
T=get_i
T.each do|t|
    if kind[t]>0
        kind[t]-=1
    else
        puts "NO"
        exit
    end
end
puts "YES"
//  [ruby]
n = gets.to_i
d = gets.chomp.split.map(&:to_i)
m = gets.to_i
t = gets.chomp.split.map(&:to_i)

hs = Hash.new(0)
n.times do |i|
  hs[d[i]] += 1
end

res = true
m.times do |i|
  hs[t[i]] -= 1
  if hs[t[i]] < 0
    res = false
    break
  end
end

puts (res)? "YES" : "NO"
//  [ruby]
N,D,M,T=$<.map{|s|s.split.sort};puts T.all?{|t|t==N||redo if N=D.shift}?:YES: :NO
//  [ruby]
#!/usr/bin/env ruby

n = gets.to_i
d = gets.split.map(&:to_i).group_by(&:itself).map { |a, b| [a, b.size] }.to_h
m = gets.to_i
t = gets.split.map(&:to_i).group_by(&:itself).map { |a, b| [a, b.size] }.to_h

if t.all? { |a, b| !d[a].nil? && d[a] >= b }
  puts 'YES'
else
  puts 'NO'
end
//  [ruby]
N,*t=`dd`.split.map &:to_i;d=t.shift N;M,*t=t
t,d=[t,d].map{|e|h=Hash.new 0;e.map{|f|h[f]+=1};h}
puts t.all?{|k,v|d[k]>=v}?:YES: :NO
//  [rust]
use std::io::*;

fn main() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.trim().split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let d: Vec<usize> = (0..n)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();
    let m: usize = itr.next().unwrap().parse().unwrap();
    let t: Vec<usize> = (0..m)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();

    let mut mp = std::collections::HashMap::new();
    for i in 0..n {
        let p = mp.entry(d[i]).or_insert(0);
        *p += 1;
    }
    for i in 0..m {
        let p = mp.entry(t[i]).or_insert(0);
        if *p > 0 {
            *p -= 1;
        } else {
            println!("NO");
            return;
        }
    }
    println!("YES");
}
//  [rust]
use whiteread::parse_line;

fn main() {
    let _n: usize = parse_line().unwrap();
    let mut d: Vec<u32> = parse_line().unwrap();
    let _m: usize = parse_line().unwrap();
    let mut t: Vec<u32> = parse_line().unwrap();
    let mut ans = "YES";

  	d.sort();
  	t.sort();
    for &ti in &t {
        if let Some(idx) = d.iter().position(|&x| x == ti) {
            d.remove(idx);
        } else {
            ans = "NO";
            break;
        }
    }
    println!("{}", ans);
}
//  [rust]
#![allow(unused, non_snake_case, dead_code, non_upper_case_globals)]
use {
    proconio::{marker::*, *},
    std::{cmp::*, collections::*, mem::*},
};

fn main() {
    input! {
        n:usize,
       mut d:[i64;n],
        m:usize,
        mut t:[i64;m],
    }

    d.sort();
    t.sort();

    let mut mm = BTreeMap::new();
    for &x in t.iter() {
        *mm.entry(x).or_insert(0) += 1;
    }

    for &x in d.iter() {
        *mm.entry(x).or_insert(0) -= 1;
    }
    let mut ans = true;
    dbg!(&mm);
    for (_, v) in mm {
        if v > 0 {
            ans = false;
            break;
        }
    }
    if ans {
        println!("YES");
    } else {
        println!("NO");
    }
}
//  [rust]
use std::collections::HashMap;
use std::io::*;
use std::str::*;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let s = stdin
        .bytes()
        .map(|c| c.unwrap() as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect::<String>();
    s.parse::<T>().ok().unwrap()
}

fn usize() -> usize {
    read()
}

fn vec_usize(n: usize) -> Vec<usize> {
    let mut vec = Vec::new();
    for _ in 0..n {
        vec.push(usize())
    }
    vec
}

fn main() {
    let n = usize();
    let d_vec = vec_usize(n);
    let m = usize();
    let t_vec = vec_usize(m);
    let mut ds = HashMap::new();
    let mut ts = HashMap::new();
    for i in 0..n {
        *ds.entry(d_vec[i] + 1).or_insert(0) += 1;
    }
    for i in 0..m {
        *ts.entry(t_vec[i] + 1).or_insert(0) += 1;
    }
    for level in ts.keys() {
        if ts[level] > *ds.get(level).unwrap_or(&0) {
            println!("{}", "NO");
            return;
        }
    }
    println!("{}", "YES");
}
//  [swift]
readLine()!
var D = [Int: Int]()
readLine()!.characters.split(" ").map({Int(String($0))!}).forEach {
  D[$0] = (D[$0] ?? 0) + 1
}
readLine()!
var ans = "YES"
readLine()!.characters.split(" ").map({Int(String($0))!}).forEach {
  if (D[$0] ?? 0) > 0 {
    D[$0] = (D[$0] ?? 0) - 1
  } else {
    ans = "NO"
  }
}
print(ans)
//  [typescript]
import * as fs from "fs";

let input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
const n = +input[0];
const d = input[1].split(" ").map((x: string): number => +x);
const m = +input[2];
const t = input[3].split(" ").map((x: string): number => +x);

const compare = (a: number, b: number) => a - b;

d.sort(compare);
t.sort(compare);

let ii = 0;
for (let i = 0; i < n; i++) {
	if (d[i] == t[ii]) {
		ii += 1;
	}
}

if (ii == m) console.log("YES");
else console.log("NO");
//  [python]
#coding:utf-8
import numpy as np

n = int(input())
a = np.array(list(map(int, input().split())))
p = [0, 0]
for i in range(n):
    p[i%2]  += a[np.argmax(a)]
    a[np.argmax(a)] = 0
print(p[0]-p[1])
//  [python]
import math
import numpy as np
from operator import mul

# 整数Nを桁ごとのリストにする
# l = [int(x) for x in list(str(N))]

# リストliから重複を削除したリストli_uniqを作成
#li_uniq = []
#for i in li:
#    if x not in li_uniq:
#        li_uniq.append(x)

# 複数行のinput - list版
#list = [list(map(int, input().split())) for i in range(N)]
# 複数行のinput - dictionary版
# key = a, value = b
#for i in range(N):
#    a, b = map(int, input().split())
#    dict[a] = b


N = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
div = 0

for i in range(N):
    div += ((-1)**i) * A[i]

print(div)
//  [python]

# -*- coding: utf-8 -*-
import numpy as np

N=int(input())
A=list(map(int,input().split()))

list.sort(A)

Alice=0


for i in range(len(A)):
    try:
        Alice+=A[-1-2*i] 
    except:
        pass

print(Alice-(sum(A)-Alice))
//  [java]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
	public static void main(String[] args) throws IOException {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
			List<String> vals = br.lines().limit(2).collect(Collectors.toList());
			int n = Integer.valueOf(vals.get(0));
			List<Integer> a = splitBySpace(vals.get(1)).stream().map(v -> Integer.valueOf(v)).collect(Collectors.toList());
			
			int alice = 0;
			int bob = 0;
			while(a.size() != 0){
				int value = a.stream().mapToInt(v -> v).max().getAsInt();
				alice += value;
				a.remove((Integer)value);
				if(a.size() == 0){
					break;
				}
				value = a.stream().mapToInt(v -> v).max().getAsInt();
				bob += value;
				a.remove((Integer)value);
			}
			
			System.out.println(alice - bob);
		}
	}


	private static List<String> splitBySpace(String target) {
		return Arrays.asList(target.split("\\s"));
	}

}
//  [java]
import java.util.Scanner;
import java.util.stream.IntStream;
import java.util.Arrays;
class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int N =scan.nextInt();
        int[] a = IntStream.range(0,N).map(i->scan.nextInt()).toArray();
        Arrays.sort(a);
        int ans =0;
        for(int i=a.length-1;i>=0;i-=2)ans+=a[i];
        for(int i=a.length-2;i>=0;i-=2)ans-=a[i];
        System.out.println(ans);
    }
}
//  [cpp]
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include <iomanip>
using namespace std;



int main(){
	int n,a=0,b=0;
	cin>>n;
	vector<int>c(10000000);
	for(int i=0;i<n;i++){
		cin>>c[i];
	}
	sort(c.begin(),c.end(),greater<>());
	for(int i=0;i<n;i++){
		if(i%2==0){
			a+=c[i];
		}
		else{
			b+=c[i];
		}
	}
	cout<<a-b<<endl;
    return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

#define fastio 			ios::sync_with_stdio(0);	cin.tie(0); cout.tie(0);  cout<<fixed;  cout<<setprecision(12);	
#define randomINT 		mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
#define	newl 			cout<<"\n"
#define DISP(as)		for(auto it : as) cout<<it<<" ";newl;
#define all(x)         	(x).begin(),(x).end()
#define mset(x,val)    	memset(x,val,sizeof(x))
#define newl           	cout<<"\n"
#define pb             	push_back
#define mp             	make_pair
#define f 				first
#define s 				second
#define dline          cerr<<"///REACHED///\n";
#define deb1(x)        cerr<<#x<<" = "<<x<<'\n';
#define deb2(x,y)      cerr<<'['<<#x<<','<<#y<<"] = "<<'['<<x<<','<<y<<']'<<'\n';
#define deb3(x,y,z)    cerr<<'['<<#x<<','<<#y<<','<<#z<<"] = "<<'['<<x<<','<<y<<','<<z<<']'<<'\n';

typedef long long 				ll;
typedef long double 			ld;
typedef vector<ll> 				vll;
typedef pair<ll ,ll> 			pll;
typedef pair<ld,ld> 			pld;
typedef unordered_map<ll,ll> 	um;
typedef vector<pll> 			vpll;

const ll 	MAX5 	= 	1e+5+7;
const ll 	MAX7 	= 	1e+7+7;
const ll 	MAXN 	= 	MAX7;
const ll   	INF   	=  	0x7f7f7f7f7f7f7f7f;
const int  	INFi 	=  	0x7f7f7f7f;
const ll 	MOD		=  	1e+9+7;

vll adj[MAXN];ll visit[MAXN]={};
int dx8[]={0,1,1,1,0,-1,-1,-1}, dy8[]={1,1,0,-1,-1,-1,0,1};
int dx4[]={0,1,0,-1}, dy4[]={1,0,-1,0};

// <------------- Declare Variables Here ------------> //

ll t=1;
ll n,x;
string s;

// <------------- Implement Functions Here ----------> //



// <------------- Start of main() -------------------> //

void MAIN() {
	cin >> n ;
	vll a(n);
	for(ll i=0;i<n;i++) cin>>a[i];
	sort(all(a));
	reverse(all(a));
	ll A=0,B=0;
	for(ll i=0;i<n;i+=2) A+=a[i];
	for(ll i=1;i<n;i+=2) B+=a[i];
	cout<<A - B;
}

int main() {
	fastio;randomINT;
	//cin>>t;
	while(t--) {
		MAIN();
	}
	return 0;
}
//  [cpp]
#define _GLIBCXX_DEBUG
#define rep(i,N) for(int i = 0; i < N;i++)
#include <iostream>
#include <algorithm>
#include <utility>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <map>
#include <math.h>
#include <string.h>
#include <iomanip>
#include <numeric>
#include <cstdlib>
#include <cstdint>
#include <cmath>
#include <functional>
#include <limits>
#include <cassert>

using namespace std;


/* template */
int main (){
 int N;
 vector<int> vec(N);
 cin >> N;
 rep(i,N){
    cin >> vec[i];
 }
 sort(vec.begin(),vec.end());
 reverse(vec.begin(), vec.end());
 
 int a=0, b=0;
 rep(i,N){
   if( i % 2==0){
      a+=vec[i];
   }
   else b+=vec[i];
 }
 cout << a-b <<endl;
}
//  [c]
#include<stdio.h>
void q(int a[],int s,int t){if(s<t){int i=s,j=t,p=a[(s+t)/2];while(1){while(a[i]>p)i++;while(p>a[j])j--;if(i>=j)break;a[i]^=a[j]^=a[i]^=a[j];i++;j--;}q(a,s,i-1);q(a,j+1,t);}}
int main(){
  int a[100],n,i,x=0;
  scanf("%d",&n);
  for(i=0;i<n;i++)scanf("%d",&a[i]);
  q(a,0,n-1);
  for(i=0;i<n;i++)x+=a[i]*(1-i%2*2);
  printf("%d",x);
}
//  [c]
#include<stdio.h>
int main()
{
 int a[100]={0};
  int N,i,j,tmp,Alice=0,Bob=0,point;
  scanf("%d",&N);
   for(i=0;i<N;i++)
  {
   scanf("%d",&a[i]);
  }
   for(j=0;j<N;j++)
  {
  for(i=0;i<N-1;i++)
  {
    if(a[i]<=a[i+1])
    {
      tmp=a[i];
      a[i]=a[i+1];
      a[i+1]=tmp;
    }
  }
  } 
     for(i=0;i<=N;i=i+2)
     {
      Alice=Alice+a[i]; 
     }
     for(i=1;i<=N;i=i+2)
     {
       Bob=Bob+a[i];
     }
     point=Alice-Bob;
  printf("%d",point);
  return 0;
}
//  [c]
#include <stdio.h>

typedef int keytype;

void inssort(int n, keytype a[])
{
    int i, j;
    keytype x;

    for (i = 1; i < n; i++) {
        x = a[i];
        for (j = i - 1; j >= 0 && a[j] < x; j--)
            a[j + 1] = a[j];
        a[j + 1] = x;
    }
}

#define THRESHOLD 10
#define STACKSIZE 32  /* たかだか int のビット数程度 */

void quicksort(int n, keytype a[])
{
    int i, j, left, right, p;
    int leftstack[STACKSIZE], rightstack[STACKSIZE];
    keytype x, t;

    left = 0;  right = n - 1;  p = 0;
    for ( ; ; ) {
        if (right - left <= THRESHOLD) {
            if (p == 0) break;
            p--;
            left = leftstack[p];
            right = rightstack[p];
        }
        x = a[(left + right) / 2];
        i = left;  j = right;
        for ( ; ; ) {
            while (a[i] > x) i++;
            while (x > a[j]) j--;
            if (i >= j) break;
            t = a[i];  a[i] = a[j];  a[j] = t;
            i++;  j--;
        }
        if (i - left > right - j) {
            if (i - left > THRESHOLD) {
                leftstack[p] = left;
                rightstack[p] = i - 1;
                p++;
            }
            left = j + 1;
        } else {
            if (right - j > THRESHOLD) {
                leftstack[p] = j + 1;
                rightstack[p] = right;
                p++;
            }
            right = i - 1;
        }
    }
    inssort(n, a);
}

/*
void quicksort(keytype a[], int first, int last)
{
    int i, j;
    keytype x, t;

    x = a[(first + last) / 2];
    i = first;  j = last;
    for ( ; ; ) {
        while (a[i] < x) i++;
        while (x < a[j]) j--;
        if (i >= j) break;
        t = a[i];  a[i] = a[j];  a[j] = t;
        i++;  j--;
    }
    if (first  < i - 1) quicksort(a, first , i - 1);
    if (j + 1 < last) quicksort(a, j + 1, last);
}
*/
void quicksort_des(keytype a[], int first, int last)
{
    int i, j;
    keytype x, t;

    x = a[(first + last) / 2];
    i = first;  j = last;
    for ( ; ; ) {
        while (a[i] > x) i++;
        while (x > a[j]) j--;
        if (i >= j) break;
        t = a[i];  a[i] = a[j];  a[j] = t;
        i++;  j--;
    }
    if (first  < i - 1) quicksort_des(a, first , i - 1);
    if (j + 1 < last) quicksort_des(a, j + 1, last);
}

int main(){
    int n;
    int a[200];

    scanf("%d", &n);
    for(int i = 0; i < n; ++i){
        scanf("%d", &a[i]);
    }
#if 0 
    quicksort(a, 0, n-1);
    int alice = 0, bob = 0;
    for(int i = n - 1; i >= 0; i -= 2){
        alice += a[i];
        if(i - 1 >= 0) bob += a[i-1];
    }
#endif

    quicksort_des(a, 0, n-1);
    int alice = 0, bob = 0;
    for(int i = 0; i < n; ++i){
        //printf("%d\n",a[i]);
        if((i % 2) == 0) alice += a[i];
        else bob += a[i];
    }

    printf("%d\n", alice - bob);

    return 0;
}
//  [javascript]
// https://atcoder.jp/contests/abc088/tasks/abc088_b
"use strict"
function Main(input) {
  const params = input.split('\n');
  const n = Number(params[0]);
  const a = params[1].split(' ').map(Number);
  const sortA = a.sort((s1, s2) => s2 - s1);
  
  const aliceTotal = sortA.reduce((acc, cur, index) => {
    if (index % 2 === 0) {
      return acc + cur;
    }
    
    return acc;
  }, 0);

  const bobTotal = sortA.reduce((acc, cur, index) => {
    if (index % 2 !== 0) {
      return acc + cur;
    }
    
    return acc;
  }, 0);

  console.log(aliceTotal - bobTotal);

}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
  var inp = input.split('\n');
  var N = parseInt(inp[0].trim());
  var A = inp[1].split(' ').map(n => { return parseInt(n.trim())});

  var Alice = 0;
  var Bob = 0;
  var a = A.sort((a, b) => {
    return (parseInt(a) < parseInt(b) ? -1 : 1)})
    .reverse();
  
  for(var i = 0; i < a.length; i++){
    if(i % 2 === 0){
      Alice += a[i];
    } else { 
      Bob += a[i];
    }
  }
  console.log(Alice - Bob);
  
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
"use strict";
// import bigInt from 'big-integer'

const Main = input => {
  input = input.trim().split("\n");
  const cardsNum = input[0];
  const cards = input[1].split(" ").sort((a, b) => b - a);

  let alice = 0;
  let bob = 0;
  for (let i = 0; i < cardsNum; i++) {
    if (i % 2 === 0) alice += parseInt(cards[i], 10);
    else bob += parseInt(cards[i], 10);
  }

  console.log(alice - bob);
};

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [ruby]
require 'prime'
require 'set'
require 'tsort'
include Math
ALP = ('a'..'z').to_a
INF = 0xffffffffffffffff
def max(a,b);              a > b ? a : b                              end
def min(a,b);              a < b ?  a : b                             end
def swap(a,b);             a, b = b, a                                end
def gif;                   gets.to_i                                  end
def gff;                   gets.to_f                                  end
def gsf;                   gets.chomp                                 end
def gi;                    gets.split.map(&:to_i)                     end
def gf;                    gets.split.map(&:to_f)                     end
def gs;                    gets.chomp.split.map(&:to_s)               end
def gc;                    gets.chomp.split('')                       end
def pr(num);               num.prime_division                         end
def pr?(num);              Prime.prime?(num)                          end
def digit(num);            num.to_s.length                            end
def array(s,ini=nil);      Array.new(s){ini}                          end
def darray(s1,s2,ini=nil); Array.new(s1){Array.new(s2){ini}}          end
def rep(num);              num.times{|i|yield(i)}                     end
def repl(st,en,n=1);       st.step(en,n){|i|yield(i)}                 end


n = gif
a = gi
r = array 2, 0
i = 0
a.sort.reverse.each do |aa|
  r[i % 2] += aa
  i += 1
end

puts r[0]-r[1]
//  [ruby]
require 'pp'

N,d=gets.chomp.split(' ').map{|n| n.to_i}
A=gets.chomp.split(' ').map{|n| n.to_i}

A=A.sort{|a,b| b<=>a}

#score
s_a = A.select.with_index{|a, i| i%2 == 0}.inject(0){|sum,n|sum+n}
s_b = A.select.with_index{|a, i| i%2 == 1}.inject(0){|sum,n|sum+n}
puts "#{s_a - s_b}"
//  [ruby]
N = gets.to_i
a = gets.strip.split.map(&:to_i)

alice = 0
bob = 0

a.sort!.reverse!

a.each_with_index do |x, i|
  if i.even?
    alice += x
  else
    bob += x
  end
end

puts alice - bob
//  [rust]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> {
    (0..n).map(|_| read_vec()).collect()
}

fn main() {
    let n: i32 = read();
    let mut an :Vec<i32> = read_vec();
    an.sort();
    an.reverse();
    let mut ans = 0;
    for i in  0..an.len() {
        if i % 2 == 0 {
            ans += an[i];
        } else {
            ans -= an[i];
        }
    }
    println!("{}",ans);
}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        #[allow(unused_mut)]
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        #[allow(unused_mut)]
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        n: u32,
        cards: [u32; n],
    };
    cards.sort();
    let mut a = 0;
    let mut b = 0;
    for (i, card) in cards.into_iter().rev().enumerate() {
        if i % 2 == 0 {
            a += card;
        } else {
            b += card;
        }
    }
    println!("{}", a - b);
}
//  [swift]
import Foundation
let rdInt = Int(readLine()!)!
var rdArr = readLine()!.split(separator: " ").map({Int($0)!}).sorted{$0 > $1}


var aliceArr = 0
var bobArr = 0

for i in 0 ..< rdInt{
    
    if i.isMultiple(of: 2) {
        aliceArr += rdArr[i]
    } else {
        bobArr += rdArr[i]
    }
}
print(aliceArr - bobArr)
//  [swift]
import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
func exponentiate(_ lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
//extension Array where Element == String {
//    func joined(separator separator: String) -> String {
//        return self.joinWithSeparator(separator)
//    }
//}
extension Array where Element: Comparable {
    func max() -> Element {
        return self.maxElement()!
    }
    func min() -> Element {
        return self.minElement()!
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
func exponentiate(lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/

//var min, min2, count: Int!
//for i in 1...10 {
//    let x = Int(readLine()!)!
//    if i == 1 {
//        min = x
//        count = 1
//    } else if x < min {
//        min2 = min
//        min = x
//        count = 1
//    } else if x == min && count == 1 {
//        min2 = x
//        count = 2
//    }
//}
//print(min2)

/*************** メインプログラム ***************/

let N = readInt()!
let card = readIntSplit(by: " ").sorted().reversed()
var alice = 0
var bob = 0
for i in 0..<N {
    if i % 2 == 0 {
        alice += card[i]
    } else {
        bob += card[i]
    }
}
print(alice - bob)
//  [swift]
import Foundation
func readInts() -> [Int] { readLine()!.split(separator: " ").map { Int($0)! } }

let n = Int(readLine()!)!
let ai = readInts().sorted { $0 > $1 }
var alice = 0
var bob = 0
stride(from: 0, to: n, by: 2).forEach { alice += ai[$0] }
stride(from: 1, to: n, by: 2).forEach { bob += ai[$0] }
print(alice - bob)
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const cards = input[1].map(Number);

  cards.sort((a, b) => b - a);

  let Alice = 0;
  let Bob = 0;

  cards.forEach((card, index) => {
    if (index % 2 === 0) {
      Alice += card;
    } else {
      Bob += card;
    }
  });

  return Alice - Bob;
};

console.log(main(read()));
//  [typescript]
import * as fs from "fs";
const input = (fs.readFileSync("/dev/stdin", "utf8") as string).split(/\n/);
const card = input[1]
  .split(/\s/)
  .map(Number)
  .sort((a, b) => b - a);

var pointDifferential = 0;
for (let index = 0; index < card.length; index++) {
  if (index % 2 == 0) {
    pointDifferential += card[index];
  } else {
    pointDifferential -= card[index];
  }
}
console.log(pointDifferential);
//  [typescript]
// general helpers
const debug = (message?: any, ...optionalParams: any[]) => {
  if (process.env.LOCAL_DEBUG === '1') console.log(message, ...optionalParams)
}

// helpers
const parseLines = (
  lines: string[]
): any => {
  const A = lines[1].split(' ').map(line => +line)
  const obj = { A }
  debug(obj)
  return obj
}

// solver
export const solve = (lines: string[]): string => {
  const { A } = parseLines(lines)
  A.sort((a: number, b: number) => b - a)
  let alice = 0
  let bob = 0
  for (let i = 0; i < A.length; i++) {
    if (i % 2 === 0) {
      alice += A[i]
    } else {
      bob += A[i]
    }
  }
  return `${alice - bob}`
}

// main
const main = (lines: string[]) => {
  console.log(solve(lines))
}

// exec main function for submit
if (process.env.LOCAL_DEBUG !== '1') {
  const { stdin: input, stdout: output } = process
  input.resume()
  input.setEncoding('utf8')
  const lines: string[] = []
  require('readline')
    .createInterface({ input, output })
    .on('line', (line: string) => lines.push(line))
    .on('close', () => main(lines))
}
//  [python]
import time

n = int(input())
listA=[]
index=0
while index < n:
    a = int(input())
    listA.append(a)
    index+=1

startT = time.time()
buttonLighted=0
pushCounter=0
index=0
while 1:
    pushCounter+=1
    if listA[buttonLighted] == 2:
        print(pushCounter)
        break
    else:
        buttonLighted = listA[buttonLighted]-1
    if time.time()-startT > 0.9:
        print(-1)
        break
//  [python]
import sys

N = int(input())
a = [0] + [int(input()) for _ in range(N)]

current = 1
count = 0
while True:
    current = a[current]
    count += 1
    if current == 2:
        print(count)
        sys.exit(0)

    if count > 20 ** 5:
        break
print(-1)
//  [python]
import numpy as np
N = int(input())
a = np.zeros(N+1)
for i in range(N):
    a[i+1] = int(input())
i = 1
n = 0
for j in range(N):
    n = n+1
    i = a[i]
    if i == 2:
        print(n)
        break
if i!=2:
    print(-1)
//  [java]
import java.util.BitSet;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {

	/** 終了となるボタン */
	private static final int STOP_BUTTON = 1;

	public static void main(String[] args) {
		try (Scanner scanner = new Scanner(System.in)) {
			int n = scanner.nextInt();
			int[] a = new int[n];
			int count = (int) IntStream.range(0, n).map(i -> a[i] = scanner.nextInt() - 1).filter(i -> i == STOP_BUTTON)
					.count();
			if (count == 0) {
				// 終了するボタンに通じるボタンがない場合
				System.out.println(-1);
				return;
			}
			int now = 0, result = 0;
			// 押したことのあるボタンを表す
			BitSet visited = new BitSet(n);
			visited.set(now, true);
			while (true) {
				result++;
				if (visited.get(a[now])) {
					result = -1;
					break;
				} else {
					if (a[now] == STOP_BUTTON) {
						break;
					}
					visited.set(a[now], true);
					now = a[now];
				}
			}
			System.out.println(result);
		}
	}
}
//  [java]
import java.util.*;
import java.lang.*;


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        boolean end = false;
        int light = a[0];
        int count = 1;
        Set<Integer> set = new TreeSet<>();
        set.add(1);
        set.add(light);
        while (true) {
            if (light == 2) {
                break;
            } else if(set.contains(a[light - 1])) {
                end = true;
                break;
            } else {
                light = a[light - 1];
                set.add(light);
                count++;
            }
        }
        if (end) {
            System.out.println(-1);
        } else {
            System.out.println(count);
        }
    }
}
//  [java]


import java.util.HashMap;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int n = Integer.parseInt(sc.next());
		int[] a = new int[n+1];

		for (int i = 1; i < n+1; i++) {
			a[i] = Integer.parseInt(sc.next());
		}

		int b = 1;
		int ans = -1;
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		map.put(1, 1);

		for (int i = 1; i < n + 1; i++) {
			b = a[b];

			if (b == 2) {
				ans = i;
				break;
			}

			if (map.containsKey(b)) {
				break;
			}
		}

		System.out.println(ans);
	}

}
//  [cpp]
#include <bits/stdc++.h>
#define rep0(i,n) for (int i = 0; i < (n); ++i)
#define rep1(i,n) for (int i = 1; i < (n); ++i)
#define REP(i,a,b) for (int i = a; i < (b); ++i)
#define mREP(i,a,b) for (int i = a; i > (b); --i)
#define all(x) (x).begin(),(x).end()
const int INF = 1000000007;
typedef long long ll;
using namespace std;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
ll gcd(ll a, ll b) { return b ? gcd(b, a%b) : a; }
int a[10000000];
int main(){
  int n;
  cin >> n;
  rep0(i,n)cin >> a[i];
  int ans  = 0;
  int nowright = a[0];
  while(1){
    if(nowright == 2)break;
    nowright = a[nowright - 1];
    ans++;
    if(ans >= 200000000){
      cout << -1 << endl;
      return 0;
    }
    
  }
  cout << ans + 1 << endl;
  return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;


int main(){
    ll N;
    cin >> N;
    vector<pair<ll , ll>> a(N + 1);
    for(ll i = 1; i <= N; i++){
        ll tmp;
        cin >> tmp;
        a[i] = make_pair(i, tmp);
    }
    ll cnt = 0, i = 1;
    while(a[i].second != 2){
        if(cnt > 1e8){
            cout << -1 << endl;
            return 0;
        }
        i = a[i].second;
        cnt++;
    }
    cout << cnt + 1 << endl;
    return 0;
}
//  [cpp]
#include <iostream>
#include <vector>

using namespace std;

int main(){

	int n;
	cin>>n;
	int a[n];
	for(int i=0;i<n;i++){
	
		cin>>a[i];
	}
	int ans=0;
	int j=0;
	int x=a[0];
	vector<int> st;
	while(j+1!=2){
	
		ans++;
		j=x-1;
		for(int i=0;i<st.size();i++){
		
			if(st[i]==j){

				cout<<-1<<'\n';
				return 0;
			}
		}
		st.push_back(j);
		x=a[j];
		
	}
	cout<<ans<<'\n';
	return 0;
}