#include <bits/stdc++.h>
using namespace std;
int dig(int a) {
  if (a / 10 == 0) return a;
  return (a % 10) + dig(a / 10);
}
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < 10; i++) {
    if (dig(n + i) % 4 == 0) {
      cout << (n + i);
      break;
    }
  }
  return 0;
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.StringTokenizer;
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 CF_1183_A
{

    public static int nSum(int val){
        int sum = 0;
        while(val != 0){
            sum += val %10;
            val = val /10;
        }
        return sum;

    }
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
//        int testCount = Integer.parseInt(in.next());
////        for (int i = 1; i <= testCount; i++)
////            solver.solve(i, in, out);

        int n = Integer.parseInt(in.next());
        while (true){

            if(nSum(n)%4 ==0 ){
                out.println(n);
                break;
            }
            n ++;
        }
        out.close();
    }

    static class Task {

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            BigInteger a = new BigInteger(in.next());
            BigInteger b = new BigInteger(in.next());
            BigInteger c = new BigInteger(in.next());

            BigInteger largest  =a.max(b.max(c));
            BigInteger smallest = a.min(b.min(c));

            BigInteger middle = a.add(b).add(c).subtract(largest).subtract(smallest);
            out.println(middle.add((largest.subtract(middle.subtract(smallest)).divide(new BigInteger("2")))));

        }

    }

    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 nextInt() {
            return Integer.parseInt(next());
        }

    }
}


n = int(input())
l = list(map(int,input().split()))

if len(set(l)) == 1 and l[0] == 1 or n == 1 :
    print(sum(l))

else:
    cnt = l[0]
    for i in range(1 , n):
        cnt += l[i] + (l[i]-1) * i

    print(cnt)

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


#include <bits/stdc++.h>
using namespace std;
struct re {
  long long x, y;
};
re r[300005];
re f[300005], b[300005];
re ti(re a, re b) {
  re c;
  c.x = max(a.x, b.x);
  c.y = min(a.y, b.y);
  return c;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int n;
  cin >> n;
  int i;
  for (i = 1; i <= n; i++) cin >> r[i].x >> r[i].y;
  re b1 = r[1];
  for (i = 1; i <= n; i++) {
    b1 = ti(b1, r[i]);
    f[i] = b1;
  }
  b1 = r[n];
  for (i = n; i >= 1; i--) {
    b1 = ti(b1, r[i]);
    b[i] = b1;
  }
  long long s = 0;
  if (f[n - 1].x <= f[n - 1].y) s = max(s, f[n - 1].y - f[n - 1].x);
  if (b[2].x <= b[2].y) s = max(s, b[2].y - b[2].x);
  for (i = 2; i <= n - 1; i++) {
    b1 = ti(f[i - 1], b[i + 1]);
    if (b1.x <= b1.y) s = max(s, b1.y - b1.x);
  }
  cout << s;
  return 0;
}

def intersect(x, y):
    if x < y:
        return (y[0], x[1])
    else:
        return (x[0], y[1])

def solve(iv):
    first = {}
    second = {}
    for x, y in iv:
        first[x] = first.get(x, 0) + 1
        second[y] = second.get(y, 0) + 1
    max1, max2 = reversed(sorted([x for x, _ in iv])[-2:])
    min1, min2 = sorted([y for _, y in iv])[:2]

    res = 0
    for x, y in iv:
        first[x] -= 1
        second[y] -= 1
        if first[x] == 0 and x == max1:
            max_first = max2
        else:
            max_first = max1
        if second[y] == 0 and y == min1:
            min_second = min2
        else:
            min_second = min1
        first[x] += 1
        second[y] += 1
        if min_second - max_first > res:
            res = min_second - max_first
    return res

def main():
    n = int(input())
    iv = []
    for i in range(n):
        a, b = map(int, input().split())
        iv.append((a, b))
    res = solve(iv)
    print(res)

main()


import java.io.*;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.SSLContext;

public class Main
{
   static long mod=(long)(1e+9) + 7;
   static int[] sieve;
   static ArrayList<Integer> primes;
   static HashMap<Integer,Integer> hm;

   public static long greater(int m,int a[])
   {
	   int sum=0;
	   long till=0;
	   long fans=0;

	   hm=new HashMap<Integer,Integer>();
	   hm.put(0, 1);
	   for(int i=0;i<a.length;i++)
	   {
		   if(a[i]<m)
		   {
			   sum--;
			   if(hm.containsKey(sum))
			     till-=hm.get(sum);
		   }
		   else
		   {
			   if(hm.containsKey(sum))
				     till+=hm.get(sum);
			   sum++;
		   }

		   if(!hm.containsKey(sum)) hm.put(sum, 1);
		   else hm.put(sum, hm.get(sum)+1);

		   fans+=till;
	   }

	   return fans;
   }
   public static void main(String[] args) throws java.lang.Exception
   {
	     fast s = new fast();
	     PrintWriter out=new PrintWriter(System.out);
	     Scanner sc=new Scanner(System.in);
	     StringBuilder fans = new StringBuilder();

	     int n=s.nextInt();
	     int m=s.nextInt();

	     int a[]=new int[n];

	     for(int i=0;i<n;i++) a[i]=s.nextInt();

	     System.out.println(greater(m,a)-greater(m+1,a));

   }

static class fast {
		private InputStream i;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public static boolean next_permutation(int a[])
		   {
			   int i=0,j=0;int index=-1;
			   int n=a.length;

			   for(i=0;i<n-1;i++)
				   if(a[i]<a[i+1]) index=i;

			   if(index==-1) return false;
			   i=index;

			   for(j=i+1;j<n && a[i]<a[j];j++);

			   int temp=a[i];
			   a[i]=a[j-1];
			   a[j-1]=temp;

			   for(int p=i+1,q=n-1;p<q;p++,q--)
			   {
				   temp=a[p];
				   a[p]=a[q];
				   a[q]=temp;
			   }

			   return true;
		   }

		public static void division(char ch[],int divisor)
		   {
			   int div=Character.getNumericValue(ch[0]); int mul=10;int remainder=0;
			   StringBuilder quotient=new StringBuilder("");
			   for(int i=1;i<ch.length;i++)
			   {
				   div=div*mul+Character.getNumericValue(ch[i]);
				   if(div<divisor) {quotient.append("0");continue;}
				   quotient.append(div/divisor);
				   div=div%divisor;mul=10;

			   }
			   remainder=div;
			   while(quotient.charAt(0)=='0')quotient.deleteCharAt(0);
			   System.out.println(quotient+" "+remainder);
		   }

		public static void sieve(int size)
		{
			sieve=new int[size+1];
			primes=new ArrayList<Integer>();
			sieve[1]=1;
			for(int i=2;i<=Math.sqrt(size);i++)
			{
				if(sieve[i]==0)
				 {
					for(int j=i*i;j<size;j+=i) sieve[j]=1;
				 }
			}

			for(int i=2;i<=size;i++)
			{
				if(sieve[i]==0) primes.add(i);
			}
		}
		public static long pow(long n, long b, long MOD)
		   {
		       long x=1;long y=n;
		       while(b > 0)
		       {
		           if(b%2 == 1)
		           {
		               x=x*y;
		               if(x>MOD) x=x%(MOD);
		           }
		           y = y*y;
		           if(y>MOD) y=y%(MOD);
		           b >>= 1;
		       }
		       return x;
		   }

		 public static int upper(Integer[] a,int start,int end,int key)
		 {
			   int mid=(start+end)>>1;
			   if(start==end && a[mid]<key) {return -1;}
			   if(start>end) return -1;

			   if(a[mid]>=key && (((mid-1)>=0 && a[mid-1]<key) || (mid-1)==0)) return mid;
			   else if(a[mid]== key && (mid-1)>=0 && a[mid-1]==key) return lower(a,start,mid-1,key);
			   else if(key>a[mid]) return lower(a,mid+1,end,key);
			   else return lower(a,start,mid-1,key);
		}

		 public static int lower(Integer a[],int start,int end,int key)
		 {
			   int mid=(start+end)>>1;
			   if(start==end && a[mid]>key) {return -1;}
			   if(start>end) return -1;

			   if(a[mid]<=key && (((mid+1)<a.length && a[mid+1]>key) || (mid+1)==a.length)) return mid;
			   else if(a[mid]== key && (mid+1)<a.length && a[mid+1]==key) return upper(a,mid+1,end,key);
			   else if(key>=a[mid]) return upper(a,mid+1,end,key);
			   else return upper(a,start,mid-1,key);
		}

		public int gcd(int a,int b)
		{
			if(a==0) return b;
			return gcd(b%a,a);
		}
		public fast() {
			this(System.in);
		}
		public fast(InputStream is) {
			i = is;
		}
		public int read() {
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = i.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}
		public String nextLine() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndOfLine(c));
			return res.toString();
		}
		public String nextString() {
     		int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}
		public long nextLong() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}
		public int nextInt() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}
		public boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}
		public boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

	}
}

n, m = map(int, input().split(' '))
aa = list(map(int, input().split(' ')))

def countMoreLess(vs, value):
    #print(vs)
    cur = 0
    res = { cur: 1 }

    for v in vs:
        cur += 1 if v > value else -1
        res[cur] = res.get(cur, 0) + 1
    #print(res)
    return res

pos = aa.index(m)

leftCounts = countMoreLess(list(reversed(aa[0:pos])), m)
rightCounts = countMoreLess(aa[pos+1:], m)

res = 0
for dif, count in leftCounts.items():
    res += count * rightCounts.get(-dif, 0)
    res += count * rightCounts.get(-dif+1, 0)

print(res)


s = input()
m = int(input())
mn = m
ttt = 0
t = 0
ttt = 1
for i in range(1,len(s)):
    ttt = (ttt * 10) % m
for i in range(0,len(s)):
    t = (t * 10 + ord(s[i]) - ord('0')) % m
for i in range(0,len(s)):
    if s[i] != '0':
        mn = min(mn,t)
    t = t - (((ord(s[i])- ord('0')) * ttt) % m)
    if t < 0:
        t = t + m
    t = (t * 10 + (ord(s[i])- ord('0'))) % m
print(mn)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
		String s = sc.next();

		int divider  = sc.nextInt();
		int len = s.length();
		int cur = 0;
		int q = 0;
		int mnoj[] = new int[10];
		mnoj[1] = 1;
		for (int i = 0; i < len; i++) {
		    q = (s.charAt(i) - '0');
		    cur = (cur * 10 + q) % divider;
		    mnoj[1] = mnoj[1] * 10 % divider;
		}

		for (int i = 2; i < 10; i++)
		{
			mnoj[i] = mnoj[1] * i % divider;
		}

		int min = cur;
		for (int i = 0; i < len; i++) {
			q = (s.charAt(i) - '0');
			if (q != 0) {
				if (cur < min) {
					min = cur;
				}
			}
			cur = (cur * 10 - mnoj[q] + q + divider) % divider;
		}

		System.out.println(min);
		sc.close();
	}
}


from math import log
n = int(input())

def fivetorization(n):
	cnt = 0
	while n%5==0:
		cnt+=1
		n//=5
	return cnt

res=0
for i in range(5, 500001, 5):
	res+=fivetorization(i)
	if res==n:
		print(5)
		print(*[j for j in range(i, i+5)])
		quit()
print(0)

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author ansam
 */
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        ArrayList<Integer> list = new ArrayList<>();
        int count = 0;
        for (int i = 1; count <= m; i++) {
            // the no. of zeros change every 5 numbers
            for (int j = i; j%5 == 0; j/=5) {
                count++;

            }
            if(count == m) list.add(i);

        }
        String x = "";
        System.out.println(list.size());
        for (Integer s : list) {
            System.out.print(x+s);
            x= " ";
        }
        System.out.println("");
    }
}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (Scanner in = new Scanner(System.in)) {
            int nCand = in.nextInt();
            int mTowns = in.nextInt();
            int[][] arr = new int[mTowns][nCand];

            for (int i = 0; i < mTowns; i++) {
                for (int j = 0; j < nCand; j++) {
                    arr[i][j] = in.nextInt();
                }
            }

            int[] candidatePerTown = new int[nCand];

            for (int i = 0; i < mTowns; i++) {
                int maxCand = -1;
                int maxValue = -1;
                for (int j = nCand - 1; j >= 0; j--) {
                    if (arr[i][j] >= maxValue) {
                        maxValue = arr[i][j];
                        maxCand = j;
                    }
                }
                candidatePerTown[maxCand]++;
            }

            int maxCand = -1;
            int maxValue = -1;
            for (int i = nCand - 1; i >= 0; i--) {
                if (candidatePerTown[i] >= maxValue) {
                    maxValue = candidatePerTown[i];
                    maxCand = i;
                }
            }
            System.out.println(maxCand+ 1);
        }
    }
}

#include <bits/stdc++.h>
using namespace std;
int res[111];
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  while (m--) {
    pair<int, int> add;
    add.first = -1;
    for (int i = 0; i < n; i++) {
      int kol;
      scanf("%d", &kol);
      if (kol > add.first) {
        add.first = kol;
        add.second = i + 1;
      }
    }
    res[add.second]++;
  }
  pair<int, int> ans;
  ans.first = -1;
  for (int i = 1; i <= n; i++) {
    if (res[i] > ans.first) {
      ans.first = res[i];
      ans.second = i;
    }
  }
  printf("%d", ans.second);
}


n,m,dx,dy = map(int,input().split())
x=y=0
a=[0]*n
c=[0]*n
for i in range(1,n):
  x = (x+dx)%n
  y = (y+dy)%n
  a[x]=y
for i in range(m):
  x,y = map(int,input().split())
  index = (y-a[x]+n)%n;
  c[index] += 1
ans = 0
for i in range(n):
  if c[i] > c[ans]: ans = i
print(0, ans)

#include <bits/stdc++.h>
using namespace std;
int cnt[2000010];
int x[2000010], y[2000010];
int ordx[2000010], ordy[2000010];
int main() {
  int n, m, dx, dy;
  scanf(" %d %d %d %d", &n, &m, &dx, &dy);
  ordx[0] = ordy[0] = 0;
  int auxx = 0, auxy = 0;
  for (int i = 0; i < (n - 1); ++i) {
    auxx = (auxx + dx) % n;
    ordx[auxx] = i + 1;
    auxy = (auxy + dy) % n;
    ordy[auxy] = i + 1;
  }
  int ans = 0, id = 0;
  for (int i = 0; i < (m); ++i) {
    scanf(" %d %d", &x[i], &y[i]);
    int aux = (ordx[x[i]] - ordy[y[i]] + n) % n;
    cnt[aux]++;
    if (cnt[aux] > ans) {
      ans = cnt[aux];
      id = i;
    }
  }
  printf("%d %d\n", x[id], y[id]);
  return 0;
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
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);
        BPaintingTheWall solver = new BPaintingTheWall();
        solver.solve(1, in, out);
        out.close();
    }

    static class BPaintingTheWall {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.readInt();
            int m = in.readInt();

            int[][] wall = new int[n][n];
            for (int i = 0; i < m; i++) {
                int r = in.readInt() - 1;
                int c = in.readInt() - 1;

                wall[r][c] = 1;
            }
            int blankrow = 0, blankcol = 0;
            for (int i = 0; i < n; i++) {
                int cnt1 = 0, cnt2 = 0;
                for (int j = 0; j < n; j++) {
                    if (wall[i][j] == 1) cnt1++;
                    if (wall[j][i] == 1) cnt2++;
                }
                if (cnt1 == 0) blankrow++;
                if (cnt2 == 0) blankcol++;
            }
            double[][] dp = new double[n + 1][n + 1];
            dp[0][0] = 0;

            for (int i = 0; i <= n; i++) {
                for (int j = 0; j <= n; j++) {
                    if (i == 0 && j == 0) continue;
                    double sum = n * n;
                    if (i > 0 && j > 0) sum += dp[i - 1][j - 1] * i * j;
                    if (i > 0) sum += dp[i - 1][j] * i * (n - j);
                    if (j > 0) sum += dp[i][j - 1] * j * (n - i);
                    dp[i][j] = sum / (n * n - (n - i) * (n - j));
                }
            }
            out.println(dp[blankrow][blankcol]);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

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

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

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

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

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

        }

    }
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  int s1 = 0, s2 = 0;
  int x[105], y[105];
  bool pos = false;
  for (int i = 0; i < n; i++) {
    cin >> x[i] >> y[i];
  }
  for (int i = 0; i < n; i++) {
    s1 += x[i];
    s2 += y[i];
    if (x[i] % 2 != y[i] % 2) {
      pos = true;
    }
  }
  s1 = s1 % 2;
  s2 = s2 % 2;
  if (s1 == 0 && s2 == 0) {
    cout << "0" << endl;
  } else if (s1 == 1 && s2 == 1) {
    if (pos)
      cout << "1" << endl;
    else
      cout << "-1" << endl;
  } else {
    cout << "-1" << endl;
  }
}

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

public class A {

    static StringTokenizer st;
    static BufferedReader br;
    static PrintWriter pw;
    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n = nextInt();
        int[]a = new int[n+1], b = new int[n+1];
        int sum1 = 0, sum2 = 0;
        for (int i = 1; i <= n; i++) {
            a[i] = nextInt();
            b[i] = nextInt();
            sum1 += a[i];
            sum2 += b[i];
        }
        if (sum1 % 2==0 && sum2 % 2==0)
            System.out.println(0);
        else {
            if (sum1 % 2!=sum2 % 2) {
                System.out.println(-1);
                return;
            }
            for (int i = 1; i <= n; i++) {
                if (a[i] % 2 != b[i] % 2) {
                    System.out.println(1);
                    return;
                }
            }
            System.out.println(-1);
        }
        pw.close();
    }
    private static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
    private static long nextLong() throws IOException {
        return Long.parseLong(next());
    }
    private static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
    private static String next() throws IOException {
        while (st==null || !st.hasMoreTokens())
            st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }
}


#import math

def gcd(a, b):
   if b == 0:
      return a
   else:
     return gcd(b, a % b)

p, q = map(int, input().split())
n = int(input())
data = list(map(int, input().split()))
a = 1
b = data[-1]
for i in range(2, n + 1):
  a = b * data[n - i] + a
  a, b = b, a

a, b = b, a
nod = gcd(p, q)
p = p // nod
q = q // nod

if p == a and q == b:
  print("YES")
else:
  print("NO")

NO YES NO NO NO NO 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 NO YES NO NO NO NO NO NO NO NO YES NO NO NO NO NO NO NO NO

#include <bits/stdc++.h>
using namespace std;
const int MM = 1200000;
bool solve(long long int p, long long int q, vector<long long int> x) {
  if (p <= 0 || q <= 0) {
    return 0;
  }
  if (x.size() == 1) {
    return (p / q == x.back() && p == x.back() * q);
  }
  long long int tp = x.back();
  x.pop_back();
  if (abs(p / q - tp) > 2) {
    return 0;
  }
  return solve(q, p - q * tp, x);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long int P, Q;
  cin >> P >> Q;
  int N;
  cin >> N;
  vector<long long int> A(N);
  for (int i = 0; i < N; i++) {
    cin >> A[N - i - 1];
  }
  if (solve(P, Q, A)) {
    cout << "YES";
  } else {
    cout << "NO";
  }
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  string a, b;
  int i, j;
  cin >> a >> b;
  if (b.size() != a.size()) {
    cout << "NO";
    return 0;
  }
  for (i = 0; i < a.size(); i++)
    if (a[i] != '0') break;
  for (j = 0; j < b.size(); j++)
    if (b[j] != '0') break;
  if ((i == a.size() || j == b.size()) && i != j) {
    cout << "NO";
    return 0;
  }
  cout << "YES";
  return 0;
}

def helper(a,b):
    n=len(a)
    m=len(b)
    if n!=m:
        return 'NO'
    if a==b:
        return 'YES'
    if a=='0'*n or b=='0'*m:
        return'NO'
    return 'YES'
a=input()
b=input()
print(helper(a,b))


import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;

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

class TaskC {
	public void solve(int testNumber, InputReader in, OutputWriter out) {
        String s=in.next();
        int i,n=s.length();
        for(i=0;i<n;i++)
        {
            if(s.charAt(i)=='0')
            {
                out.printLine(s.substring(0,i)+s.substring(i+1,n));
                return;
            }
        }
        out.printLine(s.substring(1,n));
	}
}

class InputReader
{
    BufferedReader in;
    StringTokenizer tokenizer=null;

    public InputReader(InputStream inputStream)
    {
        in=new BufferedReader(new InputStreamReader(inputStream));
    }
    public String next()
    {
        try{
            while (tokenizer==null||!tokenizer.hasMoreTokens())
            {
                tokenizer=new StringTokenizer(in.readLine());
            }
            return tokenizer.nextToken();
        }
        catch (IOException e)
        {
            return null;
        }
    }
    }

class OutputWriter {
	private final PrintWriter writer;

	public OutputWriter(OutputStream outputStream) {
		writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
	}

	public OutputWriter(Writer writer) {
		this.writer = new PrintWriter(writer);
	}

	public void print(Object...objects) {
		for (int i = 0; i < objects.length; i++) {
			if (i != 0)
				writer.print(' ');
			writer.print(objects[i]);
		}
	}

	public void printLine(Object...objects) {
		print(objects);
		writer.println();
	}

	public void close() {
		writer.close();
	}
}

#include <bits/stdc++.h>
using namespace std;
char num[100005];
int main() {
  scanf("%s", num);
  int time = 0;
  if (strchr(num, '0')) {
    for (int i = 0; num[i]; i++) {
      if (num[i] == '0' && time == 0) {
        time++;
      } else {
        putchar(num[i]);
      }
    }
    putchar(10);
  } else {
    num[strlen(num) - 1] = 0;
    printf("%s\n", num);
  }
  return 0;
}


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

public class B232 {

    static StringTokenizer st;
    static BufferedReader in;
    static int mod = (int) (1e9+7);
    public static void main(String[] args) throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n = nextInt();
        long m = nextLong();
        int k = nextInt();
        long[][]dp = new long[n+1][k+1];
        int t = (int) (m % n);
        dp[0][0] = 1;
        int[][]c = new int[n+1][n+1];
        c[0][0] = 1;
        for (int i = 1; i <= n; i++) {
            c[i][0] = 1;
            for (int j = 1; j <= n; j++) {
                c[i][j] = (c[i-1][j-1]+c[i-1][j]) % mod;
            }
        }
        int[][]pow = new int[n+1][n+1];
        long p = (long) (m / n);
        for (int i = 1; i <= n; i++) {
            long b = p;
            if (i <= t)
                b++;
            for (int j = 0; j <= n; j++) {
                pow[i][j] = modpow(c[n][j], b);
            }
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= k; j++) {
                for (int j2 = 0; j2 <= n; j2++) {
                    if (j-j2 >= 0) {
                        dp[i][j] = (dp[i][j]+dp[i-1][j-j2] * pow[i][j2]) % mod;
                    }
                }
            }
        }
        System.out.println(dp[n][k]);
        pw.close();
    }
    private static int modpow(int a, long n) {
        int res = 1;
        while (n > 0) {
            if ((n & 1) != 0)
                res = (int) ((long)res * a % mod);
            n >>= 1;
            a = (int) ((long)a*a % mod);
        }
        return res;
    }
    private static int nextInt() throws IOException{
        return Integer.parseInt(next());
    }

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

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

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

#include <bits/stdc++.h>
using namespace std;
const int N = 105, mod = 1e9 + 7;
long long n, m, k;
int f[N], inv[N], dp[N][N * N];
int add(int x, int y) { return (x * 1ll + y) % mod; }
int mul(int x, int y) { return (x * 1ll * y) % mod; }
int pw(int b, long long p) {
  if (!p) return 1;
  int ret = pw(b, p / 2);
  ret = mul(ret, ret);
  if (p & 1) ret = mul(ret, b);
  return ret;
}
int c(int n, int k) { return n < k ? 0 : mul(f[n], mul(inv[k], inv[n - k])); }
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m >> k;
  f[0] = inv[0] = dp[0][0] = 1;
  for (int i = 1; i <= n; i++) {
    f[i] = mul(f[i - 1], i);
    inv[i] = pw(f[i], mod - 2);
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 0; j <= n; j++) {
      int p = pw(c(n, j), 1 + (m - i) / n);
      for (int kk = 0; kk <= k - j; kk++)
        dp[i][j + kk] = add(dp[i][j + kk], mul(p, dp[i - 1][kk]));
    }
  }
  cout << dp[n][k];
}


n,ohh,wow= list(map(int , input().split()))
if(wow==0):
    if(n>=ohh+2):
        print(1,end=" ")
        print(1,end=" ")
        for i in range(1,ohh+1):
            print(i+1,end=" ")
        for i in range(n-ohh-2):
            print(ohh+1,end=" ")
    elif(ohh==0):
        for i in range(n):
            print(1,end=" ")
    else:
        print(-1)
else:
    ans=1
    print(ans,end=" ")
    for i in range(wow):
        ans*= 2
        print(ans,end=" ")
    for i in range(1,ohh+1):
        print(ans+i,end=" ")
    for i in range(n-ohh-wow-1):
        print(1,end=" ")


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;

/**
 * @author Mubtasim Shahriar
 */

public class StonedGame {

    public static void main(String[] args) {

        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader sc = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Solver solver = new Solver();
		int t = sc.nextInt();
//        int t = 1;
        while (t-- != 0) {
            solver.solve(sc, out);
        }
        out.close();

    }

    static class Solver {
        public void solve(InputReader sc, PrintWriter out) {
            int n = sc.nextInt();
            int[] arr = sc.nextIntArray(n);
            long sum = 0;
            long max = -1;
            for(long l : arr)  {
                sum += l;
                max = Math.max(max,l);
            }
            sum -= max;
            if(max>sum) {
                out.println("T");
                return;
            }
            if(max%2==sum%2) {
                out.println("HL");
                return;
            }
            out.println("T");
        }
    }

    static void sort(int[] arr) {
        ArrayList<Integer> al = new ArrayList();
        for (int i : arr) al.add(i);
        Collections.sort(al);
        int idx = 0;
        for (int i : al) arr[idx++] = i;
    }

    static void sort(long[] arr) {
        ArrayList<Long> al = new ArrayList();
        for (long i : arr) al.add(i);
        Collections.sort(al);
        int idx = 0;
        for (long i : al) arr[idx++] = i;
    }

    static void sortDec(int[] arr) {
        ArrayList<Integer> al = new ArrayList();
        for (int i : arr) al.add(i);
        Collections.sort(al, Collections.reverseOrder());
        int idx = 0;
        for (int i : al) arr[idx++] = i;
    }

    static void sortDec(long[] arr) {
        ArrayList<Long> al = new ArrayList();
        for (long i : arr) al.add(i);
        Collections.sort(al, Collections.reverseOrder());
        int idx = 0;
        for (long i : al) arr[idx++] = i;
    }

    static class InputReader {
        private boolean finished = false;

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

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

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

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

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

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

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

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private String readLine0() {
            StringBuilder buf = new StringBuilder();
            int c = read();
            while (c != '\n' && c != -1) {
                if (c != '\r') {
                    buf.appendCodePoint(c);
                }
                c = read();
            }
            return buf.toString();
        }

        public String readLine() {
            String s = readLine0();
            while (s.trim().length() == 0) {
                s = readLine0();
            }
            return s;
        }

        public String readLine(boolean ignoreEmptyLines) {
            if (ignoreEmptyLines) {
                return readLine();
            } else {
                return readLine0();
            }
        }

        public BigInteger readBigInteger() {
            try {
                return new BigInteger(nextString());
            } catch (NumberFormatException e) {
                throw new InputMismatchException();
            }
        }

        public char nextCharacter() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            return (char) c;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E') {
                    return res * Math.pow(10, nextInt());
                }
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E') {
                        return res * Math.pow(10, nextInt());
                    }
                    if (c < '0' || c > '9') {
                        throw new InputMismatchException();
                    }
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public boolean isExhausted() {
            int value;
            while (isSpaceChar(value = peek()) && value != -1) {
                read();
            }
            return value == -1;
        }

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

        public SpaceCharFilter getFilter() {
            return filter;
        }

        public void setFilter(SpaceCharFilter filter) {
            this.filter = filter;
        }

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

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

        public int[] nextSortedIntArray(int n) {
            int array[] = nextIntArray(n);
            Arrays.sort(array);
            return array;
        }

        public int[] nextSumIntArray(int n) {
            int[] array = new int[n];
            array[0] = nextInt();
            for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
            return array;
        }

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

        public long[] nextSumLongArray(int n) {
            long[] array = new long[n];
            array[0] = nextInt();
            for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
            return array;
        }

        public long[] nextSortedLongArray(int n) {
            long array[] = nextLongArray(n);
            Arrays.sort(array);
            return array;
        }
    }

}

#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int MOD = 1e9 + 7, MAX = 1e6 + 5;
const long long INF = 1e18 + 5;
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<int> A(n);
    for (int in = 0; in < 0 + n; in++) cin >> A[in];
    sort(A.begin(), A.end());
    reverse(A.begin(), A.end());
    int xo = A[0];
    int sum = 0;
    for (int i = 1; i < n; i++) {
      xo ^= A[i];
      sum += A[i];
    }
    if (A[0] > sum || xo % 2 == 1) {
      cout << "T" << endl;
    } else
      cout << "HL" << endl;
  }
}


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

public class  Main{
	static void increase(char[]in,int idx) {
		while(in[idx]=='9') {
			in[idx]='0';
			idx--;
		}
		in[idx]++;
	}
	public static void main(String[] args) throws Exception{
		MScanner sc=new MScanner(System.in);
		PrintWriter pw=new PrintWriter(System.out);
		int n=sc.nextInt(),k=sc.nextInt();
		char[]in=sc.nextLine().toCharArray();
		int minigreater=n+1,minismaller=n+1;
		for(int i=0;i<k;i++) {
			for(int j=i+k;j<n;j+=k) {
				if(in[j]>in[i]) {
					minigreater=Math.min(minigreater, j);
				}
				if(in[j]<in[i]) {
					minismaller=Math.min(minismaller, j);
				}
			}
		}
		//System.out.println(minismaller+" "+minigreater+" "+Arrays.toString(in));
		pw.println(n);
		if(minismaller==minigreater) {
			for(char i:in)pw.print(i);
			pw.flush();
			return;
		}
		if(minismaller<minigreater) {
			for(int i=minismaller;i<n;i++) {
				in[i]=in[i%k];
			}
			for(char i:in)pw.print(i);
		}
		else {
			increase(in,k-1);
			for(int i=k;i<n;i++) {
				in[i]=in[i%k];
			}
			for(char i:in)pw.print(i);
		}
		pw.flush();
	}
	static class MScanner {
		StringTokenizer st;
		BufferedReader br;
		public MScanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public MScanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}
		public int[] takearr(int n) throws IOException {
	        int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        return in;
		}
		public long[] takearrl(int n) throws IOException {
	        long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        return in;
		}
		public Integer[] takearrobj(int n) throws IOException {
	        Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
	        return in;
		}
		public Long[] takearrlobj(int n) throws IOException {
	        Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
	        return in;
		}
		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public Long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}


n = int(input())

tram = []
current = []

curr = 0

for i in range(0, n):
    tram.extend([int(x) for x in input().split()])

for i in range(0, 2*n, 2):
    curr -= tram[i]
    curr += tram[i+1]
    current.append(curr)
print(max(current))

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

public class Solution implements Runnable{
    public static BufferedReader br;
    public static PrintWriter out;
    public static StringTokenizer stk;
    public static boolean isStream = true;

    public static void main(String[] args) throws IOException {
    	if (isStream) {
            br = new BufferedReader(new InputStreamReader(System.in));
        } else {
            br = new BufferedReader(new FileReader("in.txt"));
        }
        out = new PrintWriter(System.out);
        new Thread(new Solution()).start();
    }

    public void loadLine() {
        try {
            stk = new StringTokenizer(br.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

    public String nextWord() {
        while (stk==null||!stk.hasMoreTokens()) loadLine();
        return stk.nextToken();
    }

    public Integer nextInt() {
        while (stk==null||!stk.hasMoreTokens()) loadLine();
        return Integer.valueOf(stk.nextToken());
    }

    public Long nextLong() {
        while (stk==null||!stk.hasMoreTokens()) loadLine();
        return Long.valueOf(stk.nextToken());
    }

    public Double nextDouble() {
        while (stk==null||!stk.hasMoreTokens()) loadLine();
        return Double.valueOf(stk.nextToken());
    }

    public Float nextFloat() {
        while (stk==null||!stk.hasMoreTokens()) loadLine();
        return Float.valueOf(stk.nextToken());
    }

    public void run() {
    	int n = nextInt();
    	int sum = 0;
    	int ans = 0;
    	for (int i = 0; i < n; i++) {
    		sum -= nextInt();
    		sum += nextInt();
    		ans = Math.max(ans, sum);
    	}
    	out.println(ans);
    	out.flush();
    }
}


import java.util.Scanner;

public class DigitalRoot {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int digits[] = new int[9];
		long result = 0;
		for (int i = 1; i <= n; i++) {
			digits[i%9]++;
			result -= (n/i);
		}
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 9; j++) {
				result += 1L*digits[i]*digits[j]*digits[(i*j)%9];
			}
		}
		System.out.println(result);
	}

}

n, ans, a = int(input()), 0, [0] * 10
for i in range(1, n + 1):
    ans -= int(n/i)
    a[i % 9] += 1
for i in range(9):
    for j in range(9):
        ans += a[i] * a[j] * a[(i * j) % 9]
print(ans)


#include <bits/stdc++.h>
using namespace std;
const int N = 500500;
const long long INF = (1e17) + 777;
const int mod = (1e9) + 7;
int n, k, x, cnt[N];
vector<int> v;
int main() {
  ios_base::sync_with_stdio(0);
  ;
  cin >> k >> n;
  for (int i = 1; i <= n; i++) {
    cin >> x;
    cnt[x]++;
  }
  for (int i = 1; i <= 100; i++) {
    if (cnt[i] == 0)
      continue;
    else
      v.push_back(cnt[i]);
  }
  sort(v.begin(), v.end());
  reverse(v.begin(), v.end());
  for (int j = 100; j >= 1; j--) {
    int ans = 0;
    for (int i = 0; i < v.size(); i++) ans += v[i] / j;
    if (ans >= k) {
      cout << j;
      return 0;
    }
  }
  cout << 0;
  return 0;
}

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

public class R_499_d2_B {

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

    	String[] vals = scanner.nextLine().split(" ");

    	int n = Integer.parseInt(vals[0].trim());
    	int m = Integer.parseInt(vals[1].trim());

    	String[] types = scanner.nextLine().split(" ");

        if (m < n) {
            System.out.println(0);
            return;
        }

        if (m == n) {
            System.out.println(1);
            return;
        }

        HashMap<String, Integer> hits = new HashMap<>();
        for (int i = 0; i < types.length; i++) {
            Integer v = hits.get(types[i]);
            hits.put(types[i], v == null ? 1 : v + 1);
        }

        Integer max = Collections.max(hits.values());

        boolean flag = false;
        while (max > 0 && ! flag) {
            int units = 0;

            for (Integer e : hits.values()) {
                units += (e / max);
            }

            if (units >= n) {
                flag = true;
            }

            max--;
        }

        System.out.println(flag ? max + 1 : 0);

	}
}


import sys
import math
import itertools
import collections

def getdict(n):
    d = {}
    if type(n) is list or type(n) is str:
        for i in n:
            if i in d:
                d[i] += 1
            else:
                d[i] = 1
    else:
        for i in range(n):
            t = ii()
            if t in d:
                d[t] += 1
            else:
                d[t] = 1
    return d
def divs(n, start=1):
    r = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if (n % i == 0):
            if (n / i == i):
                r.append(i)
            else:
                r.extend([i, n // i])
    return r
def cdiv(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a*b) // math.gcd(a, b)
def wr(arr): return ' '.join(map(str, arr))
def revn(n): return int(str(n)[::-1])
def prime(n):
    if n == 2: return True
    if n % 2 == 0 or n <= 1: return False
    sqr = int(math.sqrt(n)) + 1
    for d in range(3, sqr, 2):
        if n % d == 0: return False
    return True
def convn(number, base=3):
    newnumber = ''
    while number > 0:
        newnumber = str(number % base) + newnumber
        number //= base
    return newnumber

n = input()
pointpos = n.find('.')
if n[pointpos - 1] == '9':
    print('GOTO Vasilisa.')
elif n[pointpos + 1] > '4':
    print(n[:pointpos - 1] + chr(ord(n[pointpos - 1]) + 1))
else:
    print(n[:pointpos])

GOTO Vasilisa.
12345678901234567890
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
1
GOTO Vasilisa.
3
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
1
GOTO Vasilisa.
GOTO Vasilisa.
2
GOTO Vasilisa.
0
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
71828182845904523536
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
8
14159265358979323846
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
50
0
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
GOTO Vasilisa.
3

#include <bits/stdc++.h>
using namespace std;
void solve() {
  string s1, s2, s3;
  cin >> s1;
  long long f = 0, l1;
  for (long long x = 0; x < s1.length(); x++) {
    if (s1[x] == '.') {
      f = 1;
      continue;
    }
    if (f == 0)
      s2 += s1[x];
    else
      s3 += s1[x];
  }
  l1 = s2.length();
  if (s2[l1 - 1] - 48 < 9) {
    if (s3[0] - 48 >= 5) s2[l1 - 1] += 1;
  } else {
    cout << "GOTO Vasilisa.";
    return;
  }
  cout << s2;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  solve();
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
long long a[N];
long long n, m;
int main() {
  cin >> n >> m;
  for (long long i = 1; i <= n; i++) {
    cin >> a[i];
  }
  a[n + 1] = 100000000000;
  long long l = 1, q = 0;
  long double ans = -1;
  for (long long i = 1; i <= n; i++) {
    while (a[i] - a[l] > m) {
      l++;
    }
    if (i - l >= 2) {
      q = 1;
      ans =
          max(ans, (long double)(a[i] - a[l + 1]) / (long double)(a[i] - a[l]));
    }
  }
  long long r = 1;
  for (int i = 1; i <= n; i++) {
    while (a[r + 1] - a[i] <= m) {
      r++;
    }
    if (r - i >= 2) {
      q = 1;
      ans =
          max(ans, (long double)(a[r] - a[i + 1]) / (long double)(a[r] - a[i]));
    }
  }
  if (!q) {
    cout << -1;
  } else {
    cout << fixed << setprecision(20) << ans;
  }
}

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

public class Codeforces472_C {
	// C. Three-level Laser
	static int[] A = new int[400005];

	public static int er(int a[], int l, int r, int v) {
		// a[i]<=v
		int mid;
		while (l <= r) {
			mid = (l + r) / 2;
			if (a[mid] > v) {
				r = mid - 1;
				continue;
			}
			if (a[mid] <= v) {
				if (mid == r)
					return mid;
				if (a[mid + 1] > v)
					return mid;
				l = mid + 1;
			}
		}

		return -1;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<String,Integer> mp=new HashMap<String,Integer>();
		Scanner input = new Scanner(System.in);

		int n, u;
		n = input.nextInt();
		u = input.nextInt();
		for(int i=1;i<=n;i++)
		{
			A[i]=input.nextInt();
		}
		double r=0.0;
		boolean f=false;
		for(int i=1;i<=n-2;i++) {
			int ix=er(A,i+2,n,A[i]+u);
			if(ix==-1)
				continue;
			else {
				f=true;

				r=max(r,(double)(A[ix]-A[i+1])/(double)(A[ix]-A[i]));
			}

		}

		if(f)
			System.out.println(r);
		else
			System.out.println(-1);
		input.close();
	}

	private static double max(double r, double d) {
		// TODO Auto-generated method stub

		return r>d?r:d;
	}

}


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

public class main {
    public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static PrintWriter pw = new PrintWriter(System.out);
    public static String line;
    public static StringTokenizer st;
    public static ArrayList<ArrayList<Integer>> adjList;
    public static int[] dx = {-1, 0, 1, 0, -1, 1, 1, -1};
    public static int[] dy = {0, 1, 0, -1, 1, 1, -1, -1};
    public static int INF = 0x3f3f3f3f;
    public static int MOD = 1000000007;

    public static void main(String[] args) throws Exception{
        st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken());
        int k = Integer.parseInt(st.nextToken());
        TreeSet<Group> d = new TreeSet<Group>();
        Group.k = k;
        for(int i = 0; i < N; i++){
            st = new StringTokenizer(br.readLine());
            int[] A = new int[k];
            for(int j = 0; j < k; j++) A[j] = Integer.parseInt(st.nextToken());
            Group g = new Group(A);
            // System.out.println(g);
            Group g1 = null;
            while((g1 = d.lower(g)) != null){
                // System.out.println(g1);
                boolean f = false;
                for(int j = 0; j < k; j++){
                    if(g.low[j] < g1.high[j]){
                        g.merge(g1);
                        d.remove(g1);
                        f = true;
                        break;
                    }
                }
                if(!f){
                    break;
                }
            }
            while((g1 = d.higher(g)) != null){
                boolean f = false;
                for(int j = 0; j < k; j++){
                    if(g.high[j] > g1.low[j]){
                        g.merge(g1);
                        d.remove(g1);
                        f = true;
                        break;
                    }
                }
                if(!f){
                    break;
                }
            }
            d.add(g);
            // System.out.println(d);
            pw.print(d.last().size + "\n");
        }

        pw.close();
        br.close();
    }
}

class Pair implements Comparable<Pair>{
    public int x, y;

    Pair(int _x, int _y){
        x = _x;
        y = _y;
    }

    public String toString(){
        return x + "," + y;
    }

    public int compareTo(Pair p){
        if(x != p.x) return x < p.x ? -1 : 1;
        else if(y != p.y) return y < p.y ? -1 : 1;
        return 0;
    }
}

class Group implements Comparable<Group>{
    public int[] low, high;
    public int size;
    public static int k;

    Group(int[] a){
        low = new int[k];
        high = new int[k];
        for(int i = 0; i < k; i++){
            low[i] = a[i];
            high[i] = a[i];
        }
        size = 1;
    }

    public int compareTo(Group g){
        return low[0] - g.low[0];
    }

    public void merge(Group g){
        for(int i = 0; i < k; i++){
            low[i] = Math.min(low[i], g.low[i]);
            high[i] = Math.max(high[i], g.high[i]);
        }
        size += g.size;
    }

    public String toString(){
        return Arrays.toString(low) + "," + Arrays.toString(high);
    }
}

#include <bits/stdc++.h>
using namespace std;
const int N = 10;
int n, k;
struct Node {
  int mx[N], mn[N], siz;
  bool operator<(const Node &a) const {
    for (int i = 0; i < k; ++i)
      if (mx[i] > a.mn[i]) return 0;
    return 1;
  }
} t;
set<Node> s;
set<Node>::iterator it;
int main() {
  scanf("%d%d", &n, &k);
  for (int i = 1; i <= n; ++i) {
    t.siz = 1;
    for (int j = 0; j < k; ++j) scanf("%d", &t.mx[j]), t.mn[j] = t.mx[j];
    while ((it = s.find(t)) != s.end()) {
      t.siz += it->siz;
      for (int j = 0; j < k; ++j)
        t.mx[j] = max(t.mx[j], it->mx[j]), t.mn[j] = min(t.mn[j], it->mn[j]);
      s.erase(it);
    }
    s.insert(t);
    printf("%d\n", (--s.end())->siz);
  }
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int n, a, b, c;
  cin >> n >> a >> b >> c;
  int i, j;
  j = n % 4;
  if (j == 1) {
    cout << min(min(3 * a, b + a), c);
  } else if (j == 2) {
    cout << min(min(2 * a, b), 2 * c) << endl;
  } else if (j == 3) {
    cout << min(min(a, 3 * c), b + c) << endl;
  } else {
    cout << 0 << endl;
  }
  return 0;
}

n, a, b, c = map(int, input().split())
h=n%4
if h==0:
	d=0
else:
	if h==1:
		d=min(a*3,a+b,c)
	if h==2:
		d=min(a*2,b,c*2)
	if h==3:
		d=min(a,b+c,c*3)
print(d)


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, t, i, k;
  cin >> n >> t;
  string s;
  cin >> s;
  for (i = 0; i < n; i++) {
    if (s[i] == '.') break;
  }
  if (i == n) {
    cout << s << endl;
    return 0;
  }
  i++;
  for (k = i; k < n; k++) {
    if (s[k] >= '5') break;
  }
  if (k == n) {
    cout << s << endl;
    return 0;
  }
  k--;
  int end, flag = 0;
  if (s[k] != '.') {
    while (t > 0 && k >= i && s[k + 1] >= '5') {
      s[k] += 1;
      k--;
      t--;
    }
    end = k + 1;
    if (s[k] == '.' && t != 0) {
      if (s[k + 1] >= '5') {
        flag = 1;
        end = k - 1;
      }
    }
  } else {
    end = k - 1;
    flag = 1;
  }
  s = s.substr(0, end + 1);
  int end_s = i - 2;
  if (t > 0 && flag == 1) {
    while (end_s >= 0 && s[end_s] == '9') {
      s[end_s] = '0';
      end_s--;
    }
    if (end_s == -1)
      s = '1' + s;
    else
      s[end_s]++;
  }
  cout << s << endl;
  return 0;
}

n, t = map(int, input().split())
tmp = input()
s = []
for i in range(n):
    s.append(tmp[i])
ind = n
perenos = 0
for i in range(n):
    if (s[i] == '.'):
        nach = i + 1
for i in range(nach, n):
    if (int(s[i]) > 4):
        ind = i
        break
if (ind == n):
    print(*s, sep="")
    exit()
while (t > 0 and s[ind] != '.'):
    if (int(s[ind]) > 3):
        ind -= 1
        perenos = 1
        t -= 1
        if (s[ind] == '9'):
            t += 1
    else:
        s[ind] = str(int(s[ind]) + 1)
        perenos = 0
        break
if s[ind] == '.':
    ind -= 1
    while (s[ind] == '9'):
        s[ind] = '0'
        ind -= 1
    if (ind < 0 and perenos != 0):
        print(1, end="")
        viv = 0
        while (s[viv] != '.'):
            print(s[viv], end="")
            viv += 1
    else:
        s[ind] = str(int(s[ind]) + perenos)
        viv = 0
        while (s[viv] != '.'):
            print(s[viv], end="")
            viv += 1
else:
    while (s[ind] == '9' or s[ind] == '.'):
        if (s[ind] == '.'):
            ind -= 1
            continue
        s[ind] = '0'
        ind -= 1
    s[ind] = str(int(s[ind]) + perenos)
    for i in range(ind + 1):
        print(s[i], end="")


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

public class KefaAndPark {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        Vertex[] v = new Vertex[n];

        int isCat;
        for(int i = 0; i < n; i++) {
            isCat = sc.nextInt();
            if(isCat == 1)
                v[i] = new Vertex(true);
            else
                v[i] = new Vertex(false);
        }

        for(int i = 0; i < n-1; i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();

            v[x-1].adj.add(y-1);
            v[y-1].adj.add(x-1);
        }

        sc.close();
        System.out.println(dfs(0, -1, 0, m, v));
    }

    private static int dfs(int curr, int parent, int cats, int m, Vertex[] v) {
        if(v[curr].hasCat)
            cats++;

        if(cats > m)
            return 0;

        if(v[curr].adj.size() == 1 && v[curr].adj.get(0) == parent) {
            return 1;
        }

        int sum = 0;
        for(int next : v[curr].adj) {
            if(next == parent) continue;
            if(v[curr].hasCat)
                sum += dfs(next, curr, cats, m, v);
            else
                sum += dfs(next, curr, 0, m, v);
        }
        return sum;
    }

    private static class Vertex {
        boolean hasCat;
        List<Integer> adj;

        Vertex(boolean b) {
            hasCat = b;
            adj = new ArrayList<>();
        }
    }
}

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;
int is_cat[MAXN], n, m;
vector<int> g[MAXN];
int ans;
void get_input(), write_output();
void dfs(int, int, int);
int main() {
  get_input();
  dfs(-1, 0, 0);
  write_output();
}
void write_output() { cout << ans << endl; }
void dfs(int dad, int adjcat, int indx) {
  int size = g[indx].size();
  if (is_cat[indx] == 1)
    adjcat++;
  else
    adjcat = 0;
  if (adjcat <= m && size == 1 && indx != 0) {
    ans++;
    return;
  }
  if (adjcat > m) return;
  for (int i = 0; i < size; i++)
    if (g[indx][i] != dad) dfs(indx, adjcat, g[indx][i]);
}
void get_input() {
  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> is_cat[i];
  for (int i = 0; i < n - 1; i++) {
    int x, y;
    cin >> x >> y;
    x--, y--;
    g[x].push_back(y);
    g[y].push_back(x);
  }
}


def F(n):
    a,b = 1,0
    for i in range(n):
        a,b = b,a+b
    return b

def ans(n,k):
    if n == 0:
        return []
    elif n == 1:
        return [1]
    elif k > F(n):
        return [2,1] + [i+2 for i in ans(n-2,k-F(n))]
    else:
        return [1] + [i+1 for i in ans(n-1,k)]

n,k = map(int,input().split())
print(' '.join([str(i) for i in ans(n,k)]))

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;

public class d {

	public static void main(String[] Args) throws Exception {
		fscan sc = new fscan(System.in);
		int n = sc.nextInt();
		pre();
		long index = sc.nextLong() - 1;
		int tot = 0;
		for (int k = 0; k < n; k++) {
			if (cyc[n - k - 1] > index) {
				if (k != 0) {
					System.out.print(" ");
				}
				System.out.print((k + 1));
			} else {
				int taken = 2;
				int rem = n-k-taken;
				index -= cyc[rem + 1];
				while(index >= cyc[rem]){
					index-=cyc[rem];
					rem--;
					taken++;
				}
				for(int j = 0; j < taken;j++){
					if (k+j != 0) {
						System.out.print(" ");
					}
					System.out.print(stuff[taken-1][j]+k+1);
				}
				k+=taken-1;
			}
		}
		System.out.println();
	}

	public static void pre() {
		cyc[0] = 1;
		cyc[1] = 1;
		for (int k = 2; k < 51; k++) {
			cyc[k] = cyc[k-1] +cyc[k-2];
		}
		stuff = new int[51][51];
		for(int k = 0; k < 51; k++){
			for(int j = 0; j <= k; j++){
				if(k - j*2 >= 0){
					stuff[k][j] = k-j*2;
				}
			}
			for(int j = k,i = 1; j >= 0; j--,i+=2){
				if(k-i >= 0){
					stuff[k][j] = k-i;
				}
			}
		}
	}

	public static long[] cyc = new long[51];
	public static int[][] stuff;

	public static class fscan {
		StringTokenizer st;
		BufferedReader br;

		fscan(InputStream in) throws Exception {
			br = new BufferedReader(new InputStreamReader(in));
			st = new StringTokenizer(br.readLine());
		}

		String next() throws Exception {
			if (st.hasMoreTokens()) {
				return st.nextToken();
			}
			st = new StringTokenizer(br.readLine());
			return next();
		}

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

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


#include <bits/stdc++.h>
using namespace std;
int X = 1000000005, H[1005], W[1005], N;
int g(int h, int k, int w) {
  priority_queue<int> q;
  for (int i = 1; i <= N; i++) {
    if (H[i] <= h && W[i] <= h) {
      q.push(W[i] - H[i]);
      w += W[i];
    } else if (W[i] <= h && k) {
      w += H[i];
      k--;
    } else if (H[i] <= h)
      w += W[i];
    else
      return 1000000005;
  }
  while (!q.empty() && k && q.top() > 0) {
    w -= q.top();
    q.pop();
    k--;
  }
  return w * h;
}
int main() {
  cin >> N;
  for (int i = 1; i <= N; i++) cin >> W[i] >> H[i];
  for (int h = 1; h <= 1000; h++) X = min(X, g(h, N / 2, 0));
  cout << X << endl;
  return 0;
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

public class GroupPhoto2 {

	public static void main(String args[] ) throws Exception {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    PrintWriter p = new PrintWriter(System.out);

	    StringTokenizer st1 = new StringTokenizer(br.readLine());
	    int n = ip(st1.nextToken());

		int w[] = new int[n];
		int h[] = new int[n];

		for(int i=0;i<n;i++){
		    StringTokenizer st2 = new StringTokenizer(br.readLine());
		    w[i] = ip(st2.nextToken());
		    h[i] = ip(st2.nextToken());
		}

		int ans = Integer.MAX_VALUE;
		for(int mH = 1;mH <= 1000;mH++){

			int wid = 0;
			boolean done[] = new boolean[n];

			ArrayList<TwoInt> diff = new ArrayList<TwoInt>();

			int comp = 0;
			for(int i=0;i<n;i++){
				if(h[i] > mH){
					if(w[i] > mH){
						comp = n+1;
						break;
					}
					wid += h[i];
					comp++;
					done[i] = true;
				}
				else{
					if(h[i] < w[i] && w[i] <= mH)
						diff.add(new TwoInt(i,w[i] - h[i]));
					else{
						wid += w[i];
						done[i] = true;
					}
				}
			}

			if(comp <= n/2){
				Collections.sort(diff);
				int s = diff.size();
				int left = (n/2) - comp;
				for(int i=1;i<=Math.min(s,left);i++){
					int index = diff.get(s-i).index;
					done[index] = true;
					wid += h[index];
				}

				for(int i=0;i<n;i++){
					if(!done[i])
						wid += w[i];
				}

				//if(mH*wid < ans)
					//System.out.println(mH + " " + wid);

				ans = Math.min(mH*wid,ans);
			}
		}

		p.println(ans);
	    p.close();
	}

	public static int ip(String s){
		return Integer.parseInt(s);
	}
}

class TwoInt implements Comparable<TwoInt>{
	int index,diff;

	TwoInt(int i,int d){
		this.index = i;
		this.diff = d;
	}

	public int compareTo(TwoInt arg0) {
		return this.diff - arg0.diff;
	}

}


#include <bits/stdc++.h>
using namespace std;
struct BOX {
  long long len, num;
} box[100005];
bool cmp(BOX a, BOX b) { return a.len < b.len; }
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) cin >> box[i].len >> box[i].num;
  sort(box, box + n, cmp);
  for (int i = 0; i < n - 1; i++) {
    if (2 * box[i + 1].len - 2 * box[i].len < 32) {
      int t = ceil(box[i].num * 1.0 /
                   ((1 << (2 * box[i + 1].len - 2 * box[i].len)))) -
              box[i + 1].num;
      if (t > 0) box[i + 1].num += t;
    }
  }
  long long t = box[n - 1].num;
  int i;
  for (i = 1;; i++) {
    if (1 << (2 * i) >= t) break;
  }
  cout << i + box[n - 1].len << endl;
  return 0;
}

from math import*
n = int(input())
v=0
for i in range(n):
    a = [int(x)for x in input().split(' ')]
    k = ceil(fabs(log(a[1],4)))
    if k==0: k=1
    if k+a[0]>v:
        v = k+a[0]
print(v)


#Problem Set N: Collaborated with no one
n = input()

in_visit = 0
out_visit = 0

for i in range(len(n)):
    if n[i] == '+':
        in_visit += 1

        if out_visit:
            out_visit -= 1

    elif n[i] == '-':
        out_visit += 1

        if in_visit:
            in_visit -= 1

print(in_visit + out_visit)

#include <bits/stdc++.h>
using namespace std;
signed main() {
  string s;
  cin >> s;
  long long maxx = 0, minn = 0;
  long long d = 0;
  for (long long i = 0; i < s.length(); i++) {
    if (s[i] == '+')
      d++;
    else
      d--;
    maxx = max(maxx, d);
    minn = min(minn, d);
  }
  cout << maxx - minn << endl;
}


import java.util.*;

public class Main {

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

       int n;
       n = input.nextInt();
       int a[][] = new int[n][2];
        for (int i = 0; i < n; i++) {
            a[i][0] = input.nextInt();
            a[i][1] = input.nextInt();
        }

        Arrays.sort(a,(x,y)->(x[0]-y[0]));
        Arrays.sort(a,(x,y)->(x[1]-y[1]));
        long points=a[n-1][0];
        int iCanPlay=a[n-1][1];

        for (int i = n-2; i >=0; i--) {

            if(iCanPlay>0)
            {

                points+=a[i][0];
                iCanPlay--;
                iCanPlay+=a[i][1];
            }
            else
                break;
        }
        System.out.println(points);

    }
}

n=int(input())
arr=[]
for i in range(n):
	a,b=map(int,input().split())
	arr.append((b,a))
arr.sort(reverse=True)
counter=1
ans=0
i=0
while(counter and i<n):
	counter-=1
	counter+=arr[i][0]
	ans+=arr[i][1]
	i+=1
print(ans)


import java.util.*;
import java.io.*;
import java.math.BigInteger;
import java.text.*;
public class cf5 {
    static long mod = (long)1e9 + 7;
    static long mod1 = 998244353;
    static FastScanner f;
    static PrintWriter pw = new PrintWriter(System.out);
    static Scanner S = new Scanner(System.in);
    static long x0; static long y0;
    public static void solve()throws IOException {
        int n = f.ni(); int m = f.ni();
        int prices[] = inpint(n); sort(prices);
        HashMap<String , Integer> freq = new HashMap<>();
        for(int i = 0; i < m; ++i) {
            String x = f.next();
            if(freq.containsKey(x)) freq.put(x , freq.get(x) + 1);
            else freq.put(x , 1);
        }
        int fr[] = new int[freq.size()]; int i = 0;
        for(Integer value : freq.values()) {
            fr[i] = value; ++i;
        }
        sort(fr);
        int best = 0 , worst = 0 , j = fr.length - 1;
        for(i = n - 1; i >= n - freq.size(); --i , --j) {
            worst += fr[j] * prices[i];
        }
        j = fr.length - 1;
        for(i = 0; i < freq.size(); ++i , --j) {
            best += fr[j] * prices[i];
        }
        pn(best + " " + worst);
    }
    public static void main(String[] args)throws IOException {
        init();
        int t = 1;
        while(t --> 0) {solve();}
        pw.flush();
        pw.close();
    }

/******************************END OF MAIN PROGRAM*******************************************/
    public static void init()throws IOException{if(System.getProperty("ONLINE_JUDGE")==null){f=new FastScanner("");}else{f=new FastScanner(System.in);}}
    public static class FastScanner {
        BufferedReader br;StringTokenizer st;
        FastScanner(InputStream stream){try{br=new BufferedReader(new InputStreamReader(stream));}catch(Exception e){e.printStackTrace();}}
        FastScanner(String str){try{br=new BufferedReader(new FileReader("!a.txt"));}catch(Exception e){e.printStackTrace();}}
        String next(){while(st==null||!st.hasMoreTokens()){try{st=new StringTokenizer(br.readLine());}catch(IOException e){e.printStackTrace();}}return st.nextToken();}
        String nextLine()throws IOException{return br.readLine();}int ni(){return Integer.parseInt(next());}long nl(){return Long.parseLong(next());}double nextDouble(){return Double.parseDouble(next());}
    }
    public static void pn(Object o){pw.println(o);}
    public static void p(Object o){pw.print(o);}
    public static void pni(Object o){pw.println(o);pw.flush();}
    static int gcd(int a,int b){if(b==0)return a;else{return gcd(b,a%b);}}
    static long gcd(long a,long b){if(b==0)return a;else{return gcd(b,a%b);}}
    static long exgcd(long a,long b){if(b==0){x0=1;y0=0;return a;}long temp=exgcd(b,a%b);long t=x0;x0=y0;y0=t-a/b*y0;return temp;}
    static long pow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=res*a;b>>=1;a=a*a;}return res;}
    static long mpow(long a,long b){long res=1;while(b>0){if((b&1)==1)res=((res%mod)*(a%mod))%mod;b>>=1;a=((a%mod)*(a%mod))%mod;}return res;}
    static long mul(long a , long b){return ((a%mod)*(b%mod)%mod);}
    static long adp(long a , long b){return ((a%mod)+(b%mod)%mod);}
    static boolean isPrime(long n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
    static boolean isPrime(int n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(int i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
    static HashSet<Long> factors(long n){HashSet<Long> hs=new HashSet<Long>();for(long i=1;i<=(long)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
    static HashSet<Integer> factors(int n){HashSet<Integer> hs=new HashSet<Integer>();for(int i=1;i<=(int)Math.sqrt(n);i++){if(n%i==0){hs.add(i);hs.add(n/i);}}return hs;}
    static HashSet<Long> pf(long n){HashSet<Long> ff=factors(n);HashSet<Long> ans=new HashSet<Long>();for(Long i:ff)if(isPrime(i))ans.add(i);return ans;}
    static HashSet<Integer> pf(int n){HashSet<Integer> ff=factors(n);HashSet<Integer> ans=new HashSet<Integer>();for(Integer i:ff)if(isPrime(i))ans.add(i);return ans;}
    static int[] inpint(int n){int arr[]=new int[n];for(int i=0;i<n;i++){arr[i]=f.ni();}return arr;}
    static long[] inplong(int n){long arr[] = new long[n];for(int i=0;i<n;i++){arr[i]=f.nl();}return arr;}
    static boolean ise(int x){return ((x&1)==0);}static boolean ise(long x){return ((x&1)==0);}
    static int gnv(char c){return Character.getNumericValue(c);}
    static int log(long x){return x==1?0:(1+log(x/2));} static int log(int x){return x==1?0:(1+log(x/2));}
    static void sort(int[] a){ArrayList<Integer> l=new ArrayList<>();for(int i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
    static void sort(long[] a){ArrayList<Long> l=new ArrayList<>();for(long i:a)l.add(i);Collections.sort(l);for(int i=0;i<a.length;++i)a[i]=l.get(i);}
    static void sort(ArrayList<Integer> a){Collections.sort(a);}
}

3 3
4 2 3
wivujdxzjm
awagljmtc
wivujdxzjm

6 5
3 5 1 6 8 1
peach
grapefruit
banana
orange
orange

4 3
5 3 10 3
xzjhplrzkbbzkypfazf
xzjhplrzkbbzkypfazf
h

2 2
91 82
eiiofpfpmemlakcystpun
mcnzeiiofpfpmemlakcystpunfl

12 18
42 44 69 16 81 64 12 68 70 75 75 67
fm
qamklzfmrjnqgdspwfasjnplg
qamklzfmrjnqgdspwfasjnplg
qamklzfmrjnqgdspwfasjnplg
l
l
l
fm
qamklzfmrjnqgdspwfasjnplg
l
nplgwotfm
p
l
amklzfm
tkpubqamklzfmrjn
pwf
fm
p

n, m = input().split(" ")
n = int(n)
m = int(m)
priceList = []
res = []
least = 0
most = 0
fruitCount = 0
seq = input().split(" ")
for i in seq:
    priceList.append(int(i))

item = []
count = []

for i in range(m):
    inp = input()
    if inp in item:
        count[item.index(inp)] += 1
    else:
        item.append(inp)
        count.append(1)
        fruitCount += 1

count.sort()
count.reverse()
priceList.sort()

for i in range(len(count)):
    least += priceList[i] * count[i]

res.append(str(least))

priceList.reverse()

for i in range(len(count)):
    most += priceList[i] * count[i]

res.append(str(most))

print(" ".join(res))


#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1000010;
int f[maxn], l, vis[maxn];
char s[maxn];
void getf(char *p) {
  int i, j, n = strlen(p);
  f[0] = f[1] = 0;
  for (i = 1; i < n; i++) {
    j = f[i];
    while (j && p[j] != p[i]) j = f[j];
    f[i + 1] = p[j] == p[i] ? j + 1 : 0;
  }
}
int main() {
  int i, j;
  while (~scanf("%s", s)) {
    l = strlen(s);
    getf(s);
    for (i = 0; i <= f[l]; i++) vis[i] = 0;
    for (i = 1; i < l; i++) vis[f[i]] = 1;
    i = f[l];
    int flag = 0;
    while (i) {
      if (vis[i]) {
        flag = 1;
        s[i] = '\0';
        break;
      }
      i = f[i];
    }
    if (!flag)
      printf("Just a legend\n");
    else
      printf("%s\n", s);
  }
  return 0;
}

Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
aaaa
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
papap
Just a legend
Just a legend
Just a legend
fix
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
fix
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
Just a legend
a

from sys import stdin

def findpass(s):
    arr = suff_array(s)
    n = len(s)
    maxidx = arr[n - 1]
    valid = False

    for i in range(n - 1):
        if arr[i] == maxidx:
            valid = True
            break

    if not valid:
        maxidx = arr[maxidx - 1]

    if maxidx == 0:
        return "Just a legend"
    return s[:maxidx]

def suff_array(s):
    n = len(s)
    table = [0] * n

    pos, i = 0, 1

    while i < n:
        if s[pos] == s[i]:
            table[i] = pos + 1
            pos += 1
            i += 1
        elif pos == 0:
            i += 1
        else:
            pos = table[pos - 1]

#    print(table)
    return table

if __name__ == "__main__":
    s = stdin.readline().strip()
    print(findpass(s))


#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  int a1, a2, k1, k2, ans1, ans2, n;
  cin >> a1 >> a2 >> k1 >> k2 >> n;
  int x = n - (k1 - 1) * a1 - (k2 - 1) * a2;
  if (x <= 0)
    ans1 = 0;
  else
    ans1 = x;
  if (k1 <= k2) {
    ans2 = n / k1;
    if (ans2 > a1) {
      ans2 = a1;
      ans2 += (n - a1 * k1) / k2;
    }
  }
  if (k1 > k2) {
    ans2 = n / k2;
    if (ans2 > a2) {
      ans2 = a2;
      ans2 += (n - a2 * k2) / k1;
    }
  }
  if (ans1 > a1 + a2) ans1 = a1 + a2;
  if (ans2 > a1 + a2) ans2 = a1 + a2;
  cout << ans1 << " " << ans2 << endl;
}


#include <bits/stdc++.h>
using namespace std;
int color[200010], Max[200010];
pair<int, int> p[200010];
int main() {
  int n, q;
  memset(color, -1, sizeof(color));
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    int a;
    scanf("%d", &a);
    p[i] = make_pair(1, a);
  }
  scanf("%d", &q);
  for (int i = 1; i <= q; i++) {
    int opt, x, y;
    scanf("%d", &opt);
    if (opt == 1) {
      scanf("%d%d", &x, &y);
      p[x] = make_pair(i, y);
    } else {
      scanf("%d", &x);
      color[i] = x;
    }
  }
  Max[q + 1] = -1;
  for (int i = q; i > 0; i--) {
    Max[i] = max(Max[i + 1], color[i]);
  }
  for (int i = 1; i <= n; i++) {
    if (i > 1) printf(" ");
    printf("%d", max(p[i].second, Max[p[i].first]));
  }
  return 0;
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Jaynil
 */
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);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        public void remove(TreeMap<Integer, Integer> map, int x) {
            if (map.get(x) > 1) {
                map.put(x, map.get(x) - 1);
            } else {
                map.remove(x);
            }
        }

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int a[] = new int[n];
            for (int i = 0; i < n; i++) a[i] = in.nextInt();
            int q = in.nextInt();
            ArrayList<int[]> qs = new ArrayList<>();
            TreeMap<Integer, Integer> map = new TreeMap<>();
            int max = -1;
            for (int i = 0; i < q; i++) {
                int ty = in.nextInt();
                if (ty == 1) {
                    int u = in.nextInt() - 1;
                    int v = in.nextInt();
                    qs.add(new int[]{1, u, v});
                } else {
                    int u = in.nextInt();
                    map.put(u, map.getOrDefault(u, 0) + 1);
                    max = Math.max(u, max);
                    qs.add(new int[]{2, u});
                }
            }
            for (int i = 0; i < n; i++) {
                a[i] = Math.max(a[i], max);
            }
            for (int i = 0; i < q; i++) {
                int xx[] = qs.get(i);
                if (xx[0] == 1) {
                    a[xx[1]] = xx[2];
                    if (map.size() > 0) {
                        a[xx[1]] = Math.max(a[xx[1]], map.lastKey());
                    }
                } else {
                    remove(map, xx[1]);
                }
            }
            for (int i = 0; i < n; i++) {
                out.print(a[i] + " ");
            }
        }

    }

    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 nextInt() {
            return Integer.parseInt(next());
        }

    }
}


#include <bits/stdc++.h>
using namespace std;
long long countDig(long long s) { return floor(log10(s) + 1); }
int main() {
  long long num;
  int luckyNums = 0;
  string n;
  cin >> num;
  int digits = countDig(num);
  n = to_string(num);
  for (int i = 0; i < digits; i++) {
    if (n[i] == '4' || n[i] == '7') luckyNums++;
  }
  if (luckyNums == 4 || luckyNums == 7)
    cout << "YES" << endl;
  else
    cout << "NO" << endl;
  return 0;
}

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

import java.util.Scanner;

public class P_110A {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String num = scanner.next();
        int luckynum = 0;
        for (int i=0; i<num.length(); i++) {
            char c = num.charAt(i);
            if (c == '4' || c == '7') {
                luckynum++;
            }
        }

        if (luckynum == 4 || luckynum == 7)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}


#include <bits/stdc++.h>
using namespace std;
string s;
int m = 0, l = 1;
void rd(int &);
void wrt(int);
int main() {
  cin >> s;
  s += s;
  s += s[s.size() - 1];
  for (int i = 1; i <= (s.size() - 1); ++i)
    if (s[i - 1] != s[i])
      ++l;
    else
      m = max(m, l), l = 1;
  m = min(m, (int)s.size() / 2);
  cout << m;
  return 0;
}
void rd(int &x) {
  static int s, c;
  x = 0;
  s = 1;
  c = getchar();
  while (c != '-' && (c < 48 || 57 < c)) c = getchar();
  if (c == '-') s = -1, c = getchar();
  while (47 < c && c < 58) x = (x << 3) + (x << 1) + c - 48, c = getchar();
  x = s * x;
}
void wrt(int x) {
  if (x < 0) {
    putchar('-');
    x = -x;
  }
  static int y, cc;
  y = cc = 0;
  while (x && x % 10 == 0) ++cc, x /= 10;
  while (x > 9) y = y * 10 + x % 10, x /= 10;
  putchar(x + 48);
  while (y) putchar(y % 10 + 48), y /= 10;
  while (cc--) putchar(48);
}

bwbbwbwbwbwbw wbwbwbwbwb bwbbwbwbwbwbwbwbwbwbw wbwbwbwbwbwbwbwbwbwbwbwb bwbbwbwbwbwbwbwbwbwbwbwbwb bwbbwbwbwbwbwbwbwbwbwb bwbw bwbbwbwbwbwbwbw bwwbwwb wbwbwbwbwbwbwb wbwbwb bwbbwbwbw wbwbwbwbwbwbwbwbwbw www wbwbwbwbwbwbw wbwbwbwbwbwbwbwbwbwbw bwwbwwb wbwbwbwbwb bwbbwbwbwbwbwb wbwbwwwbwb wbwbwbwbwbw wbwbwbwbwbwbwbwbwbwbwbw wbwbwbwbwbwbwbwbw bwbbwbwbwbwb bwbbwbwbwbwbwbwb wbwbwbwbwbwbwbwbwb bwwwbwwbw bwbbwbwbwbwbwbwbwbw wbwbwbwbwbwbwbwb wbwbwbwbwbwbwbwbwbwbwbwbwb bwbbwbwbwbwbwbwbwbwbwbwb bwbbwbwbwbw bww wbwbwbwbwbwbwbw bwbbwbwbwbwbwbwbwbwbwbw bwbbwbw bwbbwbwbwb bwb wbwbwbwbwbwb bwbbwbwbwbwbwbwbwbwb wbwbwbwbwbwbwbwbwbwbwb wbwbwbwb bwbwbbbbwb wbwbwbwbwbwbwbwbwbwbwbwbw wbwbwbwbwbwbwbwbwbwb bwbbwbwbwbwbwbwbwbwbwbwbw bwwwbwwbw bwbbwbwb bwbbwbwbwbwbwbwbwb bwbbwbwbwbwbwbwbw

import sys

s = input()

n = len(s)

if n == 1:
	print(1)
	sys.exit(0)

for i in range(n-1):
	if s[i] == s[i+1] and (s[n-1] != s[0]):
		x = s[:i+1]
		y = s[i+1:n]
		s = x[::-1] + y[::-1]
ans = 1
mx = 1
for i in range(1, n):
	if s[i] != s[i-1]:
		mx += 1
	else:
		ans = max(mx, ans)
		mx = 1
print(max(mx, ans))


# We are the all singing all dancing crap of the world

n = int(input())

khela = []
for i in range(n):
    s = input()
    khela.append([len(s),s])

khela = sorted(khela)
if (n==1):
    print('YES')
    print(khela[0][1])

else:
    lent = len(khela)
    for i in range(lent-1):
        c = 0
        for ii in range(i+1,khela[i+1][0]-khela[i][0]+2+i):
    #        print('i is ',
    #                 i, 'ii is ',ii, '',khela[i][1],'== ??', khela[i+1][1][ii-i-1:ii+khela[i][0]-i-1])
    #
            if (khela[i][1]==khela[i+1][1][ii-i-1:ii+khela[i][0]-i-1]):
                c = 1
        if c==0:
            break

    if c == 1:
        print("YES")
        for i in range(len(khela)):
            print(khela[i][1])

    else:
        print('NO')

#include <bits/stdc++.h>
using namespace std;
bool is_substring(string s1, string s2) {
  for (int i = 0; i <= (s1.size() - s2.size()); i++) {
    if (s1.substr(i, s2.size()) == s2) return true;
  }
  return false;
}
void solution() {
  long long int n;
  string s;
  cin >> n;
  vector<pair<int, string> > mpp;
  for (int i = 0; i < n; i++) {
    cin >> s;
    mpp.push_back(make_pair(s.size(), s));
  }
  sort((mpp).begin(), (mpp).end());
  for (int j = 0; j < mpp.size() - 1; j++) {
    if (is_substring(mpp[j + 1].second, mpp[j].second) == false) {
      cout << "NO";
      return;
    }
  }
  cout << "YES\n";
  for (int i = 0; i < mpp.size(); i++) {
    cout << mpp[i].second << "\n";
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long int t;
  t = 1;
  while (t--) {
    solution();
    cout << "\n";
  }
}


#include <bits/stdc++.h>
using namespace std;
int a[105], v[105];
bool used[105];
int main() {
  int n, m;
  scanf("%d %d", &n, &m);
  scanf("%d", &v[1]);
  for (int i = 2; i <= m; i++) {
    scanf("%d", &v[i]);
    int dif = v[i] - v[i - 1];
    if (dif <= 0) dif += n;
    if (used[dif] && a[v[i - 1]] != dif) {
      printf("-1");
      return 0;
    }
    used[dif] = true;
    a[v[i - 1]] = dif;
  }
  for (int i = 1; i <= n; i++) {
    if (a[i] == 0) {
      for (int j = 1; j <= n; j++) {
        if (!used[j]) {
          a[i] = j;
          used[j] = true;
          break;
        }
      }
      if (a[i] == 0) {
        printf("-1");
        return 0;
      }
    }
  }
  for (int i = 1; i <= n; i++) {
    printf("%d ", a[i]);
  }
  return 0;
}

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

public class Solution {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
           int n=sc.nextInt();
           int m=sc.nextInt();

           int l[]=new int[m];
           int freq[]=new int[n+1];
           int a[]=new int[n];

            for(int i=0;i<n;i++)
                a[i]=0;

           for(int i=1;i<=n;i++)
               freq[i]=0;

           for(int i=0;i<m;i++)
           {
                l[i]=sc.nextInt();
           }

            for(int i=1;i<m;i++)
            {
                int value=l[i]-l[i-1];
                if(value<=0)
                    value+=n;
                if(freq[value]==1&&a[l[i-1]-1]!=value)
                {
                    System.out.print("-1");
                    return;
                }
                if(a[l[i-1]-1]!=0&&a[l[i-1]-1]!=value)
                {
                    System.out.print("-1");
                    return;
                }
                a[l[i-1]-1]=value;
                freq[value]=1;
            }
            for(int i=0;i<n;i++)
            {
                if(a[i]==0)
                {
                    for(int j=1;j<=n;j++)
                    {
                        if(freq[j]==0)
                        {
                            a[i]=j;
                            freq[j]=1;
                            break;
                        }
                    }
                }
            }
        for(int i=0;i<n;i++)
            System.out.print(a[i]+" ");
    }
}