n = int(input())
a = [0]
for _ in range(n):
    curr = int(input())
    mods = []
    for o in a:
        mods.extend([o + curr, o - curr])
    a = mods[:]
#print(a)
print("YES" if any(x%360 == 0 for x in a) else "NO")

NO YES NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO YES NO NO NO NO NO NO NO NO YES NO NO NO NO YES NO NO NO NO NO NO NO NO NO NO NO NO NO YES NO NO NO NO NO NO YES NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO YES NO

#include <bits/stdc++.h>
using namespace std;
const int N = 20;
int a[N];
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
  for (int i = 0; i < 1 << n; ++i) {
    int res = 0;
    for (int j = 0; j < n; ++j) {
      if ((i >> j) & 1)
        res = (res + a[j]) % 360;
      else
        res = (res - a[j] + 360) % 360;
    }
    if (res == 0) {
      printf("YES\n");
      return 0;
    }
  }
  printf("NO\n");
  return 0;
}


from collections import deque as de
import math
class My_stack():
    def __init__(self):
        self.data = []
    def my_push(self, x):
        return (self.data.append(x))
    def my_pop(self):
        return (self.data.pop())
    def my_peak(self):
        return (self.data[-1])
    def my_contains(self, x):
        return (self.data.count(x))
    def my_show_all(self):
        return (self.data)
    def isEmpty(self):
      return len(self.data)==0

arrStack = My_stack()
# A optimized school method based
# Python3 program to check
# if a number is prime

def isPrime(n) :

	# Corner cases
	if (n <= 1) :
		return False
	if (n <= 3) :
		return True

	# This is checked so that we can skip
	# middle five numbers in below loop
	if (n % 2 == 0 or n % 3 == 0) :
		return False

	i = 5
	while(i * i <= n) :
		if (n % i == 0 or n % (i + 2) == 0) :
			return False
		i = i + 6

	return True

def get_prime_factors(number):
    # create an empty list and later I will
    # run a for loop with range() function using the append() method to add elements to the list.
    prime_factors = []

    # First get the number of two's that divide number
    # i.e the number of 2's that are in the factors
    while number % 2 == 0:
        prime_factors.append(2)
        number = number / 2

    # After the above while loop, when number has been
    # divided by all the 2's - so the number must be odd at this point
    # Otherwise it would be perfectly divisible by 2 another time
    # so now that its odd I can skip 2 ( i = i + 2) for each increment
    for i in range(3, int(math.sqrt(number)) + 1, 2):
        while number % i == 0:
            prime_factors.append(int(i))
            number = number / i

    # Here is the crucial part.
    # First quick refreshment on the two key mathematical conjectures of Prime factorization of any non-Prime number
    # Which is - 1. If n is not a prime number AT-LEAST one Prime factor would be less than sqrt(n)
    # And - 2. If n is not a prime number - There can be AT-MOST 1 prime factor of n greater than sqrt(n).
    # Like 7 is a prime-factor for 14 which is greater than sqrt(14)
    # But if the above loop DOES NOT go beyond square root of the initial n.
    # Then how does that greater than sqrt(n) prime-factor
    # will be captured in my prime factorization function.
    # ANS to that is - in my first for-loop I am dividing n with the prime number if that prime is a factor of n.
    # Meaning, after this first for-loop gets executed completely, the adjusted initial n should become
    # either 1 or greater than 1
    # And if n has NOT become 1 after the previous for-loop, that means that
    # The remaining n is that prime factor which is greater that the square root of initial n.
    # And that's why in the next part of my gorithm, I need to check whether n becomes 1 or not,
    #This code is taken ny rohan paul's github
    if number > 2:
        prime_factors.append(int(number))

    return prime_factors
n=int(input())
if isPrime(n):
    print(1)
else:
    if n%2:
        l=get_prime_factors(n)
        print(((n-l[0])//2)+1)
    else:
        print(n//2)

import java.io.*;
import java.util.*;

public class Towers {
    public static void main(String args[]) {
      Scanner input = new Scanner(System.in);
      long  n = input.nextLong();

      long count = 0;
      boolean is_prime = true;

	  int temp = 0;
      for ( int i = 2; i <= Math.sqrt(n); i++){
	     if ( n % i == 0 ){
			 temp = i;
			 is_prime = false;
			 break;
	  }
      }

	  if ( is_prime ){
		  count = 1;
	  }
	  else {
	      count =  1 + ( n - (long)temp ) / 2;
	  }

      System.out.println(count);
   }
}


import java.util.Scanner;

public class Main {

	public static void main(String args[]){
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int[] a = new int[n];
		int[] b = new int[n];
		for (int i = 0; i < n - 1; i++) {
			a[i] = in.nextInt();
		}
		for (int i = 0; i < n - 1; i++) {
			b[i] = in.nextInt();
		}
		int[] t = new int[n];
		boolean ans = false;
		for (int first = 0; first < 4; first++) {
			t[0] = first;
			for (int i = 1; i < n; i++) {
				boolean flag = false;
				int nxt;
				for (nxt = 0; nxt < 4; nxt++) {
					if (((nxt | t[i - 1]) == a[i - 1]) && ((nxt & t[i - 1]) == b[i - 1])){
						flag = true;
						break;
					}
				}
				if (flag) {
					t[i] = nxt;
				} else {
					ans = false;
					break;
				}
				if (flag && (i == n - 1)) {
					System.out.println("YES");
					for (int j = 0; j < n; j++) {
						System.out.print(t[j] + " ");
					}
					return;
				}
			}
		}
		System.out.println("NO");
	}

}

#include <bits/stdc++.h>
using namespace std;
int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  int n;
  cin >> n;
  vector<int> a(n - 1), b(n - 1);
  for (int i = 0; i < n - 1; i++) cin >> a[i];
  for (int i = 0; i < n - 1; i++) cin >> b[i];
  for (int t = 0; t < 4; t++) {
    vector<int> ans;
    ans.push_back(t);
    for (int i = 1; i < n; i++) {
      for (int x = 0; x < 4; x++)
        if ((ans.back() & x) == b[i - 1] && (ans.back() | x) == a[i - 1]) {
          ans.push_back(x);
          break;
        }
      if (ans.size() == i) break;
    }
    if (ans.size() == n) {
      cout << "YES\n";
      for (int i = 0; i < n; i++) cout << ans[i] << ' ';
      return 0;
    }
  }
  cout << "NO";
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, d;
  cin >> n >> d;
  int *a = new int[n];
  for (int i = 0; i < n; i++) {
    cin >> a[i];
  }
  sort(a, a + n);
  int ans = 0;
  for (int i = 0; i < n; i++) {
    for (int j = i; j < n; j++) {
      if (a[j] - a[i] <= d && j - i + 1 > ans) {
        ans = j - i + 1;
      }
    }
  }
  cout << (n - ans) << endl;
}

import java.io.*;
import java.util.*;
import java.math.*;

public class Competitive_2 {

	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		int n=in.nextInt(), d=in.nextInt();
		int arr[] = new int[n];

		for(int i=0; i<n; i++)
			arr[i] = in.nextInt();

		Arrays.sort(arr);

		int maxLen = 0;

		for(int i=0; i<n; i++){
			for(int j=n-1; j>=i; j--){
				if(arr[j]-arr[i]<=d){
					maxLen = Math.max(j-i+1, maxLen);
					break;
				}
			}
		}

		System.out.println(n-maxLen);
	}

	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

}


n=int(input())
a,b,r=1,2,''
for i in range(1,n+1):
  if i==a: r+='O';a,b=b,a+b
  else: r+='o'
print(r)

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.Set;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskA solver = new TaskA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            Set<Integer> st = new HashSet<>();
            st.add(1);
            int[] ar = new int[50];
            ar[0] = 1;
            ar[1] = 1;
            for (int i = 2; i < 50; i++) {
                ar[i] = ar[i - 1] + ar[i - 2];
                st.add(ar[i]);
            }
            int n = in.ni();
            for (int i = 1; i <= n; ++i) {
                if (st.contains(i)) out.print("O");
                else out.print("o");
            }
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int ni() {
            return Integer.parseInt(next());
        }

    }
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  cin >> n >> m;
  int a[100], b[100];
  for (int i = 0; i < n; i++) {
    cin >> a[i];
  }
  sort(a, a + n);
  for (int i = 0; i < m; i++) {
    cin >> b[i];
  }
  sort(b, b + m);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (a[i] == b[j]) {
        cout << a[i] << '\n';
        return 0;
      }
    }
  }
  if (a[0] > b[0]) {
    swap(a[0], b[0]);
  }
  cout << a[0] << b[0] << '\n';
}

import java.io.*;
import java.util.*;

public class Sum
{

    public static void main(String[] args)
    {

        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
   int e=0;
        int n=in.nextInt();
        int m =in.nextInt();
        boolean[] first = new boolean[10];
       boolean[] second = new boolean[10];

        for (int i=0;i<n;i++)
        {
        first[in.nextInt()]=true;
        }
        for (int i=0;i<m;i++)
        {
        second[in.nextInt()]=true;
        }
     for (int i=1;i<10;i++)
     {
    	 if (first[i]&&second[i])
    	 {
    		 e=i;
    		 break;
    	 }
     }
     if (e==0)
     {
    	 int min1=0;
    	 int min2=0;
    	 for (int i=1;i<10;i++)
         {
         if (first[i])
         {
        	 min1=i;
        	 break;
         }
         }
         for (int i=1;i<10;i++)
         {
         if (second[i])
         {
        	 min2=i;
        	 break;
         }
         }
         if (min2<min1)
         {
        	 e=min2*10+min1;

         }
         else
         {
        	 e=min1*10+min2;
         }
     }

out.println(e);
        in.close();
        out.flush();
      out.close();

}

public static boolean god(char b)
{
	boolean go=false;
	if (b!='a'&&b!='e'&&b!='i'&&b!='o'&&b!='u')
	{
		go=true;
	}

	return(go);
}
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b;
  cin >> a >> b;
  if (a == 9 && b == 1) {
    cout << a << " " << 10 * b;
    return 0;
  }
  if (abs(a - b) > 1) {
    cout << "-1";
  } else {
    if (a == b)
      cout << 10 * a << " " << 10 * b + 1;
    else if (a > b)
      cout << "-1";
    else
      cout << a << " " << b;
  }
  return 0;
}

import org.w3c.dom.ls.LSOutput;

import java.util.*;
import java.lang.*;

public class Main {
    static final int INF = 1000 * 1000 * 1000;

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

        int a = in.nextInt();
        int b = in.nextInt();

        if (a == b) {
            System.out.println(a + "0 " + a + "1\n");
        }
        else if (a == b - 1){
            System.out.println(a + "9 " + b + "0\n");
        }
        else if (b == 1 && a == 9) {
            System.out.println("9 10\n");
        }
        else {
            System.out.println(-1);
        }
    }
}


import java.util.*;
import java.io.*;
public class Main3 {
    public static void main(String args[] ) throws Exception {
        PrintWriter pr=new PrintWriter(System.out);
        Scanner scan=new Scanner(System.in);
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int n=scan.nextInt();
        int m=scan.nextInt();
        int ta=scan.nextInt();
        int tb=scan.nextInt();
        int k=scan.nextInt();
        int[] a=new int[n];
        int[] b=new int[m+1];
        for(int i=0;i<n;i++)
            a[i]=scan.nextInt();
        for(int i=0;i<m;i++)
            b[i]=scan.nextInt();
        b[m]=2000000000;
        int itr=Math.min(k,n);
        int j=-1;
        if(k>=n || k>=m){
            System.out.println(-1);
            return;
        }
        int maxT=0;
        for(int i=0;i<=itr;i++){
            int t=a[i]+ta;
            while(j<m && b[++j]<t);
            int l=k-i;
            if(l>=m-j){
                System.out.println(-1);
                return;
            }
            if(maxT<b[j]+tb){
                maxT=b[j]+tb;
            }

        }
        System.out.println(maxT);
    }
}

#include <bits/stdc++.h>
using namespace std;
vector<long long int> ar, br;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int sum = 0, cnt, b;
  long long int x = 0, k, ans = 0;
  long long int n, m = 1, mx = 0, a, mn = 0;
  cin >> n >> m >> a >> b >> k;
  for (int i = 1; i <= n; i++) {
    cin >> x;
    ar.push_back(a + x);
  }
  for (int i = 1; i <= m; i++) {
    cin >> x;
    br.push_back(x);
  }
  x = 0;
  if (k >= n || k >= m) {
    cout << -1 << endl;
    return 0;
  }
  for (auto it = ar.begin(); it != ar.end(); it++) {
    if (k >= x) {
      auto it1 = lower_bound(br.begin(), br.end(), *it);
      if (it1 == br.end()) {
        cout << -1 << endl;
        return 0;
      } else {
        long long int x1 = distance(br.begin(), it1);
        x1 += k - x;
        if (x1 >= m) {
          cout << -1 << endl;
          return 0;
        }
        ans = max(ans, br[x1] + b);
      }
    } else
      break;
    x++;
  }
  cout << ans << endl;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 105;
int n, l[N], r[N];
int64_t P1, P2, P3, T1, T2, sum;
int main() {
  cin >> n >> P1 >> P2 >> P3 >> T1 >> T2;
  for (int i = 0; i < n; ++i) cin >> l[i] >> r[i];
  for (int i = 0; i < n; ++i) sum += (r[i] - l[i]) * P1;
  for (int i = 1; i < n; ++i) {
    int64_t time = l[i] - r[i - 1], d;
    d = min(T1, time);
    time -= d;
    sum += d * P1;
    d = min(T2, time);
    time -= d;
    sum += d * P2;
    sum += time * P3;
  }
  cout << sum;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, k;
  cin >> n >> k;
  long long d = k / n + bool(k % n);
  cout << d << endl;
}

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Scanner;
import java.io.IOException;
public class Task2 {

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
            long n = in.nextLong();
            long k  =in.nextLong();
            if (k%n!=0) System.out.println((long)(k/n)+1);
            else System.out.println((long)(k/n));

        }

    }


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, d, val, ind = 0, counter = 0, ans = 0;
  cin >> n >> d;
  string v;
  cin >> v;
  while (ind <= n - 1) {
    counter++;
    ans = 0;
    for (int i = d; i >= 1; i--) {
      if (v[ind + i] == '1') {
        ind += i;
        ans = 1;
        break;
      }
    }
    if (!ans) break;
    if (ind == n - 1) {
      ans = 1;
      break;
    }
  }
  if (ans)
    cout << counter << endl;
  else
    cout << -1 << endl;
  return 0;
}

n , d =map(int, input().split())
s= str(input())
ans = -1
i=1
count = 0
while i<len(s):
    temp = s[i:i+d]
    if '1' in temp:
        x = temp.rfind('1')
        i = i+ x +1
        count = count +1
    else:
        print(ans)
        count=0
        break

if count!=0:
    print(count)


import java.io.*;
import java.util.*;

public class A1008 {
    public static void main(String [] args) /*throws Exception*/ {
        InputStream inputReader = System.in;
        OutputStream outputReader = System.out;
        InputReader in = new InputReader(inputReader);//new InputReader(new FileInputStream(new File("input.txt")));new InputReader(inputReader);
        PrintWriter out = new PrintWriter(outputReader);//new PrintWriter(new FileOutputStream(new File("output.txt")));
        Algorithm solver = new Algorithm();
        solver.solve(in, out);
        out.close();
    }
}

class Algorithm {
    void solve(InputReader ir, PrintWriter pw) {

        int [] hours = {0, 1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15, 20, 21, 22, 23};
        int [] minutes = {0, 10, 20, 30, 40, 50, 1, 11, 21, 31, 41, 51, 2, 12, 22, 32};
        String time = ir.next();
        int cHour = Integer.parseInt(time.substring(0, 2)), cMinute = Integer.parseInt(time.substring(3, 5));
        int count = 0, total = 0;

        while (cHour > hours[count]) count++;

        if (cHour == hours[count]) {
            if (cMinute <= minutes[count]) total = minutes[count] - cMinute;
            else {
                if (count == 15) total = 60 - cMinute;
                else total = 60 - cMinute + minutes[count + 1] + 60 * (hours[count + 1] - cHour - 1);
            }
        } else {
            if (cMinute <= minutes[count]) total = minutes[count] - cMinute + 60 * (hours[count] - cHour);
            else total = 60 - cMinute + minutes[count] + 60 * (hours[count] - cHour - 1);
        }

        pw.print(total);

    }

}

class InputReader {
    private BufferedReader reader;
    private StringTokenizer tokenizer;

    InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream), 32768);
        tokenizer = null;
    }

    String next() {
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    String nextLine(){
        String fullLine = null;
        while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                fullLine = reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return fullLine;
        }
        return fullLine;
    }

    String [] toArray() {
        return nextLine().split(" ");
    }

    int nextInt() {
        return Integer.parseInt(next());
    }
    double nextDouble() {
        return Double.parseDouble(next());
    }
    long nextLong() {
        return Long.parseLong(next());
    }

}


import java.io.PrintWriter;

import java.util.*;
import java.util.Arrays ;
import java .lang.String.* ;
import java .lang.StringBuilder ;

public class Test{
    static int pos = 0 ;
    static int  arr[] ;
  static LinkedList l1 = new  LinkedList() ;
static void find(int p ,char[]x,int put[],String s){
    int c= 0 ;
    for (int i = 0; i < s.length(); i++) {
        if(x[p]==s.charAt(i)){
        c++ ; }
    }
    put[p] = c ;
}
static int mode(int m ,int[]x ){
    int temp = 0 ;
    for (int i = x.length-1; i >=0; i--) {
        if(x[i]<=m){
            temp= x[i] ;
           /// break ;
             return m-temp ;

        }
    }
     return m-temp ;
}
static int mode2(int m ,int[]x ){
    int temp = 0 ;

    for (int i = x.length-1; i >=0; i--) {
        if(x[i]<=m){
            temp= x[i] ;
           /// break ;
             return x[i] ;

        }
    }
     return 0 ;
}
static int find(int x[],int temp){
    int j = 0 ;
    for (int i = x.length-1; i >=0; i--) {
        if(x[i]==temp) return j+1 ;
        j++ ;
    }
    return -1 ;
}
static String ch(long[]x,long b){
    for (int i = 0; i < x.length; i++) {
        if(x[i]==b)return "YES" ;
    }
    return "NO" ;
}

    public static void main(String[] args)  {

        Scanner in = new Scanner(System.in) ;
        PrintWriter pw = new PrintWriter(System.out);
        int n = in.nextInt() ;
        int m = in.nextInt() ;
        long k = in.nextLong() ;
        char y  ;
         if(k%2==0){
             y='R' ;
         }else y='L' ;
       long p = 2 ;
        if(k%2!=0)k++ ;
     long  add = 2*m ;
        long save1=0 ;
        long save2=0 ;
       boolean t= true;
         for (int i = 0; i < m&&t; i++) {
             long f= p ;
            for (int j = 0; j < n; j++) {
            if(f==k)  {
                save1= i+1 ;
                save2=j+1 ;
                t= false;
                break ;
            }
            f+=add;

        }
            p+=2 ;
         }

         System.out.println(save2+" "+save1+" "+ y);
 }
}


n, a, b = list(map(int, input().split()))

if b == 0:
	print(a)
	exit()

dx = b // abs(b)
for i in range(abs(b)):
	a += dx
	if a == 0:
		a = n
	elif a == n + 1:
		a = 1
print(a)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main implements Runnable {
  BufferedReader in;
  PrintWriter out;
  StringTokenizer tok = new StringTokenizer("");

  @Override
  public void run() {
    init();
    solve();
    out.close();
  }

  private void init() {
    in = new BufferedReader(new InputStreamReader(System.in));
    out = new PrintWriter(System.out);
  }

  private String readString() {
    while (!tok.hasMoreTokens()) {
      try {
        tok = new StringTokenizer(in.readLine());
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return tok.nextToken();
  }

  private int readInt() {
    return Integer.parseInt(readString());
  }

  public static void main(String[] args) {
    new Thread(new Main()).run();
  }

  private long readLong() {
    return Long.parseLong(readString());
  }

  private void solve() {
    int n = readInt();
    int start = readInt();
    int finish = readInt();
    int add = finish > 0 ? 1 : -1;
    if (finish < 0)
      finish = -finish;
    while (finish > 0) {
      start += add;
      finish--;
      if (start == n + 1)
        start = 1;
      if (start == 0)
        start = n;
    }
    out.print(start);
  }

}


import math
#n,k = map(int, input().strip().split(' '))
n=int(input())
#lst = list(map(int, input().strip().split(' ')))
if n==1 or n==2 or n==3:
    print(n)
else:
    p=math.sqrt(n)
    l=[1,n]
    c=1
    for j in range(2,int(p)+1):
        if n%j==0:
            l.insert(c,j)
            if n//j!=j:
                l.insert(c+1,n//j)
            c+=1
            while(True):
                if l[-1]%(j*j)==0:
                    del l[-1]
                else:
                    break
    i1=1
    i2=-1

    while(i1<len(l)):
        if l[i1]==l[-1]:
            break
        else:
            if l[i2]%l[i1]**2==0:
                del l[i2]
            else:
                if l[i2]<l[i1]**2:
                    i1+=1
                    i2=-1
                else:
                    i2-=1

    print(l[-1])

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * User: dmitry
 */
public class Main {
    public static InputStream is = System.in;
    public static BufferedReader br = new BufferedReader(new InputStreamReader(is));
    public static StringTokenizer stok;

    public static String next() {
        String nxt;
        try {
            if (stok != null && stok.hasMoreElements()) return stok.nextToken();
            if ((nxt = br.readLine()) != null) {
                stok = new StringTokenizer(nxt);
                if (stok.hasMoreElements()) return stok.nextToken();
            } else return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Integer nextInt() {
        return Integer.valueOf(next());
    }

    public static Long nextLong() {
        return Long.valueOf(next());
    }

    public static void main(String[] args) {
        long n = nextLong();
        List<Long> dels = getDels(n);
        if (!check(dels, n)) {
            System.out.println(n);
            return;
        }
        for (Long del : dels) {
            List<Long> mdels = getDels(del);
            if (!check(mdels, del)) {
                System.out.println(del);
                return;
            }
        }
    }

    public static List<Long> getDels(long n) {
        Set<Long> ll = new HashSet<>();
        Set<Long> dels = new HashSet<>();
        dels.add(1l);
        dels.add(n);
        for (long i = 2; i * i <= n; i++) {
            if (n % i == 0) {
                ll.add(i);
            }
        }
        dels.addAll(ll);
        for (Long aLong : ll) {
            long N = n;
            while (N % aLong == 0) {
                dels.add(N / aLong);
                N /= aLong;
            }
        }
        List<Long> ans = new ArrayList<>();
        ans.addAll(dels);
        Collections.sort(ans, new Comparator<Long>() {
            @Override
            public int compare(Long o1, Long o2) {
                return o2.compareTo(o1);
            }
        });
        return ans;
    }

    private static boolean check(List<Long> dels, long n) {
        for (Long del : dels) {
            long N = n;
            if (del > 1)
                if (N % del == 0) {
                    N /= del;
                    if (N % del == 0) {
                        return true;
                    }
                }
        }
        return false;
    }

}


import java.util.*;
import java.awt.Point;
import java.io.*;
public class Main {
static int bit[];
public static void main(String [] args)throws Exception{
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	int n=Integer.parseInt(br.readLine());
	bit=new int [n+1];
	point array[]=new point[n+1];
	array[0]=new point(Integer.MIN_VALUE,0);
	StringTokenizer st=new StringTokenizer(br.readLine());
	for(int i=1;i<=n;i++)
		array[i]=new point(Integer.parseInt(st.nextToken()),i);
		Arrays.sort(array,new X());
		long ans[]=new long[n];
		//for(int i=0;i<=n;i++)System.out.print(array[i].x+" "+array[i].y+" ");
		for(int i=1;i<=n;i++){
			int idx=array[i].y;
		  for(int j=1;j<=n-1;j++){
		  	if((idx-1)*j + 2 > n)break;
		  	ans[j]+=read((idx-1)*j + 2,Math.min(n,idx*j + 1));
		  }
		  update(idx,n);
		}
		System.out.println();
		//for(int i=0;i<n;i++)System.out.print(array[i].x+" "+array[i].y);
		StringBuilder sb=new StringBuilder();
		for(int i=1;i<=n-1;i++)
			sb.append(ans[i]+" ");
			System.out.print(sb);
}
static int less(int val){
	int ans=0;
	while(val > 0){
		ans+=bit[val];
		val-=val&(-val);
	}
	return ans;
}
static int read(int b,int a){
	return less(a) - less(b-1);
}
static void update(int idx,int max){
	while(idx <= max){
		bit[idx]+=1;
		idx+=idx&(-idx);
	}
}
static class point {
	int x;
	int y;
	public point(int x,int y){
		this.x=x;
		this.y=y;
	}
}
static class X implements Comparator<point>{
	public int compare(point a,point b){
		if(a.x > b.x)return 1;
			if(a.x < b.x)return -1;
			return a.y - b.y;
	}
}
}

import sys

def myargsort(a):
    b = list(zip(a, range(0, len(a))))
    b.sort()
    r = [pr[1] for pr in b]
    return r

fin = sys.stdin
n = int(fin.readline())
a = [int(number) for number in fin.readline().split()]
p = myargsort(a)
p.reverse()
j = 0
aib = [0] * (n + 1)

def ultb(x):
    return -(x ^ (-x)) // 2

def add(p, a, aib, n):
    while p <= n:
        aib[p] += a
        p += ultb(p)
def suma(p, aib):
    r = 0
    while p > 0:
        r += aib[p]
        p -= ultb(p)
    return r

for i in range(0, n):
    add(i + 1, 1, aib, n)
r = [0] * (n + 1)
for i in range(0, n):
    if i > 0 and a[i - 1] > a[i]:
        r[1] += 1
    while j < n and a[p[j]] == a[p[i]]:
        add(p[j] + 1, -1, aib, n)
        j += 1
    k = 2
    while k < n and p[i] * k + 1 < n:
        dr = min(n, p[i] * k + k + 1)
        st = p[i] * k + 2
        r[k] += suma(dr, aib) - suma(st - 1, aib)
        k += 1
print(*r[1:n])


#include <bits/stdc++.h>
using namespace std;
const int N = 505;
long long dp[N][N];
int mod, n, m, sum[N];
long long C(int a) { return (long long)a * (a - 1) / 2; }
long long dfs(int a, int b) {
  if (a < 0 || b < 0) return 0;
  if (a == 0 && b == 0) return 1;
  if (~dp[a][b]) return dp[a][b];
  dp[a][b] = 0;
  dp[a][b] += C(a) * dfs(a - 2, b) % mod;
  dp[a][b] += C(b) * dfs(a + 2, b - 2) % mod;
  dp[a][b] += a * b * dfs(a, b - 1) % mod;
  dp[a][b] %= mod;
  return dp[a][b];
}
int main() {
  char s[N];
  memset(dp, -1, sizeof dp);
  while (cin >> n >> m >> mod) {
    memset(sum, 0, sizeof sum);
    for (int i = 0; i < m; i++) {
      scanf("%s", s);
      for (int j = 0; j < n; j++) sum[j] += s[j] - '0';
    }
    int a = 0, b = 0;
    for (int i = 0; i < n; i++)
      if (sum[i] == 1)
        a++;
      else if (sum[i] == 0)
        b++;
    cout << dfs(a, b) << endl;
  }
  return 0;
}

from math import *
from collections import *
import sys
sys.setrecursionlimit(10**9)
dp = [[-1 for i in range(505)] for j in range(505)]
def memo(row,z,o):
	if(row == n):
		if(z == 0 and o == 0):
			return 1
		else:
			return 0
	if(dp[z][o] != -1): return dp[z][o]

	if(z > 1):
		dp[z][o] += (z*(z-1)//2)*(memo(row+1,z-2,o+2))
		dp[z][o] %= mod
	if(z >= 1 and o >= 1):
		dp[z][o] += (z*o)*(memo(row+1,z-1,o))
		dp[z][o] %= mod
	if(o > 1):
		dp[z][o] += (o*(o-1)//2)*(memo(row+1,z,o-2))
		dp[z][o] %= mod
	#print(row,z,o,dp[z][o])
	dp[z][o] += 1
	dp[z][o] %= mod
	return dp[z][o]%mod

n,m,mod = map(int,input().split())
a = []
for i in range(m):
    s = list(input())
    a.append(s)
#print(a)
ct = [0 for i in range(n)]
for i in range(m):
	for j in range(n):
		if(a[i][j] == '1'):
			ct[j] += 1

z = ct.count(0)
o = ct.count(1)
ans = memo(m,z,o)
print(ans%mod)


#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 100;
int main() {
  int flag = 0;
  long long n, a, b;
  cin >> n >> a >> b;
  long long x = a, y = b;
  if (a > b) {
    swap(a, b);
    flag = 1;
  }
  if (a * b > 6 * n) {
    printf("%lld\n", a * b);
    printf("%lld %lld\n", a, b);
    return 0;
  }
  long long ans = 0x3f3f3f3f3f3f3f3f, l = 0, r = 0;
  long long len = sqrt(6 * n) + 1;
  for (int i = a; i <= len + 5; i++) {
    if (6 * n % i == 0 && 6 * n / i >= b) {
      l = i;
      r = 6 * n / i;
      break;
    }
    y = 6 * n / i + 1;
    y = max(y, b);
    if (i * y < ans) {
      l = i;
      r = y;
      ans = l * r;
    }
  }
  if (flag) swap(l, r);
  printf("%lld\n", l * r);
  printf("%lld %lld\n", l, r);
  return 0;
}

n,a,b = map(int, input().split(' '))
A = 6*n
if a*b >= 6*n :
    print(a*b)
    print(a,b)
else :
    R = []
    temp = float("INF")
    for i in range(1, int(A**0.5)+2) :
        j = A//i
        if i*j < A : j+=1
        x = max([a,b,i,j])
        y = max(min(a,b) , min(i,j))
        if temp > x*y :
            temp = x*y
            if b>a : x,y = y,x
            R = [x,y, temp]
    print(R[2])
    print(R[0], R[1])


import sys,math
n,k=map(int,sys.stdin.readline().split())
if n<=2*k:
    print(-1)
else:
    ans=[]
    for i in range(n):

        for j in range(i+1,k+i+1):
            if j+1==n:
                ans.append([i+1,j+1])
            else:
                ans.append([i+1,((j+1)%n)])
    print(len(ans))
    for i in range(len(ans)):
        print(*ans[i])

Input: 5 1
445 223
Input: 8 8
Input: 7 4
Input: 8 1
Input: 8 6
Input: 7 6
4 1
Input: 5 5
Input: 1 1
Input: 5 2
Input: 2 0
Input: 3 2
Input: 6 6
1 1
Input: 5 0
Input: 7 3
2 1
Input: 3 3
Input: 5 3
Input: 2 2
Input: 4 1
Input: 7 7
Input: 8 7
Input: 6 2
Input: 4 4
Input: 6 1
Input: 6 4
Input: 1 0
Input: 7 0
Input: 6 0
Input: 8 5
Input: 8 2
Input: 4 2
609 305
Input: 5 4
Input: 8 0
Input: 2 1
Input: 4 0
5 2
Input: 4 3
Input: 7 2
Input: 7 5
Input: 3 1
999 500
Input: 8 3
Input: 7 1
Input: 8 4
3 1
Input: 3 0
Input: 6 5
Input: 6 3

#include <bits/stdc++.h>
using namespace std;
int n, k;
int main() {
  cin >> n >> k;
  int total = (n * (n - 1)) / 2;
  if (total >= n * k) {
    total = n * k;
    cout << total << "\n";
    int nod1 = 1;
    int nod2 = nod1 + 1;
    int cate = 0;
    while (total > 0) {
      cate++;
      if (nod2 > n) nod2 = 1;
      cout << nod1 << " " << nod2 << "\n";
      if (cate == k) {
        nod1++;
        nod2 = nod1 + 1;
        cate = 0;
      } else
        nod2++;
      total--;
    }
  } else
    cout << -1 << "\n";
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, x, chest = 0, bi = 0, back = 0;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> x;
    if (i % 3 == 1)
      chest += x;
    else if (i % 3 == 2)
      bi += x;
    else if (i % 3 == 0)
      back += x;
  }
  int m = max(chest, max(bi, back));
  if (m == chest)
    cout << "chest";
  else if (m == bi)
    cout << "biceps";
  else
    cout << "back";
  return 0;
}

biceps chest chest chest chest chest back chest biceps biceps back biceps chest chest chest chest biceps

import java.util.*;
public class p255a {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int N = in.nextInt();
		int[] arr = new int[3];
		for(int i = 0; i < N; i++)
			arr[i%3] += in.nextInt();

		if(arr[0] > arr[1] && arr[0] > arr[2])
			System.out.println("chest");
		else if(arr[1] > arr[2])
			System.out.println("biceps");
		else
			System.out.println("back");

	}
}


#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)
#from __future__ import print_function, division    #while using python2
# from itertools import accumulate
# from collections import defaultdict, Counter

def modinv(n,p):
    return pow(n,p-2,p)

def get_numbers(s):
    if len(s) == 1:
        return int(s)

    ans = 0
    n = len(s)
    for i in range(1, n):
        ans += (9 * (10 ** (max(0, i-2))))

    x = n-2
    for i in range(n):
        k = int(s[i])
        if i == 0:
            k -= 1
        # print("i = ", i, ", k = ", k)
        ans += (k * (10 ** x))
        x -= 1
        if x < 0:
            break
    if int(s[-1]) >= int(s[0]):
        ans += 1
    return ans

def main():
    #sys.stdin = open('input.txt', 'r')
    #sys.stdout = open('output.txt', 'w')

    # print(get_numbers(input()))

    l, r = [int(x) for x in input().split()]
    # print(get_numbers(str(l-1)))
    # print(get_numbers(str(r)))

    print(get_numbers(str(r)) - get_numbers(str(l-1)))

#------------------ Python 2 and 3 footer by Pajenegod and c1729-----------------------------------------
py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0
    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s
    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s:self.buffer.write(s.encode('ascii'))
            self.read = lambda:self.buffer.read().decode('ascii')
            self.readline = lambda:self.buffer.readline().decode('ascii')

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')

if __name__ == '__main__':
   main()

#include <bits/stdc++.h>
using namespace std;
long long calc(long long n) {
  if (n < 10) {
    return n;
  }
  long long ans = n / 10 + 9;
  long long l = n % 10;
  while (n > 9) {
    n = n / 10;
  }
  if (n > l) {
    ans--;
  }
  return ans;
}
int main() {
  long long l, r;
  cin >> l >> r;
  cout << calc(r) - calc(l - 1);
}


#include <bits/stdc++.h>
const int N = 200010;
int s, a[N], n;
int ans[N], sum;
int main() {
  int i, t;
  scanf("%d", &n);
  s = 0;
  for (i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    s += a[i];
  }
  sum = 0;
  for (i = 1; i <= n; i++) {
    if ((s - a[i]) % (n - 1) == 0) {
      t = (s - a[i]) / (n - 1);
      if (t == a[i]) {
        sum++;
        ans[sum] = i;
      }
    }
  }
  printf("%d\n", sum);
  for (i = 1; i < sum; i++) printf("%d ", ans[i]);
  if (sum > 0) printf("%d\n", ans[i]);
  return 0;
}

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class T1{
    public T1(){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int k = 0;
        long sum = 0;
        int arr[] = new int[n];
        int ans[] = new int[n];
        for(int i = 0; i < n; i++){
            arr[i] = s.nextInt();
            sum += arr[i];
        }
        for(int i = 0; i < n; i++){
            double res = 1.0 * (sum - arr[i]) / (n - 1);
            if(res == arr[i]){
                ans[k] = i + 1;
                k++;
            }
        }
        System.out.println(k);
        for(int i = 0; i < k; i++)
            System.out.print(ans[i] + " ");
    }
    public static void main(String args[]){
        T1 t1 = new T1();
    }
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  unsigned long long int a, b, c, d, t, i, br[1000], j;
  cin >> t;
  for (i = 0; i < t * t; i++) {
    {
      if (i < t)
        cin >> br[i];
      else
        cin >> c;
    }
    if (i == t + 2) a = sqrt((br[2] * br[1]) / c);
  }
  cout << a << " ";
  for (i = 1; i < t; i++) {
    cout << br[i] / a;
    if (i < t - 1) cout << " ";
  }
}

import java.util.Scanner;

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

            solve();

    }
    protected  static  void solve()
    {
        int n = sc.nextInt();
        long a[][] = new long[n][n];
       for(int i = 0; i < n; i++)
        {
            for(int j = 0;j<n;j++)
            {
                a[i][j] = sc.nextLong();
            }
        }
        long k= (long)Math.sqrt((a[0][1]*a[0][2])/a[1][2]);

        System.out.print(k+" ");
        for(int i = 1;i<n;i++)
            System.out.print(a[0][i]/k+" ");
        System.out.println();

    }
}


N = int(input())

def make_vowels(N):
    ans = ["aeiou", "eioua", "iouae", "ouaei", "uaeio"]
    vowels = "aeiou"
    m = 5
    while m < N:
        if N % m == 0 and N // m >= 5:
            break
        m += 1
    else:
        return print(-1)

    n = N // m
    for i in range(n):
        if i <= 4:
                ans[i] = ans[i]+(vowels[i]*(m-5))
        else:
            ans.append("aeiou"+"b"*(m-5))

    ans = "".join(ans)
    return print(ans)

make_vowels(N)


import java.util.Scanner;

public class Test{
    public static void main(String[] args){
        Scanner scan=new Scanner(System.in);
        int nb=scan.nextInt();
        int[] T=new int[]{15,14,12,13,8,9,10,11,0,1,2,3,4,5,6,7};
        System.out.println(T[nb]);
    }
}


n,m = list(map(int, input().split()))
avg = 0
def s(p):
	return p*(p+1)//2
for i in range(m):
	x,d = list(map(int, input().split()))
	avg += (n*x + max( d*s(n-1),  d*(s(n//2)+s((n-1)//2))))
	#print(avg)
print("%.15f" % (avg/n))

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll prog(ll n) { return n * (n + 1) / 2; }
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int n, m;
  cin >> n >> m;
  ll sum = 0;
  for (int i = 0; i < m; i++) {
    int x, d;
    cin >> x >> d;
    if (d < 0) {
      sum += n * x + 1LL * (prog(n / 2) + prog((n + 1) / 2 - 1)) * d;
    } else {
      sum += n * x + 1LL * prog(n - 1) * d;
    }
  }
  cout << fixed << setprecision(10) << double(sum) / double(n) << endl;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  string s;
  cin >> s;
  int n = s.length();
  double ans = 0.0;
  vector<int> all[26];
  for (int i = 0; i < s.length(); i++) {
    all[s[i] - 'a'].push_back(i);
  }
  for (int i = 0; i < 26; i++) {
    if (all[i].size() == 0) {
      continue;
    }
    double now = 0.0;
    for (int j = 1; j < n; j++) {
      int bo[26];
      for (int a = 0; a < 26; a++) {
        bo[a] = 0;
      }
      double here = 0.0;
      for (int a = 0; a < all[i].size(); a++) {
        int v = (int)(s[(all[i][a] + j) % n] - 'a');
        bo[v]++;
      }
      for (int a = 0; a < 26; a++) {
        if (bo[a] == 1) {
          here += (1.0 / (double)all[i].size());
        }
      }
      now = max(now, here * (double)all[i].size() / (double)n);
    }
    ans += now;
  }
  cout << fixed << setprecision(15) << ans << endl;
  return 0;
}

s=input()

d=dict()
mod=[]
mx=[]

for k in s:
	d[k]=[]
for i in range(len(s)):
	d[s[i]].append(i)
index=0
for k in d.keys():
	mod.append(d[k])

for k in mod:
	mxct=0
	ct=0
	x=[]
	for i in range(len(s)):
		ct=0
		dic=dict()
		for j in k:
			elt = s[(j+i)%(len(s))]
			if elt in dic.keys():
				dic[elt]+=1
			else:
				dic[elt]=1
		for r in dic.keys():
			if dic[r]==1:
				ct+=1
		mxct=max(ct,mxct)
	mx.append(mxct)
sm=0
for k in mx:
	sm+=k
print(sm/len(s))


#Circle of Numbers
import math

def centre(n, pts):
    x, y = 0, 0
    for j in [7,11,13,17,19,23,29,31,37,1193,1663,2711,4007,65537]:
        if math.gcd(n,j) == 1:
            for i in range(n):
                k = int(pts[i])
                x += k*math.cos(math.pi * 2*i*j/n)
                y += k*math.sin(math.pi * 2*i*j/n)
            if not (abs(x) < 0.000001 and abs(y) < 0.000001):
                return 'NO'
    return 'YES'

def strconv(s):
    return [char for char in s]

n = int(input())
pts = strconv(input())
print(centre(n,pts))

NO YES NO NO NO NO NO NO NO NO NO NO NO YES NO NO NO YES NO NO YES NO NO NO NO NO NO NO NO NO YES NO NO NO NO NO NO YES NO NO NO NO NO NO NO NO NO

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.util.*;

public class Main {
	public static double[] a = new double[100000];
	public static boolean[] flag = new boolean[100001];
	public static final double eps = 1e-8;
	public static void main(String args[]) {
		Scanner cin = new Scanner (new BufferedInputStream(System.in));
		PrintStream cout = System.out;
		int n=cin.nextInt();
		String s = cin.next();
		for(int i=0; i<n; i++) {
			a[i]=s.charAt(i)-'0';
			flag[i]=false;
		}
		for(int i=2; i<=n; i++) {
			if(flag[i] == true) continue;
			for(int j=i; j<n; j+=i) flag[j]=true;
			if((n%i) != 0) continue;
			for(int r=0; r<(n/i); r++) {
				double sum=0;
				for(int j=r; j<n; j+=(n/i)) sum+=a[j];
				sum/=i;
				for(int j=r; j<n; j+=(n/i)) a[j]-=sum;
			}
		}
		boolean bad = false;
		for(int i=0; i<n; i++) {
			if(a[i]>eps || a[i]<-eps) {
				bad=true;
				break;
			}
		}
		if(bad) cout.println("NO");
		else cout.println("YES");
	}
}


#include <bits/stdc++.h>
using namespace std;
pair<int, int> a[105];
bool cmp(pair<int, int> x, pair<int, int> y) { return x.first > y.first; }
int main() {
  int n, s = 0;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i].first;
    a[i].second = i;
    s += a[i].first;
  }
  if (a[1].first == 0 || s < n - 1)
    cout << -1;
  else {
    cout << n - 1 << '\n';
    sort(a + 2, a + n + 1, cmp);
    int uk = 1, r = 2;
    while (r <= n) {
      for (int j = 1; j <= a[uk].first && r <= n; j++, r++)
        cout << a[uk].second << ' ' << a[r].second << '\n';
      uk++;
    }
  }
  return 0;
}

import java.lang.*;
import java.util.*;
import java.util.stream.Collectors;
import java.io.*;

public class Equalize {
		static public class Pair
		{
			int i;
			int j;
			public Pair(int i, int j)
			{
				this.i=i;
				this.j=j;
			}
		}
		public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n= sc.nextInt();
		int[] ar = new int[n];
		int sum=0;
		for(int i=0;i<n;i++)
		{
			ar[i]=sc.nextInt();
			sum+=ar[i];
		}
		if(ar[0]==0 || sum<n-1)System.out.println(-1);
		else
		{
			List<Pair> list = new ArrayList<Pair>();
			int i=0,j=1;
			while(i<n)
			{
				while(j<n && ar[j]==0)j++;
				if(j==n) {
					i=j;
					break;
				}
				list.add(new Pair(i+1,j+1));
				ar[i]--;
				if(ar[i]==0)ar[i]=1001;
				i=j;
				j+=1;
			}

			i=1;j=0;
			//System.out.println(Arrays.toString(ar));
			while(j<n)
			{
				while(j<n &&  (ar[j]==0 || ar[j]==1001))j++;
				while(i<n && ar[i]!=0)i++;
				if(i==n || j==n)break;
				list.add(new Pair(j+1,i+1));
				ar[j]--;
				if(ar[j]==0)ar[j]=1001;
				i++;
			}
			System.out.println(list.size());
			for(i=0;i<list.size();i++)
				System.out.println(list.get(i).i+" "+list.get(i).j);

		}

		}
}


from bisect import bisect_left
n,k=map(int,input().split())
q="abcdefghijklmnopqrstuvwxyz"
a={i:[] for i in q}

for key,value in enumerate(input()):a[value].append(key)
#print(a)
def g(t):return [(t[i]+t[i-1])//2 for i in range(1,len(t))]    #类似于二分查找的思路 //便于快速确定位置
c={i:g(a[i]) for i in q}
#print(c)

for _ in range(n):
    s,t=0,input()
    lt=len(t)
    for key,value in enumerate(t):
        if a[value]:
            if c[value]:s+=abs(key-a[value][bisect_left(c[value],key)])
            else:s+=abs(key-a[value][0])
        else:
            s+=lt
    print(s)

9 9
vkontakte
vcontacte
vkontrakte
vkollapse
vkrokodile
vtopke
vkapuste
vpechke
vk
vcodeforcese

20 10
iwbiucrjoj
qvjewvdrgwgc
ewwqyhtdzakryafqaacimthycyasyb
cuoscayekvbsqokyfdmjnojkjennf
hkuv
jtdgbespjdtbc
geujitsrlqihoulvwuobnfospq
zqhnlqxacchxhyeehnpfwdjnwvj
xicsaoyfgtdbwqfrdgaiyn
atgshewfkuxaipizcdev
vp
yblkfmqsj
yevxolvycyrrooosberqzrabefdckg
rytykrlgttc
afphunqbtydppxotf
nkfoatpikdg
jwskqdsnymehilufkjzcjbwlixy
wswr
wsuhgjvzgppyeoxqrftpvmdlxqotl
yivyjfuqxstysxgmmqutmd
bymvqulyuzibelpuuwsoiuktv

10 20
owopujiohbocynvpllmk
yyprqugbejvhi
agrdbmotaastc
zesafjoocdjnxgse
r
enlfylphtqjnrbo
jphnoumpdrebxtgbch
fapki
hbfptfbjhio
sugzpa
qojcadybsjedi

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;

public class TyndexDotBrome {

    void run() {
        try {
            BufferedReader bfd = new BufferedReader(new InputStreamReader(
                    System.in));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                    System.out));
            String sp[] = bfd.readLine().split(" +");
            int n = Integer.parseInt(sp[0]);
            int i , j;
            long res;
            char[] uArr = bfd.readLine().toCharArray(), arr;

            @SuppressWarnings("unchecked")
            ArrayList<Integer>[] pos = new ArrayList[26];
            for(i=0; i<pos.length; ++i)
                pos[i] = new ArrayList<Integer>();
            for(i=0; i<uArr.length; ++i)
                pos[uArr[i]-'a'].add(i);
            for(i=0; i<n; ++i){
                arr = bfd.readLine().trim().toCharArray();
                res = 0;
                for(j=0; j<arr.length; ++j){
                    if(j<uArr.length && arr[j]==uArr[j]);
                    else {
                        if(pos[arr[j]-'a'].size()==0)
                            res += arr.length;
                        else {
                            int x = Collections.binarySearch(pos[arr[j]-'a'], j);
                            int insertPt = - x - 1;
                            if(insertPt!=0){
                                int plus = Integer.MAX_VALUE;
                                if(insertPt>0)
                                    plus = Math.min(plus, Math.abs(pos[arr[j]-'a'].get(insertPt-1)-j));
                                if(insertPt>=0 && insertPt<pos[arr[j]-'a'].size())
                                    plus = Math.min(plus, Math.abs(pos[arr[j]-'a'].get(insertPt)-j));
                                if(insertPt+1<pos[arr[j]-'a'].size())
                                    plus = Math.min(plus, Math.abs(pos[arr[j]-'a'].get(insertPt+1)-j));
                                res += plus;
                            } else {
                                res += Math.abs(pos[arr[j]-'a'].get(insertPt)-j);
                            }
                        }
                    }
                }
                out.write(res + "\n");
            }
            out.flush();
            out.close();
        } catch (Exception e) {

        }
    }

    public static void main(String[] args) {
        new TyndexDotBrome().run();
    }

}


#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 50 + 10;
int a1[MAX_N], a2[MAX_N], b[MAX_N];
int dp1[MAX_N], dp2[MAX_N], sum[MAX_N];
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n - 1; i++) cin >> a1[i];
  for (int i = 0; i < n - 1; i++) cin >> a2[i];
  for (int i = 0; i < n; i++) cin >> b[i];
  for (int i = 0; i < n; i++) {
    for (int j = i - 1; j >= 0; j--) {
      dp1[i] += a1[j];
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = i; j < n - 1; j++) {
      dp2[i] += a2[j];
    }
  }
  int ans = 0;
  int mini = INT_MAX, minI = -1;
  for (int i = 0; i < n; i++) {
    sum[i] = b[i] + dp1[i] + dp2[i];
    if (sum[i] < mini) {
      mini = sum[i];
      minI = i;
    }
  }
  ans += sum[minI];
  sum[minI] = INT_MAX;
  mini = INT_MAX, minI = -1;
  for (int i = 0; i < n; i++) {
    if (sum[i] < mini) {
      mini = sum[i];
      minI = i;
    }
  }
  ans += sum[minI];
  cout << ans << endl;
  return 0;
}

n = int(input())
a1 = [int(s) for s in input().split()]
a2 = [int(s) for s in input().split()]
b = [int(s) for s in input().split()]

sum = 0
for i in range(n-1):
    sum = sum + a2[i]

sum1 = min(sum + b[0], sum - a2[0] + a1[0] + b[1])
sum2 = max(sum + b[0], sum - a2[0] + a1[0] + b[1])

sum = sum - a2[0] + a1[0] + b[1]

for i in range(2, n):
    sum = sum + b[i] - b[i-1] + a1[i-1] - a2[i-1]
    if sum < sum1:
        sum2 = min(sum2,sum1)
        sum1 = sum
    else:
        sum2 = min(sum2, sum)

print(sum1+sum2)


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.BufferedOutputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Kattio in = new Kattio(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskAA solver = new TaskAA();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskAA {
        public void solve(int testNumber, Kattio in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();

            int[] ans = new int[n + 1];
            for (int i = 0; i < m; ++i) {
                int x = in.nextInt();
                for (int j = x; j <= n; ++j) {
                    if (ans[j] != 0) break;
                    ans[j] = x;
                }
            }

            for (int i = 1; i <= n; ++i)
                out.print(ans[i] + " ");
        }

    }

    static class Kattio extends PrintWriter {
        private BufferedReader r;
        private String line;
        private StringTokenizer st;
        private String token;

        public Kattio(InputStream i) {
            super(new BufferedOutputStream(System.out));
            r = new BufferedReader(new InputStreamReader(i));
        }

        public Kattio(InputStream i, OutputStream o) {
            super(new BufferedOutputStream(o));
            r = new BufferedReader(new InputStreamReader(i));
        }

        public int nextInt() {
            return Integer.parseInt(nextToken());
        }

        private String peekToken() {
            if (token == null)
                try {
                    while (st == null || !st.hasMoreTokens()) {
                        line = r.readLine();
                        if (line == null) return null;
                        st = new StringTokenizer(line);
                    }
                    token = st.nextToken();
                } catch (IOException e) {
                }
            return token;
        }

        private String nextToken() {
            String ans = peekToken();
            token = null;
            return ans;
        }

    }
}


from collections import Counter

def main():
    n, m = map(int, input().split())

    c = list(map(int, input().split()))

    sc = sorted(range(n), key=lambda x: c[x])
    mc = Counter(c).most_common(1)[0][1]

    print(n if mc <= n - mc else 2*(n - mc))

    for i in range(n):
        print(c[sc[i]], c[sc[i-mc]])

if __name__ == '__main__':
    main()

# Made By Mostafa_Khaled

#include <bits/stdc++.h>
using namespace std;
int a[5005];
int main() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> a[i];
  sort(a, a + n);
  int num = 0;
  for (int i = 0; i < n; i++) {
    if (a[i] != a[(i + (n / 2)) % n]) num++;
  }
  cout << num << endl;
  for (int i = 0; i < n; i++) {
    cout << a[i] << " " << a[(i + (n / 2)) % n] << endl;
  }
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
struct kor {
  int x, d;
};
int main(int argc, char *argv[]) {
  int n;
  int ind = 0;
  cin >> n;
  kor a[n];
  for (int i = 0; i < n; ++i) {
    cin >> a[i].x >> a[i].d;
  }
  for (int i = 0; i < n - 1; ++i) {
    for (int j = i + 1; j < n; ++j) {
      if ((a[i].x == (a[j].x + a[j].d)) && (a[j].x == (a[i].x + a[i].d))) {
        cout << "YES";
        ind = 1;
        j = n;
        i = n;
      }
    }
  }
  if (ind == 0) {
    cout << "NO";
  }
  return EXIT_SUCCESS;
}

YES YES NO NO YES NO YES NO YES NO NO NO YES YES YES NO YES YES NO NO NO NO YES YES YES NO YES YES YES NO NO YES YES YES YES YES NO NO YES NO YES YES YES NO NO NO NO YES YES YES NO NO YES YES YES YES YES NO NO NO YES YES NO NO NO NO NO YES YES YES NO NO NO YES NO YES YES NO NO NO NO YES NO YES YES YES NO

n=int(input())
a1=[]
a2=[]
for i in range(n):
	x,d=list(map(int,input().split()))
	a1.append(x)
	a2.append(d)

flag=1
for i in range(n):
	for j in range(i+1,n):
		if ((a1[i]+a2[i]==a1[j]) and (a1[j]+a2[j]==a1[i])):
			print("YES")
			flag=0
			break
	if(flag==0):
		break
if(flag==1):
	print("NO")


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.ObjectInputStream.GetField;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

	public class Q1 {

		static long MOD = 1000000007;
		static boolean b[], b1[], check;
		static ArrayList<Integer>[] amp, pa;
		static ArrayList<Pair>[] amp1;
		static ArrayList<Pair>[][] damp;
		static int left[],s[],right[],end[],sum[],dist[],cnt[],start[],color[],parent[],prime[],size[];
		static long ans = 0,k;
		static int p = 0;
		static FasterScanner sc = new FasterScanner(System.in);
		static Queue<Integer> queue = new LinkedList<>();
		static PriorityQueue<Integer> pq;
		static BufferedWriter log;
		static HashSet<Integer>[] hs;
		static HashMap<String,Integer> hm;
		static HashMap<Pair,Integer> hmp;
		static Stack<Integer> st;
		static boolean boo[][];
		static Pair prr[];
		static long parent1[],parent2[],size1[],size2[],arr1[],SUM[],MAX[];
		static int arr[];
		public static void main(String[] args) throws Exception {
	    	/*new Thread(null, new Runnable() {
				public void run() {
					try {

				} catch (Exception e) {
						System.out.println(e);
					}
				}
			}, "1", 1 << 26).start();*/
			soln();
		}
		static long dp[][];
		static int N,K,T;
		static int time = 0;
		static int cost[][];
		static boolean b11[];
		static HashMap<Pair,Integer> h = new HashMap<>();
		static long ans1;
		static long ans2;
		static ArrayList<Integer> ampp;
		public static void soln() throws IOException {
			//FasterScanner in = new FasterScanner(new FileInputStream("C:\\Users\\Admin\\Desktop\\QCL.txt"));
			//PrintWriter out = new PrintWriter("C:\\Users\\Admin\\Desktop\\A1.txt");
			log = new BufferedWriter(new OutputStreamWriter(System.out));
			long l = sc.nextLong(), r = sc.nextLong();
			String str = Long.toBinaryString(r);
			String str2 = Long.toBinaryString(l);
			StringBuilder sb = new StringBuilder();
			sb.append(str2);
			while(sb.length()!=str.length()) sb.insert(0, 0);
			str2 = sb.toString();
			sb = new StringBuilder();
			if(l==r){
				System.out.println(0);
				return;
			}
			boolean b = false, c = false;;
			for(int i = 0; i< str.length();i++){
				//System.out.println(str.charAt(i)+" "+str2.charAt(i));
				if(str.charAt(i)=='1'){
					if(str2.charAt(i)=='1'){
						if(c){
							for(int j = i;j<str.length();j++) sb.append('1');
							break;
						}
						else sb.append('0');
					}
					else{
						b = true;
						c = true;
						sb.append('1');
					}
				}
				else{
					if(str2.charAt(i)=='1') sb.append(1);
					else{
						if(b){
						for(int j = i;j<str.length();j++) sb.append('1');
						break;
						}
						else sb.append('0');
					}
				}
			}
			//System.out.println(sb);
			int cnt = 0;
			long ans = 0;
			for(int j = sb.length()-1;j>=0;j--){
				if(sb.charAt(j)=='1'){
					ans += (long)Math.pow(2, cnt);
				}
				//System.out.println(ans);
				cnt++;
			}
			System.out.println(ans);
			log.close();
			//out.close();
		}
		static boolean check(char c){
			if(c=='a' || c=='e' || c=='i' || c=='y' || c=='u' || c=='o') return true;
			return false;
		}
		static void bfs(int x){

		}
		static void dfs(int x){
			b[x] = true;
			if(amp[x].size()%2==1) p++;
			for(int p:amp[x]){
				if(!b[p]){
					dfs(p);
				}
			}
		}
		static long comp(long n, long m){
			int l = Math.max(Long.toBinaryString(n).length(),Long.toBinaryString(m).length());
			System.out.println((m&(n^MAX[l]))+" "+(((m^MAX[l])&n)));
			return 2*((m&(n^MAX[l]))+(((m^MAX[l])&n)));
		}
		static void recur(int n, int m, int k){
			if(n<0 || m<0) return;
			if(k==0){
				p++;
				return;
			}
			recur(n-k,m,k-1);
			recur(n,m-k,k-1);
			return;
		}
		public static void buildWeightedGraph(int n){
			for(int i =0 ;i< n; i++){
				int x = sc.nextInt(), y = sc.nextInt(), w = sc.nextInt();
				amp1[--x].add(new Pair(--y,w));
				amp1[y].add(new Pair(x,w));
			}
		}

		public static void seive(int n){
			b = new boolean[(n+1)];
			Arrays.fill(b, true);
			b[1] = false;
			for(int i = 2;i*i<=n;i++){
				if(b[i]){
					for(int p = 2*i;p<=n;p+=i){
						b[p] = false;
					}
				}
			}
			/*for(int i = 2;i<=n;i++){
				if(b[i]) prime[i] = i;
			}*/
		}

		static class Graph{
			int vertex;
			int weight;
			Graph(int v, int w){
				vertex = v;
				weight = w;
			}
		}
		static class Pair implements Comparable<Pair> {
			int u;
			int v;
			public Pair(){
				u = 0;
				v = 0;
			}
			public Pair(int u, int v) {
				this.u = u;
				this.v = v;
			}
			public int hashCode() {
				int hu = (int) (u ^ (u >>> 32));
				int hv = (int) (v ^ (v >>> 32));
				return 31*hu + hv;
			}

			public boolean equals(Object o) {
				Pair other = (Pair) o;
				return (u == other.u && v == other.v);
			}

			public int compareTo(Pair other) {
				return Long.compare(u, other.u) != 0 ? (Long.compare(u, other.u)) : (Long.compare(v, other.v));
			}

			public String toString() {
				return "[u=" + u + ", v=" + v + "]";
			}
		}

		public static void buildGraph(int n){
			for(int i =0;i<n;i++){
				int x = sc.nextInt()-1, y = sc.nextInt()-1;
				amp[x].add(y);
				amp[y].add(x);
			}
		}

		public static int getParent(long x){
			while(parent[(int) x]!=x){
				parent[ (int) x] = parent[(int) parent[ (int) x]];
				x = parent[ (int) x];
			}
			return (int) x;
		}
		static long min(long a, long b, long c){
			if(a<b && a<c) return a;
			if(b<c) return b;
			return c;
		}
		/*

		static class Pair3{
			int x, y ,z;
			Pair3(int x, int y, int z){
				this.x = x;
				this.y = y;
				this.z = z;
			}
		}*/
		static int sum(int n){
			String str = Integer.toString(n);
			int cnt = 0;
			for(int i = 0; i< str.length();i++){
				cnt+=(str.charAt(i)-'0');
			}
			return cnt;
		}
		 static void KMPSearch(String pat, String txt)
		    {
		        int M = pat.length();
		        int N = txt.length();

		        // create lps[] that will hold the longest
		        // prefix suffix values for pattern
		        int lps[] = new int[M];
		        int j = 0;  // index for pat[]

		        // Preprocess the pattern (calculate lps[]
		        // array)
		        computeLPSArray(pat,M,lps);

		        int i = 0;  // index for txt[]
		        while (i < N)
		        {
		            if (pat.charAt(j) == txt.charAt(i))
		            {
		                j++;
		                i++;
		            }
		            if (j == M)
		            {
		               // parent.add((i-j));
		                j = lps[j-1];
		            }

		            // mismatch after j matches
		            else if (i < N && pat.charAt(j) != txt.charAt(i))
		            {
		                // Do not match lps[0..lps[j-1]] characters,
		                // they will match anyway
		                if (j != 0)
		                    j = lps[j-1];
		                else
		                    i = i+1;
		            }
		        }
		    }
		 static void computeLPSArray(String pat, int M, int lps[])
		    {
		        // length of the previous longest prefix suffix
		        int len = 0;
		        int i = 1;
		        lps[0] = 0;  // lps[0] is always 0

		        // the loop calculates lps[i] for i = 1 to M-1
		        while (i < M)
		        {
		            if (pat.charAt(i) == pat.charAt(len))
		            {
		                len++;
		                lps[i] = len;
		                i++;
		            }
		            else  // (pat[i] != pat[len])
		            {
		                // This is tricky. Consider the example.
		                // AAACAAAA and i = 7. The idea is similar
		                // to search step.
		                if (len != 0)
		                {
		                    len = lps[len-1];

		                    // Also, note that we do not increment
		                    // i here
		                }
		                else  // if (len == 0)
		                {
		                    lps[i] = len;
		                    i++;
		                }
		            }
		        }
		    }
		private static void permutation(String prefix, String str) {
		    int n = str.length();
		    if (n == 0); //hs.add(prefix);
		    else {
		        for (int i = 0; i < n; i++)
		            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
		    }
		}
		public static char give(char c1,char c2){
			if(c1!='a' && c2!='a') return 'a';
			if(c1!='b' && c2!='b') return 'b';
			return 'c';
		}

		public static void buildTree(int n){
			int arr[] = sc.nextIntArray(n);
			for(int i = 0;i<n;i++){
				int x = arr[i]-1;
				amp[i+1].add(x);
				amp[x].add(i+1);
			}
		}

		static class SegmentTree {
			boolean st[];
			boolean lazy[];

			SegmentTree(int n) {
				int size = 4 * n;
				st = new boolean[size];
				Arrays.fill(st, true);
				lazy = new boolean[size];
				Arrays.fill(lazy, true);
				//build(0, n - 1, 1);
			}

			/*long[] build(int ss, int se, int si) {
				if (ss == se) {
					st[si][0] = 1;
					st[si][1] = 1;
					st[si][2] = 1;
					return st[si];
				}
				int mid = (ss + se) / 2;
				long a1[] = build(ss, mid, si * 2), a2[] = build(mid + 1, se,
						si * 2 + 1);
				long ans[] = new long[3];
				if (arr[mid] < arr[mid + 1]) {
					ans[1] = Math.max(a2[1], Math.max(a1[1], a1[2] + a2[0]));
					if (a1[1] == (mid - ss + 1))
						ans[0] = ans[1];
					else
						ans[0] = a1[0];
					if (a2[2] == (se - mid))
						ans[2] = ans[1];
					else
						ans[2] = a2[2];
				} else {
					ans[1] = Math.max(a1[1], a2[1]);
					ans[0] = a1[0];
					ans[2] = a2[2];
				}
				st[si] = ans;
				return st[si];
			}*/

			void update(int si, int ss, int se, int idx, long x) {
				if (ss == se) {
					//arr[idx] += val;
					st[si]=false;
				}
				else {
					int mid = (ss + se) / 2;
					if(ss <= idx && idx <= mid)
			        {
			             update(2*si, ss, mid, idx, x);
			        }
			        else
			        { update(2*si+1, mid+1, se, idx, x);
			        }
					st[si] = st[2*si]|st[2*si+1];
				}
			}
			/*boolean get(int qs, int qe, int ss, int se, int si){
				if(qs>se || qe<ss) return 0;
				if (qs <= ss && qe >= se) {
					return st[si];
				}
				int mid = (ss+se)/2;
				return get(qs, qe, ss, mid, si * 2)+get(qs, qe, mid + 1, se, si * 2 + 1);
			}*/
			void updateRange(int node, int start, int end, int l, int r, boolean val)
			{
			    if(!lazy[node])
			    {
			        // This node needs to be updated
			        st[node] = lazy[node];    // Update it
			        if(start != end)
			        {
			            lazy[node*2] = lazy[node];                  // Mark child as lazy
			            lazy[node*2+1] = lazy[node];                // Mark child as lazy
			        }
			        lazy[node] = true;                                  // Reset it
			    }
			    if(start > end || start > r || end < l)              // Current segment is not within range [l, r]
			        return;
			    if(start >= l && end <= r)
			    {
			        // Segment is fully within range
			        st[node] =  val;
			        if(start != end)
			        {
			            // Not leaf node
			            lazy[node*2] = val;
			            lazy[node*2+1] = val;
			        }
			        return;
			    }
			    int mid = (start + end) / 2;
			    updateRange(node*2, start, mid, l, r, val);        // Updating left child
			    updateRange(node*2 + 1, mid + 1, end, l, r, val);   // Updating right child
			    st[node] = st[node*2] | st[node*2+1];        // Updating root with max value
			}

			boolean queryRange(int node, int start, int end, int l, int r)
			{
			    if(start > end || start > r || end < l)
			        return false;         // Out of range
			    if(!lazy[node])
			    {
			        // This node needs to be updated
			        st[node] = lazy[node];            // Update it
			        if(start != end)
			        {
			            lazy[node*2] = lazy[node];         // Mark child as lazy
			            lazy[node*2+1] = lazy[node];    // Mark child as lazy
			        }
			        lazy[node] = true;                 // Reset it
			    }
			    if(start >= l && end <= r)             // Current segment is totally within range [l, r]
			        return  st[node];
			    int mid = (start + end) / 2;
			    boolean p1 = queryRange(node*2, start, mid, l, r);         // Query left child
			    boolean b = queryRange(node*2 + 1, mid + 1, end, l, r); // Query right child
			    return (p1 | b);
			}
			void print() {
				for (int i = 0; i < st.length; i++) {
					System.out.print(st[i]+" ");
				}
				System.out.println();
			}
		}
		static int convert(int x){
			int cnt = 0;
			String str = Integer.toBinaryString(x);
			//System.out.println(str);
			for(int i = 0;i<str.length();i++){
				if(str.charAt(i)=='1'){
					cnt++;
				}
			}
			int ans = (int) Math.pow(3, 6-cnt);
			return ans;
		}
		static class Node2{
			Node2 left = null;
			Node2 right = null;
			Node2 parent = null;
			int data;
		}
		static class BinarySearchTree{
			Node2 root = null;
			int height = 0;
			int max = 0;
			int cnt = 1;
			ArrayList<Integer> parent = new ArrayList<>();
			HashMap<Integer, Integer> hm = new HashMap<>();
			public void insert(int x){
				Node2 n = new Node2();
				n.data = x;
				if(root==null){
					root = n;
				}
				else{
					Node2 temp = root,temb = null;
					while(temp!=null){
						temb = temp;
						if(x>temp.data) temp = temp.right;
						else temp = temp.left;
					}
					if(x>temb.data) temb.right = n;
					else temb.left = n;
					n.parent = temb;
					parent.add(temb.data);
				}
			}
			public Node2 getSomething(int x, int y, Node2 n){
				if(n.data==x || n.data==y) return n;
				else if(n.data>x && n.data<y) return n;
				else if(n.data<x && n.data<y) return getSomething(x,y,n.right);
				else return getSomething(x,y,n.left);
			}
			public Node2 search(int x,Node2 n){
				if(x==n.data){
					max = Math.max(max, n.data);
					return n;
				}
				if(x>n.data){
					max = Math.max(max, n.data);
					return search(x,n.right);
				}
				else{
					max = Math.max(max, n.data);
					return search(x,n.left);
				}
			}
			public int getHeight(Node2 n){
				if(n==null) return 0;
				height = 1+ Math.max(getHeight(n.left), getHeight(n.right));
				return height;
			}
		}
		static long findDiff(long[] arr, long[] brr, int m){
			int i = 0, j = 0;
			long fa = 1000000000000L;
			while(i<m && j<m){
				long x = arr[i]-brr[j];
				if(x>=0){
					if(x<fa) fa = x;
					j++;
				}
				else{
					if((-x)<fa) fa = -x;
					i++;
				}
			}
			return fa;
		}
		public static long max(long x, long y, long z){
			if(x>=y && x>=z) return x;
			if(y>=x && y>=z) return y;
			return z;
		}

		static long modInverse(long a, long mOD2){
		            return  power(a, mOD2-2, mOD2);
		}
		static long power(long x, long y, long m)
		{
		    if (y == 0)
		        return 1;
		    long p = power(x, y/2, m) % m;
		    p = (p * p) % m;

		    return (y%2 == 0)? p : (x * p) % m;
		}
		static long power2(long x,BigInteger y,long m){
			long ans = 1;
			BigInteger two = new BigInteger("2");
			while(y.compareTo(BigInteger.ZERO)>0){
				if(y.getLowestSetBit()==y.bitCount()){
					x = (x*x)%MOD;
					y = y.divide(two);
				}
				else{
					ans = (ans*x)%MOD;
					y = y.subtract(BigInteger.ONE);
				}
			}
			return ans;
		}
		static BigInteger power2(BigInteger x, BigInteger y, BigInteger m){
			BigInteger ans = new BigInteger("1");
			BigInteger one  = new BigInteger("1");
			BigInteger two  = new BigInteger("2");
			BigInteger zero  = new BigInteger("0");
			while(y.compareTo(zero)>0){
				//System.out.println(y);
				if(y.mod(two).equals(one)){
					ans = ans.multiply(x).mod(m);
					y = y.subtract(one);
				}
				else{
					x = x.multiply(x).mod(m);
					y = y.divide(two);
				}
			}
			return ans;
		}
		static BigInteger power(BigInteger x, BigInteger y, BigInteger m)
		{
		    if (y.equals(0))
		        return (new BigInteger("1"));
		    BigInteger p = power(x, y.divide(new BigInteger("2")), m).mod(m);
		    p = (p.multiply(p)).mod(m);

		    return (y.mod(new BigInteger("2")).equals(0))? p : (p.multiply(x)).mod(m);
		}
		static long d,x,y;
		public static void extendedEuclidian(long a, long b){
			if(b == 0) {
		        d = a;
		        x = 1;
		        y = 0;
		    }
		    else {
		        extendedEuclidian(b, a%b);
		        int temp = (int) x;
		        x = y;
		        y = temp - (a/b)*y;
		    }
		}

		public static long gcd(long n, long m){
			if(m!=0) return gcd(m,n%m);
			else return n;
		}

		static BufferedReader reader;
	    static StringTokenizer tokenizer;
	    static PrintWriter writer;

	    static class FasterScanner {

			private final InputStream stream;
			private final byte[] buf = new byte[8192];
			private int curChar, snumChars;
			private SpaceCharFilter filter;

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

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

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

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

			public int[] nextIntArray(int n) {
				int a[] = new int[n];
				for (int i = 0; i < n; i++) {
					a[i] = nextInt();
				}
				return a;
			}

			public long[] nextLongArray(int n) {
				long a[] = new long[n];
				for (int i = 0; i < n; i++) {
					a[i] = nextInt();
				}
				return a;
			}

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

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

			public boolean isSpaceChar(int c) {
				if (filter != null)
					return filter.isSpaceChar(c);
				return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
			}

			private boolean isEndOfLine(int c) {
				return c == '\n' || c == '\r' || c == -1;
			}

			public interface SpaceCharFilter {
				public boolean isSpaceChar(int ch);
			}
		}
	}

def bin(a):
    if a <= 1:
        return a
    else:
        return 10*bin(a//2)+a%2

def convBin(a):
    k,i = 0,0
    while a!=0:
        k += (a%10)*int((2**i))
        a //= 10
        i += 1
    return k

def maxi(a,b):
    if a == b:
        return 0
    elif a+1 == b:
        return a^b
    elif a+2 == b:
        x = a^(a+1)
        y = a^(a+2)
        z = (a+1)^(a+2)
        return max(max(x,y),z)
    else:
        x = str(bin(a^b))
        y = '1'*len(x)
        return convBin(int(y))
a = list(map(int,input().split()))
print(maxi(a[0],a[1]))


x, t, a, b, da, db = (int(q) for q in input().split())
if (x in (a - da * i + b - db * j for i in range(t) for j in range(t)) or
    (a >= x and (a - x) % da == 0 and (a - x) // da < t) or
    (b >= x and (b - x) % db == 0 and (b - x) // db < t) or
    x == 0):
	print('YES')
else:
	print('NO')

30 5 20 20 20 5
```

Note that each sample input consists of six integers separated by whitespace, in the format `x t a b da db`, where `x` is the number of points Valera wants to get, `t` is the duration of the contest in minutes, `a` and `b` are the initial costs of the two problems, and `da` and `db` are the number of points each problem loses per minute.

NO YES YES YES YES YES YES YES YES YES NO YES NO NO YES YES YES YES NO NO NO YES YES YES NO NO NO YES YES NO NO YES YES YES YES YES YES YES YES YES NO YES YES NO YES NO YES YES YES YES YES NO

import java.util.Scanner;

public class TwoProblems {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner input = new Scanner(System.in);
		int x = input.nextInt();
		int t = input.nextInt();
		int a = input.nextInt();
		int b = input.nextInt();
		int da = input.nextInt();
		int db = input.nextInt();
	  int total1 = a;
	  int total2 = b;
		for(int i=0; i<t;i++){
	        //	System.out.println(total1 + " " + total2);
	        	for(int j=0; j<t;j++){
	        		if(total1+total2==x){
	        			System.out.println("YES");
	        			return;
	        		}
	        		if(total1+total2 < x)break;
	        		total2-=db;
	        		//System.out.println(total1 + " " + total2);
	        	}
	        	total2 = b;
	        	total1 -=da;
	        	if(total1+total2<x)break;
		}
		 total1 = a;
		 total2=b;
		for(int i=0; i<t;i++){
			if(total1==x){
				System.out.println("YES");
				return;
			}
			if(total1<x)break;
		  total1-=da;
		}
		for(int i=0; i<t;i++){
			if(total2==x){
				System.out.println("YES");
				return ;
			}
			if(total2<x)break;
			total2-=db;
		}
		if(x!=0)System.out.println("NO");
		else
			System.out.println("YES");
	}

}


#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int t = 1;
  while (t--) {
    long long int n, m;
    cin >> n >> m;
    char M[n][m];
    for (long long int i = 0; i < n; i++) {
      for (long long int j = 0; j < m; j++) {
        cin >> M[i][j];
      }
    }
    int ans = 0;
    for (int i = 0; i < n; ++i) {
      bool wasBest = false;
      for (int j = 0; j < m; ++j) {
        bool isBest = true;
        for (int k = 0; k < n; ++k)
          if (M[k][j] > M[i][j]) isBest = false;
        if (isBest) wasBest = true;
      }
      if (wasBest) ans++;
    }
    cout << ans;
  }
  return 0;
}

n,m=map(int,input().split())
a=list()
b=list()
c=list()
for i in range(n):
    a.append([int(i) for i in list(input())])
for i in range(m):
    x=0
    for j in range(n):
        if(a[j][i]>x):
            x=a[j][i]
            b=list()
            b.append(j)
        elif(a[j][i]==x):
            b.append(j)
    c+=b
print(len(set(c)))


"""This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead."""
from math import gcd
n, k = map(int, input().split())
a, b = map(int, input().split())
lll = [a + b, abs(a - b), k - a - b, k - abs(a - b)]
x, y = n * k, 0
for ll in lll:
  for i in range(n):
    l = ll + i * k
    c = n * k // gcd(l, n * k)
    if c < x: x = c
    if c > y: y = c
print(x, y)

42 81
       1 51
```

Note that these are just random sample inputs, and not necessarily representative of all possible inputs that conform to the given problem description.

#include <bits/stdc++.h>
using namespace std;
long long INF = 1e18;
long long x = INF;
long long y = -INF;
long long nod(long long a, long long b) {
  while (a > 0 && b > 0) {
    long long c = a % b;
    a = b;
    b = c;
  }
  return a + b;
}
void f(long long start, long long b, long long n, long long k) {
  long long l1 = -1, l2 = -1, k1, k2;
  for (int l = 1; l <= k; l++) {
    if (start + l - ((start + l - 1) / k * k + 1) == b) {
      l1 = l;
    }
    if (((start + l - 1) / k + 1) * k + 1 - (start + l) == b) {
      l2 = l;
    }
  }
  for (int i = 0; i < n; i++) {
    if (l1 != -1) {
      k1 = (n * k) / nod(i * k + l1, n * k);
      x = min(x, k1);
      y = max(y, k1);
    }
    if (l2 != -1) {
      k2 = (n * k) / nod(i * k + l2, n * k);
      x = min(x, k2);
      y = max(y, k2);
    }
  }
}
int main() {
  long long n, k, a, b;
  cin >> n >> k;
  cin >> a >> b;
  f(a + 1, b, n, k);
  f(k + 1 - a, b, n, k);
  std::cout << x << ' ' << y;
}


n = int(input())
str = input()
difficulty = []
difficulty = str.split()
flag = 1
for i in difficulty:
    if i == '1':
        print("HARD")
        flag = 0
        break

if(flag ==1):
    print("EASY")

'''
3
0 0 1

HARD

1
0

EASY

'''

HARD EASY HARD HARD HARD HARD HARD HARD HARD HARD EASY EASY EASY HARD EASY HARD HARD HARD EASY HARD HARD HARD HARD HARD EASY HARD HARD HARD EASY HARD HARD HARD EASY HARD HARD HARD EASY HARD EASY EASY EASY EASY HARD HARD HARD HARD HARD HARD HARD HARD

#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int n, m;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> m;
    if (m == 1) {
      cout << "HARD";
      return 0;
    }
  }
  cout << "EASY";
}


//package graphs;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class PW {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FastReader s = new FastReader();

		int n=s.nextInt();

		if(n<=5)
		{
			System.out.println(-1);
			for(int i=1;i<=n-1;i++)
			{
				System.out.println(1+" "+(i+1));
			}
		}
		else
		{

			System.out.println(1+" "+2);
			System.out.println(2+" "+4);
			System.out.println(2+" "+3);
			n-=3;
			int st=5;
			for(int i=1;i<=n-1;i++)
			{
				System.out.println(3+" "+(st++));
			}
			n+=3;
			for(int i=1;i<=n-1;i++)
			{
				System.out.println(1+" "+(i+1));
			}
		}

	}

	public static long  solve(long n)
	{
		long sum=0;
		while(true)
		{
			sum=0;
			long t=n;
			while(t!=0)
			{
				sum=sum+t%10;
				t=t/10;
			}
			long ans=gcd(n,sum);
			if(ans>1)
				return n;
			n++;
		}

	}

	static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(
                new InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() { return Integer.parseInt(next()); }

        long nextLong() { return Long.parseLong(next()); }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

	public static long solve(int n, int r)
    {

        long p = 1, k = 1;
        if (n - r < r) {
            r = n - r;
        }

        if (r != 0) {
            while (r > 0) {
                p *= n;
                k *= r;

                long m = __gcd(p, k);

                p /= m;
                k /= m;

                n--;
                r--;
            }

        }
        else {
            p = 1;
        }

        //System.out.println(p);
        return p;
    }

	public static long gcd(long a,long b)
	{
		if(a==0||b==0)
			return a+b;
		return gcd(b,(a%b));
	}

	public static long __gcd(long n1, long n2)
    {
        long gcd = 1;

        for (int i = 1; i <= n1 && i <= n2; ++i) {
            // Checks if i is factor of both integers
            if (n1 % i == 0 && n2 % i == 0) {
                gcd = i;
            }
        }
        return gcd;
    }

	public static boolean prime(int n)
	{
		if(n<=2)
			return true;

		for(int i=2;i<=Math.sqrt(n);i++)
		{
			if(n%i==0)
				return false;
		}

		return true;

	}
	public static long fastExpo(long a,long n,long mod){
        if (n == 0)
            return 1;
        else{
            long x = fastExpo(a,n/2,mod);
            if ((n&1) == 1){
                return (((a*x)%mod)*x)%mod;
            }
            else{
                return (((x%mod)*(x%mod))%mod)%mod;
            }
        }
    }
}
class pair{
	//public:
		long f;
		long s;
		pair(long x,long y)
		{
			f=x;
			s=y;
		}

}

#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int TESTS = 1;
  while (TESTS--) {
    int i, n;
    cin >> n;
    if (n < 6)
      cout << "-1" << endl;
    else {
      cout << "1 3" << endl << "1 2" << endl << "1 4" << endl;
      for (i = 5; i < n + 1; i++) cout << "2 " << i << endl;
    }
    for (i = 2; i < n + 1; i++) cout << "1 " << i << endl;
  }
}


import java.util.Scanner;

public class Main20200817 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] line1 = scanner.nextLine().split(" ");
        String[] line2 = scanner.nextLine().split(" ");
        scanner.close();
        int length = Integer.parseInt(line1[0]);
        int inputMin = Integer.parseInt(line1[1]);
        int[] ints = new int[line2.length];
        for (int i = 0; i < ints.length; i++) {
            ints[i] = Integer.parseInt(line2[i]);
        }
        cal(inputMin, ints);
    }

    private static void cal(int inputMin, int[] ints) {
        int result = inputMin;
        for (int i = 0; i < ints.length; i++) {
            if (ints[i] < inputMin) {
                result--;
            } else if (ints[i] == inputMin) {
                result++;
            }
        }
        System.out.println(result);
    }
}

7 4
```

Each sample input consists of two integers `n` and `x`, separated by a space, representing the size of the set and the desired MEX, respectively. The second line contains `n` distinct non-negative integers not exceeding 100 that represent the set.

#include <bits/stdc++.h>
using namespace std;
int s[105];
int main() {
  int n, x;
  while (cin >> n >> x) {
    for (int i = 0; i < n; i++) {
      cin >> s[i];
    }
    sort(s, s + n);
    int index = lower_bound(s, s + n, x) - s;
    if (s[index] == x) {
      cout << 1 + x - index << endl;
    } else {
      cout << x - index << endl;
    }
  }
  return 0;
}


#include <bits/stdc++.h>
const int N = 1e5 + 7;
using namespace std;
vector<int> ans, a[N];
int us[N], need[N];
int x, i, j, k, n, m;
void dfs(int x) {
  us[x] = 1;
  for (int i = 0; i < a[x].size(); ++i)
    if (us[a[x][i]] == 1) {
      cout << -1;
      exit(0);
    } else if (us[a[x][i]] == 2)
      continue;
    else
      dfs(a[x][i]);
  us[x] = 2;
  ans.push_back(x);
}
int main() {
  cin >> n >> k;
  for (int i = 0; i < k; ++i) cin >> need[i], need[i]--;
  for (int i = 0; i < n; ++i) {
    cin >> m;
    for (int j = 0; j < m; ++j) cin >> x, a[i].push_back(x - 1);
  }
  for (int i = 0; i < k; ++i)
    if (!us[need[i]]) dfs(need[i]);
  cout << ans.size() << "\n";
  for (int i = 0; i < ans.size(); ++i) cout << ans[i] + 1 << ' ';
}

f = lambda: map(int, input().split())
g = lambda: [[] for x in range(n)]
n, k = f()
n += 1

s, p = [], list(f())
c, d = [0] * n, [0] * n
u, v = g(), g()

for x in range(1, n):
    t = list(f())
    m = t.pop(0)
    if m:
        c[x] = m
        v[x] = t
        for y in t: u[y].append(x)
    else:
        s.append(x)
        d[x] = 1
while s:
    x = s.pop()
    for y in u[x]:
        c[y] -= 1
        d[y] = max(d[y], d[x] + 1)
        if c[y] == 0: s.append(y)

if any(c[x] for x in p):
    print(-1)
    exit()

q = [0] * n
while p:
    x = p.pop()
    if q[x] == 0:
        p += v[x]
        q[x] = 1

p = sorted((d[x], x) for x in range(n) if q[x])
print(len(p))
for d, x in p: print(x)


import java.io.*;
import java.util.*;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import static java.util.Arrays.sort;

public class family_photos {
	static BufferedReader in;
	static PrintWriter out;
	static StringTokenizer tok;

	static void solve() throws Exception {
		int n = nextInt();
		long a1[] = new long[n];
		long b1[] = new long[n];
		long a2[] = new long[n];
		long b2[] = new long[n];
		for (int i = 0; i < n; i++) {
			a1[i] = nextLong();
			b1[i] = nextLong();
			a2[i] = nextLong();
			b2[i] = nextLong();
		}
		long greed[] = new long[2 * n];
		int greedCnt = 0;
		long ans = 0;
		for (int i = 0; i < n; i++) {
			if (a1[i] + b1[i] >= a2[i] + b2[i]) {
				greed[greedCnt++] = a1[i] + b1[i];
				greed[greedCnt++] = a2[i] + b2[i];
				ans -= b1[i] + b2[i];
			} else if (a1[i] > b2[i]) {
				ans += a1[i] - b2[i];
			} else if (b1[i] > a2[i]) {
				ans -= b1[i] - a2[i];
			}
		}
		sort(greed, 0, greedCnt);
		for (int i = 0; i < greedCnt; i++) {
			if (((i ^ greedCnt) & 1) != 0) {
				ans += greed[i];
			}
		}
		out.print(ans);
	}

	static int nextInt() throws IOException {
		return parseInt(next());
	}

	static long nextLong() throws IOException {
		return parseLong(next());
	}

	static double nextDouble() throws IOException {
		return parseDouble(next());
	}

	static String next() throws IOException {
		while (tok == null || !tok.hasMoreTokens()) {
			tok = new StringTokenizer(in.readLine());
		}
		return tok.nextToken();
	}

	public static void main(String[] args) {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(new OutputStreamWriter(System.out));
			solve();
			in.close();
			out.close();
		} catch (Throwable e) {
			e.printStackTrace();
			exit(1);
		}
	}
}

num_stacks = int(input())

answer = 0
array = []

for i in range(num_stacks):
    a1, b1, a2, b2 = input().split(' ')
    a1 = int(a1)
    a2 = int(a2)
    b1 = int(b1)
    b2 = int(b2)

    if a1 + b1 >= a2 + b2:
        answer += a1 + a2
        array.append(a2 + b2)
        array.append(a1 + b1)

    elif a1 > b2:
        answer += a1 - b2

    elif b1 > a2:
        answer += a2 - b1

    # Elif both side skip

array.sort()

for i in range(0, len(array), 2):
    answer -= array[i]

print(answer)


#include <bits/stdc++.h>
using namespace std;
const long long MAXN = 1000000000;
const long long HOUSE_PRICE = 1234567LL;
const long long CAR_PRICE = 123456LL;
const long long COMPUTER_PRICE = 1234LL;
long long N;
void init() { cin >> N; }
bool isDivisible(long long a, long long b, long long c) {
  if (c % a == 0 or c % b == 0) return true;
  if ((c & 1) == 1) return false;
  const long long m1 = 2201LL;
  const long long m2 = -22LL;
  const long long k1 = 617LL;
  const long long k2 = -61728LL;
  long long x0 = (m2 * c) / 2LL;
  long long y0 = (m1 * c) / 2LL;
  while (y0 >= 0) {
    if (x0 >= 0) return true;
    x0 += k1;
    y0 += k2;
  }
  return false;
}
bool isPossible() {
  for (long long a = 0; a * HOUSE_PRICE <= N; a++) {
    if (isDivisible(CAR_PRICE, COMPUTER_PRICE, N - a * HOUSE_PRICE))
      return true;
  }
  return false;
}
void solve() { cout << (isPossible() ? "YES" : "NO") << "\n"; }
int main() {
  init();
  solve();
  return 0;
}

YES YES YES YES NO NO NO NO NO NO YES YES NO YES NO NO YES YES NO NO YES YES NO NO NO YES YES YES NO NO NO NO NO YES NO NO NO YES YES NO NO YES NO NO NO NO NO

import java.io.*;
import java.math.BigInteger;
import java.util.*;

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

		long n = Long.parseLong(in.next());
		String ris = "NO";

		int cas = 1234567, aut = 123456, com = 1234;

		if(n % cas == 0)
		{
			ris = "YES";
		}else
		{
			for(int i = 0; i <= n / cas; i ++)
			{
				long totCas = i * cas;
				if((n - totCas) % aut == 0)
				{
					ris = "YES";
					break;
				}else
				{
					for(int j = 0; j <= (n - totCas) / aut; j ++)
					{
						long totAut = j * aut;
						if((n - totCas - totAut) % com == 0)
						{
							ris = "YES";
							break;
						}
					}
				}
			}
		}

		System.out.println(ris);
    }
}


import java.io.*;
import java.util.*;

public class Main {

    void solve(Scanner in, PrintWriter out) {
        long n = in.nextLong();
        out.println(n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 * (n - 4) / 5 * n * (n - 1) * (n - 2) * (n - 3) * (n - 4));
    }

    void run() {
        try (
                Scanner in = new Scanner(System.in);
                PrintWriter out = new PrintWriter(System.out)) {
            solve(in, out);
        }
    }

    public static void main(String[] args) {
        new Main().run();
    }
}

xxx", where each input is between 5 and 100:

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  long long ans = 1;
  for (int i = 0; i < 5; i++) ans *= (n - i);
  long long tmp = ans;
  for (int i = 1; i <= 5; i++) ans /= i;
  cout << ans * tmp;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int dp[1000010];
int main(void) {
  int N, i, j, x;
  cin >> N;
  for ((i) = 0; (i) < (int)(N); (i)++) {
    scanf("%d", &x);
    dp[x] = 1;
  }
  int M = 1000000;
  for (i = 1; i <= M; i++)
    if (dp[i] != 0)
      for (j = 2 * i; j <= M; j += i)
        if (dp[j] != 0) dp[j] = max(dp[j], dp[i] + 1);
  int ans = 0;
  for (i = 1; i <= M; i++) ans = max(ans, dp[i]);
  cout << ans << endl;
  return 0;
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class WorkFile {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(reader.readLine());
        boolean[] array = new boolean[1000005];
        StringTokenizer stoken = new StringTokenizer(reader.readLine());
        for (int i=0; i<n; i++) {
            int x = Integer.parseInt(stoken.nextToken());
            array[x] = true;
        }
        int[] dp = new int[1000005];
        for (int i=1; i<1000005; i++) {
            if (!array[i]) continue;
            for (int j=i*2; j<1000005; j+=i) {
                if (!array[j]) continue;
                dp[j] = Integer.max(dp[i]+1, dp[j]);
            }
            dp[i]++;
        }
        int res = 0;
        for (int i=0; i<1000005; i++) {
            res = Integer.max(res, dp[i]);
        }
        System.out.println(res);
    }
}


#include <bits/stdc++.h>
using namespace std;
int make1(int n, int m, int a, int b) {
  int wk = 0;
  while (n > 0) {
    n--;
    wk += a;
  }
  return wk;
}
int make2(int n, int m, int a, int b) {
  int wk = 0;
  while (n > 0) {
    n -= m;
    wk += b;
  }
  return wk;
}
int make3(int n, int m, int a, int b) {
  int wk = 0;
  while (n >= m) {
    n -= m;
    wk += b;
  }
  while (n > 0) {
    n--;
    wk += a;
  }
  return wk;
}
int main() {
  int n = 0, m = 0, a = 0, b = 0, last = 0;
  scanf("%i%i%i%i", &n, &m, &a, &b);
  if (a * m < b) {
    last = a * n;
    printf("%i\n", last);
  } else {
    int q = make1(n, m, a, b);
    int qq = make2(n, m, a, b);
    int qqq = make3(n, m, a, b);
    int min = q;
    if (qq < min) {
      min = qq;
    }
    if (qqq < min) {
      min = qqq;
    }
    printf("%i\n", min);
  }
  return 0;
}

inp = input().split()
n = int(inp[0])
m = int(inp[1])
a = int(inp[2])
b = int(inp[3])
sumary = min(b,a*m)
print(min((sumary)*(n//m + 1), sumary*(n // m) + (n - (n//m)*m) * a ))


def readln(): return tuple(map(int, input().split()))

n, = readln()
max_pref = [-1] * 100001
flag = True
for _ in range(n):
    x, k = readln()
    flag &= max_pref[k] + 1 >= x
    max_pref[k] = max(max_pref[k], x)
print('YES' if flag else 'NO')

NO YES NO NO NO NO YES NO NO YES NO NO NO NO NO YES NO NO YES NO NO NO NO NO YES NO NO NO YES YES NO YES NO NO NO YES NO YES NO NO YES YES NO NO NO NO NO NO NO YES

#include <bits/stdc++.h>
#pragma comment(linker, "/stack:256000000")
using namespace std;
int a[100100];
int main() {
  int n, x, k;
  cin >> n;
  for (int(i) = 0; (i) < (n); (i)++) {
    scanf("%d %d", &x, &k);
    if (a[k] < x) {
      printf("NO");
      return 0;
    }
    if (a[k] == x) {
      ++a[k];
    }
  }
  printf("YES");
  return 0;
}


def ceil(x):
    if int(x) != x:
        return int(x+1)
    else:
        return int(x)

def mafia():
    n = int(input())
    rounds = list(map(int, str(input()).split()))
    count = 0
    rounds.sort(reverse=True)
    for i in range(n-1, 0, -1):
        if rounds[i-1] == rounds[i]:
            continue
        else:
            steps = n - i
            count += steps*(rounds[i-1] - rounds[i])
    rounds[0] -= count
    if rounds[0] > 0:
        k = ceil(rounds[0] / (n - 1))
        count += n * k
        rounds[0] += k * (1 - n)
    if rounds[0] <= 0:
        count += rounds[0]
    print(count)

if __name__ == '__main__':
    mafia()

#include <bits/stdc++.h>
using namespace std;
const int N = 100001;
int n;
int a[N];
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d", a + i);
  long long lo = *max_element(a, a + n), hi = 1e13;
  while (lo < hi) {
    long long mid = (lo + hi) >> 1;
    long long tot = 0;
    for (int i = 0; i < n; i++) tot += max(0LL, mid - a[i]);
    if (tot < mid)
      lo = mid + 1;
    else
      hi = mid;
  }
  cout << lo << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main(void) {
  int num, j = 0, times = 1;
  cin >> num;
  int arr[num];
  for (int i = 0; i < num; i++) {
    cin >> arr[i];
  }
  sort(arr, arr + num);
  while (arr[j] == arr[j + 1] && j < num - 1) {
    times++;
    j++;
  }
  if (times == num)
    cout << "NO\n";
  else
    cout << arr[j + 1];
  return 0;
}

n=int(input())
ar=[int(i) for i in input().split()]
ar=list(set(sorted(ar)))
ar.sort()

try:
	print(ar[1])
except IndexError:
	print("NO")


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  vector<int> v(n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &v[i]);
  }
  long long ans = 0;
  for (int i = 0; i < n - 1; i++) {
    ans += max(0, v[i] - v[i + 1]);
  }
  cout << ans << '\n';
  return 0;
}

def solve(arr, n):
    inc = 0
    ans = 0
    for i in range(1, n):
        arr[i] += inc
        if arr[i] >= arr[i - 1]:
            continue
        diff = arr[i - 1] - arr[i]
        ans += diff
        inc += diff
        arr[i] += diff
    # print(arr)
    # print(ans)
    return ans

def read():
    n = int(input())
    arr = list(map(int, input().strip().split()))
    ans = solve(arr, n)
    print(ans)

read()