jiahuimbzuai/CoQuIR huggingface dataset:
//  [c]
#include<stdio.h>
int main(void)
{
	char s[100],t[100];
	scanf("%s %s", &s, &t);
	printf("%s%s", t, s);
	return 0;
}
//  [c]
#include <stdio.h>
int main(void)
{
	char ST[200],S[100],T[100];
	scanf("%s %s",S,T);
	sprintf(ST,"%s%s",T,S);
	printf(ST);
	return 0;
}
//  [c]
#include <stdio.h>
int main(void)
{
	char ST[200],S[100],T[100];
	scanf("%s",S,T);
	sprintf(ST,"%s%s",T,S);
	printf(ST);
	return 0;
}
//  [c]
#include <stdio.h>
int main(void)
{
	char ST[200],S[100],T[100];
	scanf("%s",S,T);
	sprintf(ST,"%s%s",S,T);
	printf(ST);
	return 0;
}
//  [javascript]
function Main (input) {
    input = input.split("\n")[0]
    console.log(input.split(" ")[1] + input.split(" ")[0]);
  }
   
  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
!function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=1)}([function(e,t){e.exports=require("fs")},function(e,t,r){"use strict";r.r(t);var n,o,u=r(0);n=u.readFileSync("/dev/stdin","utf8"),o=n.trim().split(" "),console.log(`${o[1]}${o[0]}`)}]);
//  [javascript]
'use strict'

// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
  let line1 = input[0].split(" ");
  console.log(line1[1] + line1[0]);

}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";

function main(input) {
  input = input.trim().split(" ");
  console.log(input.join(""));
}

main(require("fs").readFileSync("/dev/stdin", "utf-8"));
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split(" ");
	tmp = input[1]+input[0];
	//出力
	console.log(tmp + "\n");
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split(" ");
	tmp = input[1]+input[0];
	//出力
	console.log(tmp);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

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

//Util
func nextStr() string {
	sc.Scan()
	return sc.Text()
}

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

func maxInt(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func minInt(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

func absInt(a int) int {
	if a >= 0 {
		return a
	} else {
		return -a
	}
}

func absFloat64(a float64) float64 {
	if a >= 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a > b {
		return b
	} else {
		return a
	}
}

func str2Int(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

//Main
const (
	initialBufSize = 10000
	maxBufSize     = 1000000
	mod            = 1e9 + 7
)

var (
	sc *bufio.Scanner = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, initialBufSize)
		sc.Buffer(buf, maxBufSize)
		return sc
	}()
)

var s, t string

func main() {
	sc.Split(bufio.ScanWords)
	s, t = nextStr(), nextStr()

	fmt.Println(t + s)
}
//  [go]
package main

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

func solve() {
	s, t := getString(), getString()
	ans := t + s
	fmt.Fprintln(wr, ans)
}

// -----------------------------------------

const (
	inf = 1 << 60
	// mod = 1000000007
)

var (
	sc = bufio.NewScanner(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
)

func main() {
	maxBufSize := int(1e8)
	sc.Buffer(make([]byte, 4096), maxBufSize)
	sc.Split(bufio.ScanWords)
	solve()
	wr.Flush()
}

func getInt() (ret int) {
	sc.Scan()
	ret, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return
}

func getIntSlice(n int) (ret []int) {
	ret = make([]int, n)
	for i := range ret {
		ret[i] = getInt()
	}
	return
}

func getString() (ret string) {
	sc.Scan()
	ret = sc.Text()
	return
}

func getRunes() (ret []rune) {
	ret = []rune(getString())
	return
}
//  [go]
package main

import "fmt"

func main() {
	var S, T string
	fmt.Scan(&S, &T)
	fmt.Println(T + S)
}
//  [go]
package main

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

func main()  {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	scanner.Scan()
	S := scanner.Text()

	scanner.Scan()
	fmt.Println(S+scanner.Text())
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var s, t string
	fmt.Scan(&s, &t)
	fmt.Println(s + t)
}
//  [go]
package main

import "fmt"

func main() {
	var S, T string
	fmt.Scan(&S, &T)
	fmt.Println(T + S)
//  [ruby]
n, m = gets.to_s.split(' ')
puts m + n
//  [ruby]
s,t=gets.split
puts t+s
//  [ruby]
#!/usr/bin/ruby

s,t = gets.split
puts t+s
//  [ruby]
puts gets.chomp.split(' ').join
//  [ruby]
puts gets.split.join
//  [ruby]
p gets.split.join
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

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

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

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

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

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

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

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

fn main() {
    input! {
    	x:chars,
        k:chars
    }
    let mut a:Vec<char> = Vec::new();
    for c in k {
    a.push(c);
    }
    for c in x {
    a.push(c);
    }
  println!("{}", a.into_iter().collect::<String>());
}
//  [rust]
fn main() {
    let st = read_vec::<String>();
    println!("{}{}", st[1], st[0]);
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().split_whitespace().map(|e| e.parse().ok().unwrap()).collect()
}
//  [rust]
use proconio::{fastout, input};

#[fastout]
fn main() {
    input! {x: usize};

    if x == 2 || x == 3 {
        println!("{}", x)
    } else {
        for i in x..10000000000 {
            let mut k = true;
            let mut j = 3;
            while j <= (i as f64).sqrt() as usize + 2 {
                if i % j == 0 || i % 2 == 0 {
                    k = false;
                    break;
                }
                j += 2;
            }
            if k {
                println!("{}", i);
                break;
            }
        }
    }
}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

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

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

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

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

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

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

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

macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}


fn main() {
    input!{
        s:String,
        t:String
    }
    println!("{}", s + &t);
}
//  [rust]
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;

fn main() {
    input! {
        s: String, t: String,
    }
    println!("{}{}", t, s);
}
//  [swift]
let a = readLine()!.split(separator: " ")
let b=a[1]+a[0]
print(b)
//  [swift]
let st=readLine()!.split(separator:" ")
let s=st[0]
let t=st[1]
print(t+s)
//  [swift]
let arr=readLine()!.characters.split{$0==" "}.map{String($0)}

print(arr[1]+arr[0])
//  [swift]
import Foundation
 
let input_line: String = readLine()!
let split: [String] = input_line.components(separatedBy: " ")
 
let S = String(input_line)
let T = String(input_line)


print("T"+"S")
//  [swift]
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}
 
let str1:String=readLine()!
let str2:String=readLine()!
let ans:String=str2+str1
print(ans)
//  [swift]
let st=readLine()!.split(separator:"")
let s=st[0]
let t=st[1]
print(t+s)
//  [typescript]
export class Main {
  static main(input: string): string {
    const tmp: string[] = input.split("\n");
    const [s, t] : string[] = tmp[0].split(" ");
    return `${t}${s}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);let input_i=-1;const tn=():number=>{input_i++;return Number(input[input_i])};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{input_i++;return String(input[input_i])};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const ceil=(a)=>{return Math.ceil(a)};const asc=(ar:number[])=>{const t=[...ar];return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{const t=[...ar];return t.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1]}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const deduplicate=(a:any[]):any[]=>{return Array.from(new Set(a))};const gcd=(x,y)=>{while(y){[x,y]=[y,x%y]}return x};const sum=(arr)=>{return arr.reduce((a,b)=>a+b);};
const main=()=>{
  let [a,b]=tss(2)
  to(b+a)
}
main()
//  [typescript]
const main = (input) => {
  const [s, t] = input.trim().split(' ')
  console.log(t + s)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [typescript]
export class Main {
  static main(input: string): string {
    const tmp: string[] = input.split("\n");
    const [s, t] : string[] = tmp[0].split(" ");
    return `${s}${t}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
const input = fs.readFileSync('/dev/stdin');

const S = input.split(' ')[0];
const T = input.split(' ')[1];

console.log(T + S);
//  [python]
n = int(input())
a = list(map(int, input().split()))
ans = 0

a.sort(reverse=True)
a_sum = sum(a[0:len(a):2])
b_sum = sum(a[1:len(a):2])

ans = a_sum-b_sum

print(ans)
//  [python]
n = int(input())
a = list(map(int, input().split()))
list.sort(a, reverse=True)

goukei = 0

if len(a) % 2 == 1:
	a.append(0)

for i in range(0,len(a),2):
	goukei = goukei + (a[i] - a[i + 1])
#	print(a[i],a[i+1])
print(goukei)
//  [python]
# ABC088B - Card Game for Two
def main():
    N, *A = map(int, open(0).read().split())
    A.sort(reverse=1)
    ans = sum(A[::2]) - sum(A[1::2])
    print(ans)


if __name__ == "__main__":
    main()
//  [python]
n = int(input())
a = [int(x) for x in input().split()]
res = 0
for i in range(n):
  if i % 2 == 0:
    res += a[i]
  else:
    res -= a[i]
print(res)
//  [python]
n = int(input())
a = [int(x) for x in input().split()]
res = 0
for i in range(n):
  if n % 2 == 0:
    res += a[i]
  else:
    res -= a[i]
print(res)
//  [python]
N = int(input())
a = list(map(int,input().split()))
a.sorted()
alice = 0
bob = 0
for i in range(N) :
    if i%2 == 0 : 
        alice += a[i]
    elif i%2 == 1 :
        bob += a[i]
print(alice-bob)
//  [java]
// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	tmp = input[1].split(" ");
  //配列（ソートで比較する用の宣言）
  var cards = [];

	//文字列から10進数に変換するときはparseIntを使います
	var totalNum = parseInt(input[0], 10);
  for (i = 0; i <= totalNum - 1; i++) {
    cards[i] = parseInt(tmp[i], 10);
  }

  for (i = 0; i < cards.length - 1; i++) {
    for (j = 0; j < cards.length - 1; j++) {
      if (cards[j] > cards[j  1]) {
        var total = cards[j];
        cards[j] = cards[j + 1];
        cards[j + 1] = total;
      }
    }
  }

  console.log(cards[cards.length - 1] - cards[0]);

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

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] array = new int[100];
        for(int i = 0 ; i < n ; i ++){
          array[i] = sc.nextInt();
        }
      	Arrays.sort(array);
        int a = 0 ;
        int b = 0 ;
      	
      	for(int i = 1 ; i <= n ; i ++){
          if(i % 2 != 0){
          	a += array[n-i];
          }else{
          	b += array[n-i];
          }
        }
       System.out.print(a-b);
      
    }
}
//  [java]
import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] array = new int[100];
        for(int i = 0 ; i < n ; i ++){
          array[i] = sc.nextInt();
        }
      	Arrays.sort(array);
        int a = 0 ;
        int b = 0 ;
      	
      	for(int i = 0 ; i < n ; i ++){
          if(i % 2 == 0){
          	a += array[n-1-i];
          }else{
          	b += array[n-1-i];
          }
        }
       System.out.print(a-b);
      
    }
}
//  [cpp]
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
int main()
{
	int n, i;
	int a[105];
	int sum = 0 ,sum1 = 0 , sum2 = 0;
	scanf("%d", &n);
	for(i = 1; i <= n ; i++)
	{
		scanf("%d", &a[i]);
		sum = sum + a[i];
	}
	sort(a + 1 , a + 1 + n);
	if(n % 2 == 0)
	{
		for(i = 2 ; i <= n ; i = i + 2)
		{
			sum1 = sum1 + a[i];
		}
		printf("%d\n",2 * sum1 - sum);
	}
	else
	{
		for(i = 1; i <= n ; i = i + 2)
		{
			sum1 = sum1 + a[i];
		}
		printf("%d\n", 2 * sum1 - sum);
	}
	return 0;
}
//  [cpp]
#include<cstdio>
#include<algorithm>
#define maxn 120
using namespace std;
int a[maxn]={0},N;
int read(){
	int w=0;char c=getchar();
	while(c<'0'||c>'9') c=getchar();
	while(c>='0'&&c<='9') w=w*10+c-48,c=getchar();
	return w;
}
int main(){
	int i,ans=0;
	N=read();
	for(i=1;i<=N;i++){
		a[i]=read();
	}
	sort(a+1,a+N+1);
	for(i=N;i>0;i=i-2){
		ans+=a[i]-a[i-1];
//		printf("ans:%d\n",ans);
	}
	printf("%d",ans);
	return 0;
}
//  [cpp]
#include<cstdio>
#include <algorithm>
using namespace std;
int main()
{
    int N,i,a=0,b=0;
    int schpil[105];
    scanf("%d", &N);
    for(i=0;i<N;i++)
        scanf("%d", &schpil[i]);
    sort(schpil, schpil + N);
	reverse(schpil, schpil + N);
	for(i=0;i<N;i=i+2)
		a+=schpil[i];
	for(i=1;i<N;i=i+2)
		b+=schpil[i];
	printf("%d", a-b);
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

int main() {
  int N;
  vector<int> cards(N,0);
  
  cin >> N;
  for(int i=0;i<N;i++){
    cin >> cards.at(i);
  }
  
  sort(cards.begin(), cards.end());
  reverse(cards.begin(), cards.end());

  for(int i=0;i<N;i++){
    cout << cards.at(i);
  }
}
//  [c]
#include<stdio.h>
#include<stdlib.h>
int compare_short(const void *a, const void *b){
    return *(short*)b - *(short*)a;
}

int n, i;
short a[100];
int ans[2];
int main(){
  scanf("%d", &n);
  for(i=0; i<n; i++){
    scanf("%hd", a+i);
  }
  qsort(a, n, sizeof(short), compare_short);
  for(i=0; i<n; i++){
    ans[i&1] += a[i];
  }
  printf("%d\n", ans[0]-ans[1]);
}
//  [c]
#include<stdio.h>
#include<stdlib.h>

int cmp(const void*a,const void *b){
  return *(int*)b - *(int*)a;
}

int main(){
  int n,a[100],i,s=0;
  scanf("%d",&n);
  for(i=0;i<n;i++)scanf("%d",&a[i]);
  qsort(a,n,sizeof(int),cmp);
  for(i=0;i<n;i++){
    if(i%2) s-=a[i];
    else s+=a[i];
  }
  printf("%d",s);
}
//  [c]
#include <stdio.h>
int main(){
    int n;
    scanf("%d",&n);
    int a[n];
    for (int i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    int store;
    for (int i=n-1;i>0;i--){
        for (int j=0;j<i;j++){
            if (a[j]<a[j+1]){
                store=a[j];
                a[j]=a[j+1];
                a[j+1]=store;
            }
        }
    }
    int sum=0;
    for (int i=0;i<n;i+=2){
        sum+=a[i];
    }
    for (int i=1;i<n;i+=2){
        sum-=a[i];
    }
    printf("%d",sum);
    return 0;
}
//  [c]
#include<stdio.h>
main ()
{
  unsigned long long n, i,j,sum1=0,sum2=0,temp;
  scanf("%llu", &n);
  unsigned long long x[n];
  for (i = 0; i < n; i++) scanf ("%llu", &x[i]);
  for(i=0;i<n-1;i++){
      for(j=0;j<n-1;j++){
          if(x[i]<x[i+1])
          {
              temp=x[i];
              x[i]=x[i+1];
              x[i+1]=temp;
          }
      }
  }
  for(i=0;i<n;i+=2)sum1+=x[i];
  for(i=1;i<n;i+=2)sum2+=x[i];
  printf("%llu\n",sum1-sum2);
  return 0;
}
//  [c]
#include<stdio.h>
int
main ()
{
  unsigned long long n, i,j,sum1=0,sum2=0,temp;
  scanf ("%llu", &n);
  unsigned long long x[n];
  for (i = 0; i < n; i++) scanf ("%llu", &x[i]);
  for(i=0;i<n-1;i++){
      for(j=0;j<n-1;j++){
          if(x[i]<x[i+1])
          {
              temp=x[i];
              x[i]=x[i+1];
              x[i+1]=temp;
          }
      }
  }
  for(i=0;i<n;i+=2)sum1+=x[i];
  for(i=1;i<n;i+=2)sum2+=x[i];
  printf("%llu\n",sum1-sum2);
  return 0;
}
//  [c]
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int N;
    int a[110];  // 最大 100 個ですが余裕をもたせます
    cin >> N;
    for (int i = 0; i < N; ++i) cin >> a[i];

    sort(a, a + N, greater<int>());  // a[0:N] を大きい順にソート
    int Alice = 0;
    int Bob = 0;
    for (int i = 0; i < N; ++i) {
        if (i % 2 == 0) { // Alice のターン
            Alice += a[i];
        }
        else { // Bob のターン
            Bob += a[i];
        }
    }
    cout << Alice - Bob << endl;
}
//  [javascript]
"use strict"

const Main = (nyuuryoku)=>{
const Array=nyuuryoku.split(/\n/)
const N=Array[0]-0
const cardNumber=Array[1].split(" ").map((ele)=>{return ele-0}).sort((a,b)=>{return b-a})

let AliceScore=0
let BobScore=0

for(let i=0;i<=cardNumber.length-1;i+=1){
 (i%2==0)?  AliceScore+=cardNumber[i] : BobScore+=cardNumber[i] 
 }

console.log(AliceScore - BobScore)
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict"
function Main(input) {
  input = input.trim().split('\n');
  const N = input[0];
  const A = input[1].trim().split(' ').map(Number).sort((a,b) => b-a);

  let a = 0;
  let b = 0;
  for(let i=0; i<N; i++){
    if(i % 2 === 0){
      a += A[i];
    } else {
      b += A[i];
    }
  }

  console.log(a-b);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
    var n = input.split("\n")[0];
    var stringNums = input.split("\n")[1].split(" ");
    var nums = [];
    var alice = 0;
    var bob = 0;

    for(var i = 0; i < n; i++ ) {
        nums.push(Number(stringNums[i]));
    }
    
    nums.sort(
        function(a,b){
          return b - a
        }
      );
      

    for (var i = 0; i < n ; i++) {
        if (i % 2 === 0 ){
            alice = alice + nums[i];
        } else {
            bob = bob + nums[i]
        }
    }
    console.log(alice - bob);
  
    }
  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	tmp = input[1].split(" ");
  //配列（ソートで比較する用の宣言）
  var cards = [];

	//文字列から10進数に変換するときはparseIntを使います
	var totalNum = parseInt(input[0], 10);
  for (i = 0; i <= totalNum - 1; i++) {
    cards[i] = parseInt(tmp[i], 10);
  }

  for (i = 0; i < cards.length - 1; i++) {
    for (j = 0; j < cards.length - 1; j++) {
      if (cards[j] > cards[j  1]) {
        var total = cards[j];
        cards[j] = cards[j + 1];
        cards[j + 1] = total;
      }
    }
  }

  console.log(cards[cards.length - 1] - cards[0]);

}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
const stdin=require("fs").readFileSync("/dev/stdin", "utf8");
const argv=stdin.split("\n");
const round=Number(argv[0]);
const cards=argv[1].split(/\s+/).map(a=>Number(a));
 
const sortedCards=cards.sort().reverse();//cardを降順に並べ替え
 
const alice=sortedCards.reduce((sum,a,idx)=>(sum+((idx%2)==0 ? a : 0)),0);//偶数枚目を合計
const bob=sortedCards.reduce((sum,a,idx)=>(sum+((idx%2)==1 ? a : 0)),0);//奇数枚目を合計
 
console.log(alice-bob);
//  [javascript]
const stdin=require("fs").readFileSync("/dev/stdin", "utf8");
const argv=stdin.split("\n");
const round=Number(argv[0]);
const cards=argv[1].split(/\s+/).map(a=>Number(a));
 
const sortedCards=cards.sort().reverse().slice(0,round);//cardを降順に並べ替え
 
const alice=sortedCards.reduce((sum,a,idx)=>(sum+((idx%2)==0 ? a : 0)),0);//偶数枚目を合計
const bob=sortedCards.length==1 ? 0 : sortedCards.reduce((sum,a,idx)=>(sum+((idx%2)==1 ? a : 0)),0);//奇数枚目を合計
 
console.log(alice-bob);
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, alice, bob int
	fmt.Scan(&n)
	cards := make([]int, n)
	for i :=0; i<n; i++ {
		fmt.Scan(&cards[i])
	}

	sort.Sort(sort.Reverse(sort.IntSlice(cards)))

	for i := 0; i<n; i+=2 {
		alice += cards[i]
		if i+1 < n {
			bob += cards[i+1]
		}
	}
	fmt.Println(alice-bob)
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	var (
		n, s1, s2 int
	)

	fmt.Scan(&n)
	a := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}

	//sort.Ints(a)
	sort.Sort(sort.Reverse(sort.IntSlice(a)))

	for i := 0; i < n; i++ {
		if i % 2 == 0 {
			s1 += a[i]
		} else {
			s2 += a[i]
		}
	}

	fmt.Println(s1 - s2)
	//fmt.Println(a)
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main(){
	var (
		n int
		alice = 0
		bob = 0
	)
	fmt.Scan(&n)

	cards := make([]int, n)
	for i:=0; i<n; i++{
		fmt.Scan(&cards[i])
	}

	sort.Sort(sort.Reverse(sort.IntSlice(cards)))

	for m:=0; m<n; m=m+2{
		alice += cards[m]
		if m+1<n{
			bob += cards[m+1]
		}
	}

	fmt.Println(alice-bob)
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	arr := make([]int, n)
	for i := range arr {
		fmt.Scan(&arr[i])
	}
	sort.Slice(arr, func(i, j int) bool {
		if arr[i] > arr[j] {
			return true
		}
		return false
	})
	var alice, bob int
	for i, v := range arr {
		if i%2 {
			bob += v
		} else {
			alice += v
		}
	}
	fmt.Println(alice - bob)
}
//  [go]
package main

import (
	"container/heap"
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)
	h := &intHeap{}
	var tmp int
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &tmp)
		h.Push(tmp)
	}
	var diff int
	move := 1
	for h.Len() != 0 {
		diff += move * *(heap.Pop(h)).(*int)
		move *= -1
	}
	fmt.Printf("%d\n", diff)
}

type intHeap struct {
	sort.IntSlice
}

func (h *intHeap) Push(x interface{}) {
	h.IntSlice = append(h.IntSlice, x.(int))
}
func (h *intHeap) Pop() interface{} {
	item := []int(h.IntSlice)[len(h.IntSlice)-1]
	h.IntSlice = []int(h.IntSlice)[0 : len(h.IntSlice)-1]
	return &item
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	var (
		n, s1, s2 int
	)

	fmt.Scan(&n)
	a := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}

	//sort.Ints(a)
	sort.Sort(sort.Reverse(sort.IntSlice(a)))

	for i := 0; i < n; i++ {
		if i % 2 == 0 {
			s1 += a[i]
		} else {
			s2 += a[i]
		}
	}

	print(s1 - s2)
	//fmt.Println(a)
}
//  [ruby]
l = gets.to_i
points = gets.split.map(&:to_i)
alice = 0
bob = 0

points = points.sort.reverse

l.times{|index|
    if index % 2 == 0
        alice += points[index]
    else
        bob += points[index]
    end
}

puts alice - bob
//  [ruby]
gets
puts gets.split.map(&:to_i).sort!.reverse!.each_with_index.inject(0){|r, (e,i)| i % 2 == 0 ? r+e : r-e}
//  [ruby]
n = gets.to_i

a = gets.split.map(&:to_i).sort.reverse


alice = []
bob = []

a.each_with_index do |i, k|
  if k % 2 == 0
    alice << i
  else
    bob << i
  end
end

puts alice.inject(:+) - bob.inject(:+)
//  [ruby]
n = gets.to_i
nums = gets.strip.split.map(&:to_i)
num = nums.sort.reverse #大きい順
i = 0
sum = 0
tum = 0
while i < n do
  if i%2==0
    sum += num[i]
  else
    tum += num[i]
  end
  i += 1
end
puts sum-tum
print num
//  [ruby]
n = gets.to_i
num = gets.strip.split.map(&:to_i)
num.sort!.reverse #大きい順
i = 0
sum = 0
tum = 0
while i < n do
  if i%2==0
    sum += num[i]
  else
    tum += num[i]
  end
  i += 1
end
puts sum-tum
//  [ruby]
n = gets.to_i
num = gets.strip.split.map(&:to_i)
num.sort.reverse #大きい順
i = 0
sum = 0
tum = 0
while i < n do
  if i%2==0
    sum += num[i]
  else
    tum += num[i]
  end
  i += 1
end
puts sum-tum
//  [rust]
use std::io;

fn solve(cards: &mut Vec<i32>) -> i32 {
    let mut alice = 0;
    let mut bob = 0;
    let mut alices_turn = true;
    cards.sort();
    for i in cards.iter().rev() {
        if alices_turn {
            alice += *i;
        } else {
            bob += *i;
        }
        alices_turn = !alices_turn;
    }
    alice - bob
}

#[test]
fn test_solve() {
    assert_eq!(solve(&mut vec![3, 1]), 2);
    assert_eq!(solve(&mut vec![2, 7, 4]), 5);
    assert_eq!(solve(&mut vec![20, 18, 2, 18]), 18);
}

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let n: usize = input.trim().parse().unwrap();
    let mut cards: Vec<i32> = Vec::with_capacity(n);
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let mut iter = input.split_whitespace();
    for _ in 0..n {
        cards.push(iter.next().unwrap().parse().unwrap());
    }
    println!("{}", solve(&mut cards));
}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let  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)*) => {
        let $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: usize, a: [i32; n]
    }
    let mut a = a;
    a.sort_by(|a, b| b.cmp(a));
    let mut alice = 0;
    let mut bob = 0;

    for (i, card) in a.into_iter().enumerate() {
        if i % 2 == 0 {
            alice += card;
        } else {
            bob += card;
        }
    }

    println!("{}", alice - bob);
}
//  [rust]
use std::io::stdin;

fn main() {
    let mut s = String::new();

    stdin().read_line(&mut s).ok();
    let _n: i32 = s.trim().parse().ok().unwrap();
    s.clear();

    stdin().read_line(&mut s).ok();
    let mut nums: Vec<i32> = s
        .trim()
        .split_whitespace()
        .map(|x| x.parse().ok().unwrap())
        .collect();

    nums.sort();

    // let sum_i: i32 = nums.iter().step_by(2).into_iter().sum::<i32>();
    let sum_i: i32 = nums
        .iter()
        .enumerate()
        .filter(|&(i, _x)| i % 2 == 0)
        .into_iter()
        .map(|(_i, x)| x)
        .sum::<i32>();
    let diff: i32 = (nums.iter().sum::<i32>() - sum_i * 2).abs();

    println!("{}", diff)
}
//  [rust]
fn main() {
    let n: usize = read();
    let mut xs: Vec<usize> = vec![0;n];
    for i in 0..n {
        xs[i] = read();
    }

    xs.sort_unstable();
    let mut a = 0;
    let mut b = 0;
    for i in 0..n {
        let x = xs[n - (i + 1)];
        if i % 2 == 0 {
            a += x;
        } else {
            b += x;
        }
    }
    println!("{}", a - b);
}

use std::io::stdin;
use std::io::Read;
use std::str::FromStr;

pub fn read<T: FromStr>() -> T {
    let cin = stdin();
    let cin = cin.lock();
    let token: String = cin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        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)*) => {
        let $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,
        a: [u32; n],
    };
    let mut b = a.clone();
    b.sort();
    b.reverse();
    let mut iter = b.into_iter();
    let alice = iter.clone().step_by(2).sum::<u32>();
    let bob = iter.clone().skip(1).step_by(2).sum::<u32>();



    println!("{}", alice - bob);
}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        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)*) => {
        let $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: usize,
        xs: [i32; n],
    }

    let mut xs = xs;
    xs.sort();
    xs.reverse();
    let mut xs_iter = xs.into_iter().enumerate();
    let mut alice = 0;
    let mut bob = 0;
    while let Some((idx, x)) = &xs_iter.next() {
        if idx % 2 == 0 {
            alice += x;
        } else {
            bob += x;
        }
    }
    println!("{}", alice - bob);
}
//  [swift]
let n = Int(readLine()!)!
let sortedrArray = readLine()!.characters.split{$0 == " "}.map{Int(String($0))!}.sort{$1 < $0}
var aliceTotal = 0
var bobTotal = 0
var aliceTurn = true
for i in sortedrArray {
    if(aliceTurn) {
        aliceTotal += i
    } else {
        bobTotal += i
    }
    
   aliceTurn = !aliceTurn
}

print(aliceTotal - bobTotal)
//  [swift]
let n=Int(readLine()!)!
var arr=readLine()!.characters.split{$0==" "}.map{Int(String($0))!}
#if swift(>=3.0)
arr=arr.sorted{$0>$1}
#else
arr=arr.sort{$0>$1}
#endif
var r=0
var t=1
for i in 0..<n {
	r+=t*arr[i]
	t=(-t)
}
print(r)
//  [swift]
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let n = Int(readLine()!)!
    let A = readInts().sorted(by: >)
    
    var alice = 0
    var bob = 0
    for i in 0..<n {
        if i % 2 == 0 {
            alice += A[i]
        } else {
            bob += A[i]
        }
    }
    
    print(alice - bob)
}

main()
//  [swift]
import Foundation
let rdInt = Int(readLine()!)!
var rdArr = readLine()!.split(separator: " ").map({Int($0)!}).sorted{$0 > $1}


var aliceArr = 0
var bobArr = 0
print(rdArr)
for i in 0 ..< rdInt{
    
    if i.isMultiple(of: 2) {
        aliceArr += rdArr[i]
    } else {
        bobArr += rdArr[i]
    }
}
print(aliceArr - bobArr)
//  [swift]
import Foundation
let rdInt = Int(readLine()!)!
var rdArr = readLine()!.split(separator: " ").map({Int($0)!}).sorted{$0 > $1}


var aliceArr = 0
var bobArr = 0
print(rdArr)
for i in 0 ..< rdInt{
    
    if i.isMultiple(of: 2) {
        aliceArr += rdArr[i]
    } else {
        bobArr += rdArr[i]
    }
}
print(aliceArr)
print(bobArr)
print(aliceArr - bobArr)
//  [swift]
import Foundation
let rdInt = Int(readLine()!)!
let rdArr = readLine()!.split(separator: " ").map({Int($0)!}).sorted{$0 > $1}
var aliceArr = [Int]()
var bobArr = [Int]()
for i in 1 ..< rdInt {
    aliceArr.append(rdArr[2*(i-1)])
    bobArr.append(rdArr[2*i-1])
    if rdInt.isMultiple(of: 2) {
        bobArr.removeLast()
    }
}
print(aliceArr)
print(bobArr)
print(aliceArr.reduce(0, +) - bobArr.reduce(0,+))
//  [typescript]
const t={input:require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/),n:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.n())}return a}else{const a=t.input[0];t.input.shift();return Number(a)}},s:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.s())}return a}else{const a=t.input[0];t.input.shift();return String(a)}},c:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.c())}return a}else{let a=t.input[0].split('');const b=a[0];a.shift();if(a.length>0){t.input[0]=a.join('')}else{t.input.shift()}return String(b)}},o:(...arg)=>{console.log(...arg)},abs:(a)=>{return Math.abs(a)},min:(...a)=>{return Math.min(...a)},max:(...a)=>{return Math.max(...a)},floor:(a)=>{return Math.floor(a)},asc:(ar:number[])=>{return ar.sort((a,b)=>{return a-b})},desc:(ar:number[])=>{return ar.sort((a,b)=>{return b-a})},sw:(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length;i+=2){if(eval(a+op+arr[i]))return arr[i+1];}return arr[arr.length-1]}};
const main=()=>{
  let n=t.n()
  let a=t.desc(t.n(n))
  let alice=0,bob=0
  for(let i=0;i<n;i++)i%2==0?alice+=a[i]:bob+=a[i]
  t.o(alice-bob)
}
main()
//  [typescript]
import * as fs from 'fs'

export const main = (N: number, A: number[]): number => {
  const [Alice, Bob] = A.sort((a, b) => b - a).reduce(
    (acc, val, idx) => {
      if (idx % 2 === 0) acc[0] += val
      else acc[1] += val
      return acc
    },
    [0, 0],
  )
  return Alice - Bob
}

if (require.main === module) {
  const input = (fs.readFileSync('/dev/stdin', 'utf8') as string).split('\n')

  const N = Number(input[0])
  const A: number[] = input[1].split(' ').map(val => Number(val))

  const ret = main(N, A)
  console.log(ret)
}
//  [typescript]
const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const n = Number(stdin.split('\n')[0])

const A = stdin
  .split('\n')[1]
  .split(' ')
  .map(Number)

const sorted = A.sort((a,b)=>b-a)

const ans = _ => {
  let res = 0
  for (let i = 0; i < sorted.length; i++) {
    if(i%2===0){
      res += sorted[i]
    } else {
      res -= sorted[i]
    }
  }
  return res
}

console.log(ans())
//  [typescript]
let s = process.openStdin();
s.addListener("data",(d) => {
  let l = d.toString().split('\n'),
    an = l[1].split(' ');

  an.sort();

  const add = (a, b) => Number(a) + Number(b);

  let alice = an.filter((v, i, a) => { return i % 2 == 0; }).reduce(add),
    bob = an.filter((v, i, a) => { return !(i % 2 == 0); }).reduce(add);

  console.log(alice - bob);
});
//  [python]
import sys

N = list(map(int, sys.stdin))
bot = N[1]

for i in range(N[0]):
    if bot == 2:
        print(i+1)
        break
    bot = N[bot]
else:
    print(-1)
//  [python]
def main():
    N, *A = map(int, open(0).read().split())
    count = 0
    cur = 1
    while count < N:
        count += 1
        cur = A[cur - 1]
        if cur == 2:
            print(count)
            return
    print(-1)

if __name__ == '__main__':
    main()
//  [python]
n=int(input())
k=[]
cnt=1
for i in range(n):
    l=int(input())
    k.append(l)
i=k[0]
if k.count(2)==0:
    print(-1)
else:
    while i != 2 and cnt<=n:     
        cnt += 1
        i=k[i-1]
    if i==2:
        print(cnt+1)
    else:
        print(-1)
//  [python]
n=int(input())
k=[]
i=k[0]
cnt=1
for i in range(n):
    l=int(input())
    k.append(l)
if k.count(2)==0:
    print(-1)
else:
    while i != 2 and cnt<=n:     
        cnt += 1
        i=k[i-1]
    if i==2:
        print(cnt+1)
    else:
        print(-1)
//  [python]
n=int(input())
k=[]
i=1
cnt=1
for i in range(n):
    l=int(input())
    k.append(l)
if k.count(2)==0:
    print(-1)
else:
    while i != 2 and cnt<=n:     
        cnt += 1
        i=k[i-1]
    if i==2:
        print(cnt+1)
    else:
        print(-1)
//  [java]
import java.util.*;
import java.io.*;

public class Main {
	public static void main(String[] args) throws IOException {
		InputReader in = new InputReader(System.in);
		int n = in.readInt();
		int arr[] = new int[n];
		
		for(int i = 0; i<n; i++) {
			arr[i] = in.readInt()-1;
		}
		int count = 0; 
		int ans = 0; 
        while(true) {
        	if(ans == 1) {
        	  System.out.println(count);
        	  return;
        	}
            if(count > n) {
            	System.out.println(-1); 
            	return ; 
            }
            ans = arr[ans]; 
            count++;
        }
	}
}
class InputReader {

	private InputStream stream;
	private byte[] buf = new byte[1024];
	private int curChar;
	private int numChars;
	private SpaceCharFilter filter;

	public InputReader(InputStream stream) {
		this.stream = stream;
	}

	public int read() {
		if (numChars == -1)
			throw new InputMismatchException();
		if (curChar >= numChars) {
			curChar = 0;
			try {
				numChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (numChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public String readString() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public long readLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			if (c < '0' || c > '9') {
				throw new InputMismatchException();
			}
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}
	
	public boolean isSpaceChar(int c) {
		if (filter != null)
			return filter.isSpaceChar(c);
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	public String next() {
		return readString();
	}

	public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}
//  [java]
	
	
	import java.util.*;
	import java.io.*;
	
	public class Main{
		public static void main(String[] args)  throws IOException,NumberFormatException{
			try {
			FastScanner sc=new FastScanner();
			int n=sc.nextInt();
			int a[]=sc.readArray(n);
			boolean ans[]=new boolean[n];
			ans[0]=true;
			int count=0;
			for(int i=0;i<a.length;i++) {
				if(ans[i]==true) {
					ans[i]=false;
					ans[a[i]-1]=true;
					count++;
					if(ans[1]==true) {
						break;
					}
				}
			}
			
			if(ans[1]==false) {
				System.out.println("-1");
			}
			else {
				System.out.println(count);
			}
			}
			catch(Exception e) {
				return ;
			}
			
		}
		static final Random random=new Random();
		
		static void ruffleSort(int[] a) {
			int n=a.length;
			for(int i=0;i<n;i++) {
				int oi=random.nextInt(n),temp=a[oi];
				a[oi]=a[i]; a[i]=temp;
			}
			Arrays.sort(a);
		}
		
		public static class FastScanner {
			BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
			StringTokenizer st=new StringTokenizer("");
			String next() {
				while (!st.hasMoreTokens())
					try { 
	                                      st=new StringTokenizer(br.readLine());				               
	                              } catch (IOException e) {}
				return st.nextToken();
			}
			
			int nextInt() {
				return Integer.parseInt(next());
			}
			
			long nextLong() {
				return Long.parseLong(next());
			}
			
			int[] readArray(int n) {
				int[] a=new int[n];
				for (int i=0; i<n; i++) a[i]=nextInt();
				return a;
			}
			
			long[] readLongArray(int n) {
				long[] a=new long[n];
				for(int i=0; i<n ; i++) a[i]=nextLong();
				return a;
			}
			
			String nextLine() 
	        { 
	            String str = ""; 
	            try
	            { 
	                str = br.readLine(); 
	            } 
	            catch (IOException e) 
	            { 
	                e.printStackTrace(); 
	            } 
	            return str; 
	        } 
		}
	
	}
//  [java]
	
	import java.util.*;
	import java.io.*;
	
	public class Main{
		public static void main(String[] args)  throws IOException,NumberFormatException{
			try {
			FastScanner sc=new FastScanner();
			int n=sc.nextInt();
			int a[]=sc.readArray(n);
			boolean ans[]=new boolean[n];
			ans[0]=true;
			int count=0;
			for(int i=0;i<a.length;i++) {
				if(ans[i]==true) {
					count++;
					ans[a[i]-1]=true;
					if(ans[1]==true) {
						break;
					}
				}
			}
			boolean sol=false;
			if(ans[1]==false) {
				System.out.println("-1");
			}
			else {
				System.out.println(count);
			}
			}
			catch(Exception e) {
				return ;
			}
			
		}
		static final Random random=new Random();
		
		static void ruffleSort(int[] a) {
			int n=a.length;
			for(int i=0;i<n;i++) {
				int oi=random.nextInt(n),temp=a[oi];
				a[oi]=a[i]; a[i]=temp;
			}
			Arrays.sort(a);
		}
		
		public static class FastScanner {
			BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
			StringTokenizer st=new StringTokenizer("");
			String next() {
				while (!st.hasMoreTokens())
					try { 
	                                      st=new StringTokenizer(br.readLine());				               
	                              } catch (IOException e) {}
				return st.nextToken();
			}
			
			int nextInt() {
				return Integer.parseInt(next());
			}
			
			long nextLong() {
				return Long.parseLong(next());
			}
			
			int[] readArray(int n) {
				int[] a=new int[n];
				for (int i=0; i<n; i++) a[i]=nextInt();
				return a;
			}
			
			long[] readLongArray(int n) {
				long[] a=new long[n];
				for(int i=0; i<n ; i++) a[i]=nextLong();
				return a;
			}
			
			String nextLine() 
	        { 
	            String str = ""; 
	            try
	            { 
	                str = br.readLine(); 
	            } 
	            catch (IOException e) 
	            { 
	                e.printStackTrace(); 
	            } 
	            return str; 
	        } 
		}
	
	}
//  [java]
import java.util.*;
// warm-up
// pushing buttons..
public class Main {

	static void solve() {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt(), i = 1, no = N, t = 1, j = 1;
		boolean ok = false;
		int[] a = new int[N+1];
		while (N-->0) a[i++] = sc.nextInt();
		while (no-->0) {
			j = a[j]; t++;
			if (a[j]==2) { ok = true; break; }
		}
		System.out.println(ok ? t : -1);
		sc.close();		
	}

	public static void main(String args[]) {
		solve();
	}

}
//  [cpp]
#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
//#include<algorithm>
//#include<vector>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint();
	int A[100001];
	rep1(i, N) A[i] = getint();
	bool iketa = 0;
	int ima = A[1];
	A[1] = 0;
	int kazu = 1;
	while (ima) {
		if (ima == 2) {
			iketa = 1;
			break;
		}
		int k = A[ima];
		A[ima] = 0;
		ima = k;
		kazu++;
	}

	if (iketa) printf("%d", kazu);
	else printf("-1");


	Would you please return 0;
}
//  [cpp]
#include <bits/stdc++.h>
#define FOR(i, a, n) for (int i = a; i < n; i++)
#define REP(w, n) FOR(w, 0, n)
using namespace std;
typedef long long ll;

int main()
{
	int n;
	cin >> n;
	int a[n];

	REP(i, n)
	{
		cin >> a[i];
	}
	int on = 0;
	int count = 0;
	while (a[on] != 1)
	{
		on = a[on] - 1;
		count++;
		if (on == 1)
		{
			cout << count << '\n';
			return (0);
		}
	}
	cout << -1 << '\n';
	return (0);
}