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

public class GameWithArray {
    public static void main(String[] args) {
        FastScanner fs = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        int n = fs.nextInt();
        int sum = fs.nextInt();

        int x = sum - (n-1);
        int y = n - 1;

        if(x - y > 1){
            out.println("YES");
            for(int i = 0; i < n; i++) {
                if (i == n - 1)
                    out.print(x);
                else
                    out.print(1 + " ");
            }
            out.println();
            out.println(x-1);
        }else{
            out.println("NO");
        }
        out.close();
    }

    static class FastScanner {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");

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

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

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

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

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, s;
  cin >> n >> s;
  if (2 * n <= s) {
    cout << "YES\n";
    for (int i = 0; i < n - 1; i++) {
      cout << 2 << ' ';
      s -= 2;
    }
    cout << s << '\n' << 1;
  } else {
    cout << "NO";
  }
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 2000 + 9;
char a[N];
int v[N], sum[N];
int main() {
  int i, j, r, n, t, m, k, ans = 0;
  cin >> t;
  a[0] = 'a';
  while (t--) {
    memset(v, 0, sizeof v);
    memset(a, 0, sizeof a);
    cin >> n >> m >> k;
    int cnt = k, num = k;
    for (i = 1; i <= k; i++) {
      a[i] = 'a' + i - 1;
      v[i - 1]++;
    }
    for (i = k; i <= m - 1; i++) {
      a[i + 1] = a[i];
      v[a[i] - 'a']++;
    }
    for (i = m + 1, j = 1; i <= n; i++, j++) {
      int f = a[j] - 'a';
      v[f]--;
      if (v[f] == 0) {
        a[i] = a[j];
        v[f]++;
      } else
        for (r = 0; r < 24; r++) {
          if (v[r] != 0) {
            a[i] = r + 'a';
            break;
          }
        }
    }
    for (i = 1; i <= n; i++) cout << a[i];
    cout << endl;
  }
}

import string

def construct(n, a, b):
    return ((string.ascii_lowercase[:b] + "a" * (a - b)) * (n // a + 1))[:n]

t = int(input())
for i in range(t):
    n, a, b = map(int, input().split())
    print(construct(n, a, b))


import sys,collections as cc
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))

def div(b):
	an=[]
	for i in range(1,int(b**0.5)+1):
		if b%i==0:
			an.append(i)
			if i!=b//i:
				an.append(b//i)
	return an
n,=I()
ar=[]
vis=[-1]*(10**5+2)
for i in range(n):
	a,b=I()
	an=0
	dv=div(a)
	#print(dv,vis[:20])
	for j in dv:
		if vis[j]<i-b:
			an+=1
		vis[j]=i
	print(an)

import java.util.Arrays;
import java.util.Scanner;
public class PetyaAndDivisors {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] result = new int[n];
        int[] divisor = new int[100000+5];
        Arrays.fill(divisor, -1);
        for (int i = 0; i < n; i++) {
            int res = 0;
            int x = sc.nextInt();
            int y = sc.nextInt();
            for(int j = 1; j * j <= x; j++){
                if(x % j == 0)
                {
                    if(i - y > divisor[j])
                        res++;
                    if(j * j != x && i - y > divisor[x / j])
                        res++;
                    divisor[j] = divisor[x / j] = i;

                }
            }
            result[i] = res;
        }
        for (int i = 0; i < n; i++)
            System.out.println(result[i]);
    }
}


#include <bits/stdc++.h>
using namespace std;
vector<long long> let(26, 0);
int main() {
  long long n;
  cin >> n;
  if (n <= 2) {
    cout << "No" << endl;
  } else {
    cout << "Yes" << endl;
    cout << n - 1 << " ";
    for (int i = 0; i < n - 1; i++) {
      cout << i + 1 << " ";
    }
    cout << endl << 1 << " " << n << endl;
  }
  return 0;
}

"""#N=int(input())
n,k=map(int,input().split())
s=input()
L=[0]*26
#s=[int(x) for x in input().split()]
for j in range(0,len(s)):
    L[ord(s[j])-65]=L[ord(s[j])-65]+1
ans=1000000007
for j in range(0,k):
    ans=min(ans,L[j])
ans=k*ans
print(ans)"""
import math
pre=[]
for i in range(0,45010):
    pre.append(((i*(i+1))//2))
#print(pre[:100])
n=int(input())
if(n==0 or n==1 or n==2):
    print('No')
else:
    temp=0
    t=pre[n]
    pos=-1
    for j in range(1,n+1):
        if(math.gcd(pre[j],t-pre[j])>1):
            temp=1
            pos=j
            break
    if(temp==0):
        print('No')
    else:
        print('Yes')
        print(pos,end=" ")
        for j in range(1,pos+1):
            print(j,end=" ")
        print(" ")
        print(n-j,end=" ")
        for j in range(pos+1,n+1):
            print(j,end=" ")
        print(" ")


#include <bits/stdc++.h>
using namespace std;
const int N = 3005;
const long long mod = 1e9 + 7;
using namespace std;
int n;
char novi[N];
char s[N], t[N];
vector<int> v;
void op(char *s, int n, int pos) {
  for (int i = pos; i <= n; i++) novi[n - i + 1] = s[i];
  for (int i = 1; i < pos; i++) novi[i + (n - pos + 1)] = s[i];
  for (int i = 1; i <= n; i++) s[i] = novi[i];
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr), cout.tie(nullptr);
  cin >> n >> (s + 1) >> (t + 1);
  for (auto(i) = (1); (i) <= (n); (i)++) {
    int ok = 0;
    for (auto(j) = (1); (j) <= (n - i + 1); (j)++)
      if (t[i] == s[j]) {
        ok = j;
        break;
      }
    if (!ok) {
      return cout << -1 << endl, 0;
    }
    if (ok + 1 <= n) {
      v.push_back(n - ok);
      op(s, n, ok + 1);
    }
    v.push_back(1);
    op(s, n, n);
    v.push_back(n);
    op(s, n, 1);
  }
  cout << v.size() << endl;
  for (auto i : v) cout << i << " ";
  return cout << endl, 0;
}

n = int(input())
t = input()[:n]
s = input()[:n]

ops =[]

def shift(k, cur):
    if k == 0:
        return cur
    return cur[:-k-1:-1] + cur [:-k]

def move_to_front(k, curst):
    if k == n-1:
        ops.append(1)
        curst = curst[-1] +curst [:-1]
    else:
        ops.append(n-1)
        ops.append(k)
        ops.append(1)

        curst = curst[k] + curst[:k] + curst[-1:k:-1]

    return curst

def find_char(char, t):
    for m,cur_c in enumerate(t[::-1]):
        if cur_c == char:
            # print(t, 'found', char, ' at', n-m -1)
            return n- m -1
    return 0

# t = 'abcdefg'
# for j in range(len(t)):
#     print('before', j, t)
#     t = move_to_front(j, t )
#     print(' after', j, t)
#     print()

from collections import Counter

scount = Counter(s)
tcount = Counter(t)

ori_t = t

if scount != tcount:
    print(-1)
    exit()

for char in s[::-1]:
    t = move_to_front(find_char(char, t), t)
    # print('got t', t)
print(len(ops))
print(*ops)

# for op in ops:
#     print(op, ori_t, shift(op, ori_t))
#     ori_t = shift(op, ori_t)
#
# print(ori_t)


#include <bits/stdc++.h>
using namespace std;
vector<long long> v1;
long long power(long long x, long long y) {
  if (y == 0)
    return 1;
  else if (y % 2 == 0)
    return power(x, y / 2) * power(x, y / 2);
  else
    return x * power(x, y / 2) * power(x, y / 2);
}
int main() {
  long long n;
  long long num, i;
  for (i = 1; i <= 30; i++) {
    num = (power(2, i) - 1) * power(2, i - 1);
    v1.push_back(num);
  }
  cin >> n;
  for (i = 29; i >= 0; i--) {
    if ((n % v1[i]) == 0) {
      break;
    }
  }
  cout << v1[i] << endl;
  return 0;
}

a=[]
for i in range (1,9):
  a.append((pow(2,i)-1)*pow(2,i-1))
  #print(a)
b= int(input())
c=1
for i in range(8):
  if(b%a[i] is 0):
    c=a[i]
print(c)


n, a=map(int, input().split())
alp = 180*(n-2)/n
minR=181
x=3
angle=0
for i in range (3, n+1):
    angle = (180*(i-2) - alp*(i-2))/2
    if abs(angle-a)<minR:
        minR=abs(angle-a)
        x=i
print("2 1", x)

#include <bits/stdc++.h>
using namespace std;
int main() {
  double n, a;
  cin >> n >> a;
  cout << 1 << " " << 2 << " ";
  double ans = 1000000;
  double minDiff = 1000000;
  double maxAngle = 180 - 360 / n;
  double stepSize = 180 / n;
  for (int i = 3; i <= n; i++) {
    double angle = maxAngle - stepSize * (i - 3);
    if (fabs(angle - a) < minDiff) {
      minDiff = abs(angle - a);
      ans = i;
    }
  }
  cout << (int)ans;
  return 0;
}


import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;

public class Main {

	public static void main(String[] args) throws IOException {
		try {
			if (new File("input.txt").exists())
				System.setIn(new FileInputStream("input.txt"));
		} catch (SecurityException e) {
		}
		new Thread(null, new Runnable() {
			public void run() {
				try {
					new Main().run();
				} catch (Throwable e) {
					e.printStackTrace();
					exit(999);
				}
			}
		}, "1", 1 << 23).start();
	}

	BufferedReader in;
	PrintWriter out;
	StringTokenizer st = new StringTokenizer("");

	int M = 1000003;
	private void run() throws IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		int n = nextInt();
		long m[] = new long[1001];
		m[0] = 1;
		for(int i = 1 ; i < 1001; i++){
			long pow = 1;
			for(int j = i-1; j >= 0; j--){
				m[i] += m[j] * pow;
				pow *= 2;
				pow %= M;
			}
			m[i] %= M;
		}
		out.println(m[n]);

		in.close();
		out.close();
	}

	void chk(boolean b) {
		if (b)
			return;
		System.out.println(new Error().getStackTrace()[1]);
		exit(999);
	}
	void deb(String fmt, Object... args) {
		System.out.printf(Locale.US, fmt + "%n", args);
	}
	String nextToken() throws IOException {
		while (!st.hasMoreTokens())
			st = new StringTokenizer(in.readLine());
		return st.nextToken();
	}
	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}
	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}
	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
	String nextLine() throws IOException {
		st = new StringTokenizer("");
		return in.readLine();
	}
	boolean EOF() throws IOException {
		while (!st.hasMoreTokens()) {
			String s = in.readLine();
			if (s == null)
				return true;
			st = new StringTokenizer(s);
		}
		return false;
	}
}


n=int(input())
lst=[]
for i in range(n):
    n=input()
    lst.append(n[4:])

for i in lst:
    l=len(i)
    i=int(i)
    #print(i)
    g=0
    p=10
    c=1
    while(c<l):
        g+=p
        p*=10
        c+=1
    #print(g,p)
    while(i<1989+g):
        i+=p
    print(i)

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

public class D {

	BufferedReader br;
	PrintWriter out;
	StringTokenizer st;
	boolean eof;

	static class Olymp {
		int id;
		String s;

		public Olymp(int id, String s) {
			this.id = id;
			this.s = s;
		}
	}

	void solve() throws IOException {
		int n = nextInt();
		for (int i = 0; i < n; i++) {
			String s = nextToken();
			s = s.substring(4);
			int len = s.length();
			long tail = Integer.parseInt(s);

			long start = 1989;
			long pw = 10;
			for (int j = 1; j < len; j++) {
				start += pw;
				pw *= 10;
			}

//			System.err.println(start);

			long res = (Math.floorDiv(start - 1 - tail, pw) + 1) * pw + tail;
			out.println(res);

		}

	}

	D() throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		out.close();
	}

	public static void main(String[] args) throws IOException {
		new D();
	}

	String nextToken() {
		while (st == null || !st.hasMoreTokens()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch (Exception e) {
				eof = true;
				return null;
			}
		}
		return st.nextToken();
	}

	String nextString() {
		try {
			return br.readLine();
		} catch (IOException e) {
			eof = true;
			return null;
		}
	}

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

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

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


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  scanf("%d", &n);
  deque<int> a(n), b(n);
  for (int i = 0; i < n; ++i) scanf("%d", &a[i]);
  for (int i = 0; i < n; ++i) scanf("%d", &b[i]);
  a.erase(find(a.begin(), a.end(), 0));
  b.erase(find(b.begin(), b.end(), 0));
  while (a[0] != 1) a.push_back(a[0]), a.pop_front();
  while (b[0] != 1) b.push_back(b[0]), b.pop_front();
  puts(a == b ? "YES" : "NO");
  return 0;
}

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

import java.util.*;
import java.math.*;
import java.io.*;
import java.text.DecimalFormat;
import java.math.BigInteger;
public class Main{

    public static void main(String[] args)  throws IOException {
        s.init(System.in);

        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n;
        n=s.ni();
        int[] a=new int[n];
        int[] b=new int[n];
        int x,y;
        x=y=0;
        for(int i=0;i<n;i++){
            a[i]=s.ni();
            if(a[i]==0)
                x=i;
        }
        for(int i=0;i<n;i++){
            b[i]=s.ni();
            if(b[i]==0)
                y=i;
        }
        int flag1,flag2;
        flag1=flag2=0;
        int id=0;
        int add=0;
        int ct=0;
        for(int i=0;i<n;i++){
            if(a[i]==b[(y+1)%n]){
                id=i;
                break;
            }
        }
        ct=1;
        int u,v;
        u=id+1;
        v=y+2;
        while(ct<n-1){
            if(a[u%n]==0)
                u++;
            if(b[v%n]==0)
                v++;
            if(a[u%n]!=b[v%n]){
                flag2=1;
                break;
            }
            u++;
            v++;
            ct++;

        }
        if(flag2==0)
            out.println("YES");
        else
            out.println("NO");

        out.close();
    }

    public static class s {
        static BufferedReader reader;

        static StringTokenizer tokenizer;

        /** call this method to initialize reader for InputStream */
        static void init(InputStream input) {
            reader = new BufferedReader(
                        new InputStreamReader(input) );
            tokenizer = new StringTokenizer("");
        }

        /** get next word */
        static String ns() throws IOException {
            while ( ! tokenizer.hasMoreTokens() ) {
                //TODO add check for eof if necessary
                tokenizer = new StringTokenizer(
                    reader.readLine() );
            }
            return tokenizer.nextToken();
        }

        static int ni() throws IOException {
            return Integer.parseInt( ns() );
        }

        static double nd() throws IOException {
            return Double.parseDouble( ns() );
        }
        static long nl() throws IOException {
            return Long.parseLong( ns() );
        }

    }
}


/* package codechef; // don't place package name! */

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

/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out=new PrintWriter(System.out);
        int n=Integer.parseInt(obj.readLine());
        String words[]=new String[n];
        for(int i=0;i<n;i++){
            words[i]=obj.readLine();
        }
        long ans=-1;
        for(int i=0;i<26;i++){
            for(int j=0;j<26;j++){
                ans=Math.max(ans, count((char)(i+'a'),(char)(j+'a'), words));
            }
        }
        out.println(ans);
        out.flush();
        out.close();
    }
    static long count(char a, char b, String words[]){
        long ans=0;
        for(int i=0;i<words.length;i++){
            boolean flag=true;
            char s[]=words[i].toCharArray();
            for(int j=0;j<s.length;j++){
                if(s[j]!=a && s[j]!=b){
                    flag=false;
                    break;
                }
            }
            if(flag)    ans += s.length;
        }
        return ans;
    }
}

7
pavel
erika
alexxxxxxx
gracio
zhenya
sudarev
chelyaba

31
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml
fml

n=int(input())
i=0
x=[]
while i<n:
	x.append(str(input()))
	i+=1
i=25
r=0
while i:
	j=i
	while j:
		j-=1
		t=0
		k=n
		while k:
			k-=1
			y=x[k]
			z=len(y)
			ok=1
			while z:
				z-=1
				if ord(y[z])-ord('a')!=i:
					if ord(y[z])-ord('a')!=j:ok=0
			if ok:t+=len(y)
		if r<t:r=t
	i-=1
print(r)


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

public class CodeForces {
    public static void main(String[] args) {
        FastIO io = FastIO.create();

        int hills = io.nextInt();
        int frogs = io.nextInt();
        int mosquitoes = io.nextInt();

        int[] f = new int[frogs];
        for (int i = 0; i < frogs; i++) {
            f[i] = io.nextInt();
        }

        List<Integer>[] fKillScore = new List[frogs];
        for (int i = 0; i < frogs; i++) {
            fKillScore[i] = new ArrayList<>();
        }
        for (int i = 0; i < mosquitoes; i++) {
            int m = io.nextInt();
            for (int j = 0; j < frogs; j++) {
                int fs = f[j];
                if (m % fs == 0) {
                    fKillScore[j].add(i + 1);
                }
            }
        }

        int min = Integer.MAX_VALUE;
        List<Integer> minIds = new ArrayList<>();
        for (int i = 0; i < frogs; i++) {
            if (min > fKillScore[i].size()) {
                min = fKillScore[i].size();
                minIds.clear();
                minIds.add(i + 1);
            } else if (min == fKillScore[i].size()) {
                minIds.add(i + 1);
            }
        }

        io.println(minIds.size());

        for (Integer e : minIds) {
            io.print(e + " ");
        }

        io.close();
    }

    static class FastIO extends PrintWriter {
        BufferedReader br;
        StringTokenizer st;

        public FastIO(InputStream is, OutputStream os) {
            super(new BufferedOutputStream(os));
            br = new BufferedReader(new InputStreamReader(is));
        }

        public static FastIO create() {
            return new FastIO(System.in, System.out);
        }

        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 nextToken() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

n, m, k = map(int, input().split())
x, y = n, []
a = map(int, input().split())
b = list(map(int, input().split()))
for i, d in enumerate(a):
    c = 0
    for t in b:
        if 0 == t % d:
            c += 1
    if c < x:
        x = c
        y = [i + 1]
    elif c == x:
        y += i + 1,
print(len(y))
print(' '.join(map(str, y)))


n,a,b=int(input()),0,0
for i in map(float,input().split()):a,b=a+i*(1+b*2),i*(b+1)
print(a)

#include <bits/stdc++.h>
using namespace std;
double p[100010];
int main(void) {
  int N;
  cin >> N;
  for (int i = 0; i < N; ++i) {
    cin >> p[i];
  }
  double x = 0.0, ans = 0.0;
  for (int i = 0; i < N; ++i) {
    x = x * p[i] + p[i];
    ans += 2.0 * x;
    ans -= p[i];
  }
  printf("%.9f", ans);
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
const long long FASTIO = []() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  return 0;
}();
signed main() {
  long long n;
  cin >> n;
  set<long long> b, c;
  vector<long long> a(n + 2);
  map<long long, long long> m;
  a[0] = 1e9;
  long long f = 0;
  for (long long i = 1; i <= n; i++) {
    cin >> a[i];
    b.insert(a[i]);
    m[a[i]]++;
    if (m[a[i]] >= 2) f++;
  }
  a[n + 1] = 1e9;
  if (f == 0) {
    cout << 0;
    return 0;
  } else if (f == 1) {
    cout << 1;
    return 0;
  }
  long long ans = 1e9;
  for (long long l = 1; l < n; l++) {
    c = b;
    m[a[l]]--;
    if (m[a[l]] == 0) c.erase(a[l]);
    for (long long r = l + 1; r <= n; r++) {
      m[a[r]]--;
      if (m[a[r]] == 0) c.erase(a[r]);
      if (c.size() == l - 1 + n - r) {
        ans = min(ans, r - l + 1);
      }
    }
    for (long long i = n; i >= l; i--) {
      m[a[i]]++;
    }
  }
  if (ans == 1e9) ans = 1;
  cout << ans;
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.HashMap;
import java.io.InputStream;

/**
 * @author khokharnikunj8
 */

public class Main {
    public static void main(String[] args) {
        new Thread(null, new Runnable() {
            public void run() {
                new Main().solve();
            }
        }, "1", 1 << 26).start();
    }

    void solve() {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        ScanReader in = new ScanReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        BUniqueness solver = new BUniqueness();
        solver.solve(1, in, out);
        out.close();
    }

    static class BUniqueness {
        public void solve(int testNumber, ScanReader in, PrintWriter out) {
            int n = in.scanInt();
            int[] ar = new int[n];
            for (int i = 0; i < n; i++) ar[i] = in.scanInt();
            HashMap<Integer, Integer> count = new HashMap<>();
            boolean flag = false;
            for (int i = 0; i < n; i++) {
                if (count.containsKey(ar[i])) {
                    count.put(ar[i], count.get(ar[i]) + 1);
                    flag = true;
                } else count.put(ar[i], 1);
            }
            if (!flag) {
                out.println(0);
                return;
            }
            int counter = 0;
            for (int i : count.keySet())
                if (count.get(i) > 1) counter++;
            int ans = Integer.MAX_VALUE;
            for (int i = 0; i < n; i++) {
                for (int j = i; j < n; j++) {
                    int already = count.get(ar[j]);
                    count.put(ar[j], already - 1);
                    if (already == 2) counter--;
                    if (counter == 0) {
                        ans = Math.min(ans, j - i + 1);
                    }
                }
                for (int j = i; j < n; j++) {
                    int already = count.get(ar[j]);
                    count.put(ar[j], already + 1);
                    if (already == 1) counter++;
                }
            }
            out.println(ans);
        }

    }

    static class ScanReader {
        private byte[] buf = new byte[4 * 1024];
        private int index;
        private BufferedInputStream in;
        private int total;

        public ScanReader(InputStream inputStream) {
            in = new BufferedInputStream(inputStream);
        }

        private int scan() {
            if (index >= total) {
                index = 0;
                try {
                    total = in.read(buf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (total <= 0) return -1;
            }
            return buf[index++];
        }

        public int scanInt() {
            int integer = 0;
            int n = scan();
            while (isWhiteSpace(n)) n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    integer *= 10;
                    integer += n - '0';
                    n = scan();
                }
            }
            return neg * integer;
        }

        private boolean isWhiteSpace(int n) {
            if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
            else return false;
        }

    }
}


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

arr.sort()

if arr[-1] >= arr[-2] + arr[-3]:
  print("NO")
else:
  print("YES")
  tmp = arr[-1]
  arr[-1] = arr[-2]
  arr[-2] = tmp
  print(' '.join([str(x) for x in arr]))

#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int t, n, i;
  cin >> n;
  long long int a[n], sum = 0;
  for (long long int i = 0; i < n; i++) {
    cin >> a[i];
    sum += a[i];
  }
  sort(a, a + n);
  bool ok = false;
  ;
  swap(a[n - 1], a[n - 2]);
  if (a[n - 2] >= a[n - 1] + a[n - 3]) ok = true;
  if (ok)
    cout << "NO\n";
  else {
    cout << "YES\n";
    for (long long int i = 0; i < n; i++) cout << a[i] << " ";
    cout << endl;
  }
  return 0;
}


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

public class E66 implements Runnable {

	public StreamTokenizer in;

	public PrintWriter out;

	E66() throws IOException {
		in = new StreamTokenizer( new InputStreamReader( System.in ) );
		out = new PrintWriter( System.out );
	}

    int nextInt() throws IOException {
        in.nextToken();
        return ( int ) in.nval;
    }

    void close() throws IOException {
		out.close();
	}

	public void run() {
		try {
			solve();
			close();
		} catch ( Exception e ) {
			e.printStackTrace();
		}
	}

	public void solve() throws IOException {
        int n = nextInt();
        int x = nextInt();
        int[] a = new int[n];
        for ( int i = 0; i < n; i ++ ) {
            a[i] = nextInt();
        }
        Arrays.sort( a );
        if ( n > 0 && a[0] == 1 ) {
            out.println( ( x == 2 ) ? 0 : 1 );
            return;
        }
        boolean[] np = new boolean[1300000];
        int pn = 0;
        for ( int i = 2; i < np.length && i < x; i ++ ) {
            if ( np[i] ) {
                continue;
            }
            if ( Arrays.binarySearch( a, i ) < 0 ) {
                out.println( -1 );
                return;
            }
            pn ++;
            for ( int j = 2 * i; j < np.length; j += i ) {
                np[j] = true;
            }
        }
        out.println( pn );
	}

	public static void main( String[] args ) throws IOException {
		new Thread( new E66() ).start();
	}
}

2 40
2 3
```

I hope these inputs are helpful! Let me know if you have any questions or need further assistance.

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, x;
  cin >> n >> x;
  if (x == 2) {
    cout << 0;
    return 0;
  }
  int a[100000];
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    if (a[i] == 1) {
      cout << 1;
      return 0;
    }
  }
  sort(a, a + n);
  int next_prime = 2;
  int prime[100002];
  int ans = 0;
  int i = 0;
  while (next_prime < x) {
    while (i < n && a[i] < next_prime) i++;
    if (i == n || a[i] != next_prime) {
      cout << -1;
      return 0;
    }
    bool found = false;
    prime[ans++] = next_prime;
    while (!found && next_prime < x) {
      found = true;
      next_prime++;
      for (int j = 0; j < ans; j++) {
        if (prime[j] * prime[j] > next_prime) break;
        if (next_prime % prime[j] == 0) {
          found = false;
          break;
        }
      }
    }
  }
  cout << ans;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
static int n;
static vector<int> ve;
int main() {
  while (scanf("%d", &n) != EOF) {
    ve.clear();
    ve.resize(n);
    for (int i = 0; i < n; i++) scanf("%d", &ve[i]);
    if (n == 1 && ve[n - 1] != 15 && ve[n - 1] != 0) {
      printf("-1\n");
    } else {
      if (ve[n - 1] == 15) {
        printf("DOWN\n");
      } else if (ve[n - 1] == 0) {
        printf("UP\n");
      } else if (ve[n - 1] == 1) {
        if (ve[n - 2] == 2)
          printf("DOWN\n");
        else if (ve[n - 2] == 0)
          printf("UP\n");
      } else {
        if (ve[n - 1] > ve[n - 2])
          printf("UP\n");
        else
          printf("DOWN\n");
      }
    }
  }
  return 0;
}

2 15 14
```

Each sample input consists of two integers separated by a space, representing the number of consecutive days Vitya was watching the moon and the size of the visible part of the moon on the last day of observation, respectively. The first integer is in the range 1 to 2, and the second integer is in the range 0 to

-1 -1 DOWN DOWN UP DOWN UP DOWN UP DOWN -1 UP -1 DOWN UP UP UP DOWN -1 UP -1 UP DOWN UP -1 DOWN -1 DOWN UP DOWN DOWN -1 -1 UP DOWN -1 DOWN UP DOWN -1 DOWN -1 -1 -1 UP UP DOWN -1 UP DOWN UP UP UP DOWN

/**
 * Created by iainws on 30/09/16.
 */

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

public class CountrySide {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReaderCountrySide in = new InputReaderCountrySide(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskCountrySide solver = new TaskCountrySide();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskCountrySide {
    public void solve(int taskNumber, InputReaderCountrySide in, PrintWriter out) {
    int n = in.nextInt();
        int [] arr = new int[n];
        for(int i = 0; i < n; ++i){
            arr[i] = in.nextInt();
        }
        if(n == 1){
            if(arr[0] == 0){
                System.out.println("UP");
                return;
            }
            else if(arr[0] == 15){
                System.out.println("DOWN");
                return;
            }
            else {
                System.out.println(-1);
                return;
            }
        }
        else{
            if(arr[n - 1] == 0){
                System.out.println("UP");
                return;
            }
            if(arr[n - 1] == 15){
                System.out.println("DOWN");
                return;
            }
            if(arr[n - 2] > arr[n - 1]){
                System.out.println("DOWN");
                return;
            }
            if(arr[n - 2] < arr[n - 1]){
                System.out.println("UP");
                return;
            }
        }
    }
}

class InputReaderCountrySide {
    public BufferedReader reader;
    public StringTokenizer tokenizer;

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

}


day = int(input())
situations = input().split(" ")

dp = [[float('inf') for _ in range(3)] for _ in range(day+1)]
# Base Case:
for j in range(3):
    dp[0][j] = 0

# Inductive Step:
for i in range(1, day+1):
    # 0: rest
    dp[i][0] = 1 + min(dp[i-1][0], dp[i-1][1], dp[i-1][2])
    # 1: gym
    dp[i][1] = min(dp[i-1][0], dp[i-1][2])
    # 2. contest
    dp[i][2] = min(dp[i-1][0], dp[i-1][1])

    if situations[i-1] == '0':
        dp[i][1] = float('inf')
        dp[i][2] = float('inf')
    elif situations[i-1] == '1':
        dp[i][1] = float('inf')
    elif situations[i-1] == '2':
        dp[i][2] = float('inf')

print(min(dp[day][0], dp[day][1], dp[day][2]))


 import java.util.*;
 public class Main {
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        if(n == 1)
        {
            System.out.println("1");
        }
        else
        {
            int[] arr = new int[n];
            for(int i = 0; i < n; i++)
            {
                arr[i] = s.nextInt();
            }
            ArrayList<Integer> seq = new ArrayList<Integer>();
            int conseq = 1;
            for(int i = 0; i < n - 1; i++)
            {
                if(arr[i] <= arr[i + 1])
                {
                    conseq++;
                    if(i == n - 2)
                        seq.add(conseq);
                }
                else if(arr[i] > arr[i + 1])
                {

                    seq.add(conseq);
                    conseq = 1;
                }
            }
            Collections.sort(seq);

            System.out.println(seq.get(seq.size() - 1));
        }
    }
}

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, i, f = 0;
  cin >> n;
  int a[n], b[n];
  for (i = 0; i < n; i++) cin >> a[i];
  int m = a[0], c = 1, k = 0;
  for (i = 1; i < n; i++) {
    f = 1;
    if (m < a[i] || m == a[i]) {
      c++;
      m = a[i];
    } else {
      m = a[i];
      c = 1;
    }
    b[k] = c;
    k++;
  }
  if (f) {
    int mx = b[0];
    for (i = 1; i < k; i++) {
      if (mx < b[i]) mx = b[i];
    }
    cout << mx << endl;
  } else
    cout << c << endl;
  return 0;
}


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

public class test{
      public static void main(String aa[]){
            Scanner sc=new Scanner(System.in);
            int t=sc.nextInt();
            String cmp="";
            int result=0,count=0;
            String arr[]=new String[t];
            for(int i=0;i<t;i++){
                  arr[i]=sc.next();
            }
            for(int i=0;i<t;i++){
		  count=0;
                  cmp=arr[i];
                  for(int j=0;j<t;j++){
                        if(cmp.equals(arr[j])){
                              count++;
                        }

                  }
                  if(result<count){result=count;}

            }

            System.out.println(result);
      }

}

from collections import Counter
n = int(input())
print(max(Counter([input() for _ in range(n)]).values()))


import java.util.Scanner;

public class hello64 {
	// String s;
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		String s = input.next();
		boolean hasAn = false;
		for (int j = 0; j <= s.length(); j++) {
			String newS = "";
			for (int i = 0; i < 26; i++) {
				// System.out.println((char)(i+97));
				newS = s.substring(0, j);
				// System.out.println(newS);
				newS += (char) (i + 97);
				newS += s.substring(j);
				// System.out.println(newS);
				// System.out.println(newS);
				// System.out.println("");
				// System.out.println(isPalind(newS);
				if (isPalind(newS)) {
					System.out.println(newS);
					hasAn = true;
					break;
				}
			}
			if(hasAn) break;
		}
		if (!hasAn) {
			System.out.println("NA");
		}

	}

	public static boolean isPalind(String s) {
		int startIndex = 0;
		if (s.length() % 2 != 0) {
			startIndex = s.length() / 2;
			// System.out.println(s);
			// int dis = 1;
			for (int dis = 1; dis <= s.length() - s.length() / 2 - 1; dis++) {
				if (s.charAt(startIndex + dis) != s.charAt(startIndex - dis)) {
					return false;
				}
			}
			return true;
		} else {
			for (int dis = 0; dis <= s.length() / 2; dis++) {
				if (s.charAt(startIndex + dis) != s.charAt(s.length() - dis-1)) {
					return false;
				}
			}
			return true;
		}
		// return false;
	}
}

p iq yz rqts klm mno hi mn vw mmmm uvwx jk stu uuuu kitayuta t b mnop ghi q ssss c uvwx gggg h ab rrrr efgh palindrome o tttt bbbb qqqq gh www revive wxy iii qrst i vwx r e k kl vvvv xy ijkl w n pon v qrst dddd y a bc qrs u tu dad efe op yyyy pppp abcd yza l nnnn hhhh yutampo s lm def mno cdef oooo abc d jjjj eeee zzzz cba j yzab dog wxyz llll xyza m ef kkkk uvw ponm cccc ij g iwiwi stuv qr fed cd st ghi yza jkl ihg ijkl ee yzab opqr f bcda ffff bab klmn pqr z xxx cab ghij mnop ijk efgh lkj x tuv

kk NA NA ccccc fef tt NA yy NA NA NA NA wvw rr NA NA vv qq NA mlm gg hgh NA ff xx eeeee NA NA uu NA NA ggggg sssss uuuuu daad utu NA zzzzz hhhhh iiii NA NA cbc NA jj NA NA qiq fffff mmmmm oo NA lkl NA zyz NA NA reviver vvvvv ddddd NA jjjjj NA ll eee mm NA NA NA NA NA nnnnn NA NA rrrrr kkkkk ttttt ss ihi NA NA dd NA jij zz bb pp baab NA NA effe nmn NA NA NA NA NA NA ee wwww NA tst NA yyyyy hh qqqqq NA NA ooooo ii cc yxy aa bbbbb pop NA nn xxxx dcd kjk ww ppppp NA rqr bab iwiiwi lllll

#include <bits/stdc++.h>
using namespace std;
int main() {
  string s, a;
  cin >> s;
  for (int i = 0; i <= s.length(); i++) {
    for (int b = 'a'; b <= 'z'; b++) {
      a = s.substr(0, i) + ((char)b) + s.substr(i, s.size());
      if (a == string(a.rbegin(), a.rend())) {
        cout << a << endl;
        return 0;
      }
    }
  }
  cout << "NA" << endl;
  return 0;
}


# your code goes
n=int(input())
l=[]
for i in range(n):
	k=tuple(map(int,input().split()))
	l.append(k)
d=sorted(l)
a=-2
for i in range(n):
	if a<=d[i][1]:
		a=d[i][1]
	else:
		a=d[i][0]
print(a)

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  scanf("%d", &n);
  vector<pair<int, int> > arr;
  for (int i = 0; i < n; i++) {
    int a, b;
    scanf("%d%d", &a, &b);
    arr.push_back(pair<int, int>(a, b));
  }
  sort(arr.begin(), arr.end());
  int ans = 0;
  for (const auto &i : arr) {
    int b = i.second;
    int a = i.first;
    if (ans <= b) {
      ans = b;
    } else {
      ans = a;
    }
  }
  cout << ans << endl;
  return 0;
}


n = int(input())
a = list(map(int,input().split()))
a.sort()
i = 0
ln = nn = 1
j = n-1
while (a[i]==a[i+1] and i<n-1 and a[0]!=a[-1]):
    i+=1
    nn+=1
while(a[j]==a[j-1] and j>0 and a[0]!=a[-1]):
    j-=1
    ln+=1
dis = a[-1]-a[0]
if a[0]!=a[-1]: k = ln*nn
else: k = n*(n-1)//2
print(dis, end = " ")
print(k)

#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n;
  cin >> n;
  vector<long long> a(n);
  for (long long i = 0; i < n; i++) {
    cin >> a[i];
  }
  sort(a.begin(), a.end());
  long long min = a[0];
  long long max = a[n - 1];
  long long num1 = 0;
  long long num2 = 0;
  for (long long i = 0; a[i] == min; i++) {
    num1++;
  }
  for (long long i = n - 1; a[i] == max; i--) {
    num2++;
  }
  if (min == max) {
    cout << 0 << " " << ((num1) * (num1 - 1)) / 2 << endl;
  } else
    cout << max - min << " " << num1 * num2 << endl;
}


#include <bits/stdc++.h>
using namespace std;
const long long MAX = 100000 + 10;
long long a[MAX], d[MAX], n, ans = 0;
long long gcd(long long x, long long y) {
  if (y < x) swap(x, y);
  if (y % x == 0) return x;
  return gcd(x, y % x);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin >> n;
  for (long long i = 0; i < n; i++) {
    cin >> a[i];
    ans += a[i];
  }
  sort(a, a + n);
  d[1] = a[1] - a[0];
  ans += (d[1] * 2);
  for (long long i = 2; i < n; i++) {
    d[i] = (d[i - 1] + (a[i] - a[i - 1]) * i);
    ans += d[i] * 2;
  }
  long long k = gcd(ans, n);
  cout << ans / k << ' ' << n / k << endl;
}

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author sheep
 */
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();
	}
}

class TaskA {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.nextInt();
        long[] distance = new long[n];
        long sum = 0;
        for (int i = 0; i < n; ++i) {
            distance[i] = in.nextInt();
            sum += distance[i];
        }

        Arrays.sort(distance);

        long upper = 0, down = n;

        long previousSum = 0;
        for (int i = 0; i < n; ++i) {
            upper += i * distance[i] - previousSum;
            previousSum += distance[i];
            upper += (sum - previousSum) - distance[i] * (n - i - 1);
            upper += distance[i];
        }

        long g = BigInteger.valueOf(upper).gcd(BigInteger.valueOf(down)).longValue();
        upper /= g;
        down /= g;

        out.println(upper + " " + down);
    }
}

class InputReader {
    BufferedReader reader;
    StringTokenizer tokenizer;

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

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

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

    }


#include <bits/stdc++.h>
using namespace std;
int vet[101];
int N, res;
int main(void) {
  cin >> N;
  for (int i = 0; i < N; i++) cin >> vet[i + 1];
  for (int i = N; i >= 1; i--)
    if (vet[i] != 0) {
      if (i != 1 && (i / 2) * 2 + 1 <= N) {
        int p = i / 2;
        int h = vet[i];
        vet[p] = max(0, vet[p] - h);
        vet[p * 2] = max(0, vet[p * 2] - h);
        vet[p * 2 + 1] = max(0, vet[p * 2 + 1] - h);
        res += h;
      } else if (i * 2 + 1 > N) {
        cout << -1;
        return 0;
      } else
        res += vet[i];
    }
  cout << res;
  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 C {
	private static BufferedReader in;
	private static StringTokenizer st;
	private static PrintWriter out;

	public static void main(String[] args) throws NumberFormatException, IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		st = new StringTokenizer("");
		out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int n = nextInt();
		int a[] = new int [n+1];
		for (int i = 1; i <=n; i++) {
			a[i] = nextInt();
		}
		int ans = 0;
		if(n % 2 == 0 || n==1){
			System.out.println(-1);
			return;
		}
		for (int i = 1; i <=n; i++) {
			for (int j = (n-1)/2; j >=1; j--) {
				int max = Math.max(a[2*j], a[2*j + 1]);
				ans += max;
				a[j]-= max;
				if(a[j]<0) a[j] = 0;
				a[2*j]-= max;
				a[2*j + 1] -= max;
			}
		}
		ans+=a[1];
		System.out.println(ans);
	}

	static String next() throws IOException{
		while(!st.hasMoreTokens()){
			st = new StringTokenizer(in.readLine());
		}
		return st.nextToken();
	}
	static int nextInt() throws NumberFormatException, IOException{
		return Integer.parseInt(next());
	}
	static long nextLong() throws NumberFormatException, IOException{
		return Long.parseLong(next());
	}

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

}


from math import sqrt

def check(n, d):
    n = str(n)
    d = str(d)
    for c in d:
        if c in n:
            return True
    return False

def get_divisors(n):
    m = int(sqrt(n)) + 1
    divisors = set()
    for d in range(1, m):
        if n % d == 0:
            divisors.add(d)
            divisors.add(n // d)
    return list(divisors)

def main():
    n = int(input())
    divs = get_divisors(n)
    c = 0
    for d in divs:
        if check(n, d):
            c += 1
    print(c)

if __name__ == "__main__":
    main()

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

public class Main {

	public static void main(String[] args) {
		FastReader reader = new FastReader();
		int x = reader.nextInt();
		reader.close();
		int[] f = new int[10];
		for (char c : String.valueOf(x).toCharArray())
			++f[c - '0'];
		int val = (int) Math.sqrt((double) x);
		int cnt = 0;
		outer: for (int i = 1; i <= val; ++i) {
			if (x % i == 0) {
				int v1 = i;
				int v2 = x / i;
				int[] f1 = new int[10];
				for (char c : String.valueOf(v1).toCharArray())
					++f1[c - '0'];
				if (v1 == v2) {
					for (int j = 0; j < 10; ++j)
						if (f[j] > 0 && f1[j] > 0) {
							++cnt;
							continue outer;
						}
					break;
				}
				int[] f2 = new int[10];
				for (char c : String.valueOf(v2).toCharArray())
					++f2[c - '0'];
				boolean first = false;
				boolean second = false;
				for (int j = 0; j < 10; ++j) {
					if (f[j] > 0 && f1[j] > 0)
						first = true;
					if (f[j] > 0 && f2[j] > 0)
						second = true;
					if (first && second) {
						cnt += 2;
						continue outer;
					}
				}
				cnt += first || second ? 1 : 0;
			}
		}
		System.out.println(cnt);
	}

	public static void print2D(int[][] mat) {
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < mat.length; ++i) {
			for (int j = 0; j < mat[i].length; ++j)
				sb.append(mat[i][j] + " ");
			sb.append("\n");
		}
		System.out.println(sb.toString().trim());
	}

	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().trim());
				} 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() {
			StringBuilder str = new StringBuilder("");
			try {
				str.append(br.readLine().trim());
			} catch (IOException e) {
				e.printStackTrace();
			}
			return str.toString();
		}

		int[] readArray(int size) {
			int[] ar = new int[size];
			for (int i = 0; i < size; ++i)
				ar[i] = nextInt();
			return ar;
		}

		void close() {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}


import java.util.Scanner;

public class Microbs implements Runnable {
  public void run() {
    try {
      Scanner in = new Scanner(System.in);
      //BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      int k = in.nextInt();
      int b = in.nextInt();
      int n = in.nextInt();
      int t = in.nextInt();
      long num = 1L;
      int s = 0;
      while (num <= t) {
        num = k * num + b;
        s++;
      }
      System.out.println(Math.max(n - s + 1, 0));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

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

k, b, n, t = list(map(int, input().split()))
p = 1
while p <= t:
    p = k * p + b
    n -= 1
print(max(0, n+1))


#include <bits/stdc++.h>
const int INF = 0x3f3f3f3f;
const double EPS = 1e-9;
using namespace std;
bool cmp(int a, int b) { return a >= b; }
int main() {
  int k, cnt = 0, sum = 0, idx = 0;
  cin >> k;
  vector<int> a(12);
  for (int i = (int)(0); i < (int)(12); ++i) cin >> a[i];
  sort(a.begin(), a.end(), cmp);
  while (sum < k && idx < 12) {
    sum += a[idx];
    idx++;
    cnt++;
  }
  if (sum >= k)
    cout << cnt << endl;
  else
    cout << "-1\n";
  return 0;
}

#149A
k=int(input())
a=list(map(int,input().split()))
a.sort(reverse=True)
k1,count=0,0
for i in range(len(a)):
    if k<=k1:
        break
    else:
        k1+=a[i]
        count+=1
if k<=k1 :
    print(count)
else:
    print(-1)


/*
⠀⠀⠀⠀⣠⣶⡾⠏⠉⠙⠳⢦⡀⠀⠀⠀⢠⠞⠉⠙⠲⡀
⠀⠀⠀⣴⠿⠏⠀⠀⠀⠀⠀⠀⢳⡀⠀⡏⠀⠀Y⠀⠀⢷
⠀⠀⢠⣟⣋⡀⢀⣀⣀⡀⠀⣀⡀⣧⠀⢸⠀⠀A⠀⠀ ⡇
⠀⠀⢸⣯⡭⠁⠸⣛⣟⠆⡴⣻⡲⣿⠀⣸⠀⠀S⠀  ⡇
⠀⠀⣟⣿⡭⠀⠀⠀⠀⠀⢱⠀⠀⣿⠀⢹⠀⠀H⠀⠀ ⡇
⠀⠀⠙⢿⣯⠄⠀⠀⠀⢀⡀⠀⠀⡿⠀⠀⡇⠀⠀⠀⠀⡼
⠀⠀⠀⠀⠹⣶⠆⠀⠀⠀⠀⠀⡴⠃⠀⠀⠘⠤⣄⣠⠞
⠀⠀⠀⠀⠀⢸⣷⡦⢤⡤⢤⣞⣁
⠀⠀⢀⣤⣴⣿⣏⠁⠀⠀⠸⣏⢯⣷⣖⣦⡀
⢀⣾⣽⣿⣿⣿⣿⠛⢲⣶⣾⢉⡷⣿⣿⠵⣿
⣼⣿⠍⠉⣿⡭⠉⠙⢺⣇⣼⡏⠀⠀⠀⣄⢸
⣿⣿⣧⣀⣿………⣀⣰⣏⣘⣆⣀
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter; // System.out is a PrintWriter
import java.util.Arrays;
// import java.util.Arrays;
// import java.util.ArrayList;
// import java.util.Collections;    //  for ArrayList sorting mainly
// import java.util.HashMap;
// import java.util.HashSet;
// import java.util.Random;
import java.util.StringTokenizer;

public class A {
    public static void main(String[] args) throws IOException {
        FastScanner scn = new FastScanner();
        PrintWriter out = new PrintWriter(System.out);
        for (int tc = scn.nextInt(); tc > 0; tc--) {
            int N = scn.nextInt();
            char[] str = scn.next().toCharArray();
            Arrays.sort(str);
            for (char c : str) {
                out.print(c);
            } out.println();
        }
        out.close();
    }

    static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner() {
            this.br = new BufferedReader(new InputStreamReader(System.in));
            this.st = new StringTokenizer("");
        }

        String next() {
            while (!st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException err) {
                    err.printStackTrace();
                }
            }
            return st.nextToken();
        }

        String nextLine() {
            if (st.hasMoreTokens()) {
                return st.nextToken("").trim();
            }
            try {
                return br.readLine().trim();
            } catch (IOException err) {
                err.printStackTrace();
            }
            return "";
        }

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

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

3
11
antontrygub
15
bestcoordinator
19
trywatchinggurabruh

#include <bits/stdc++.h>

#define int long long
#define uint unsigned long long
#define vvi vector<vector<int>>
#define vi vector<int>
#define pii pair<int,int>
#define Mod (int)(1e9 + 7)
#define endl "\n"

//program specific
#define MAXN 2005

using namespace std;

int32_t main(void)
{
	int T;
	cin>>T;

	while(T--)
	{
		int n;
		string str;
		cin>>n>>str;

		vector<char> ans;

		int count = 0;

		for(char c: str) {
			if(c == 't') ++count;
			else ans.push_back(c);
		}

		while(count--) {
			ans.push_back('t');
		}

		for(char c: ans) cout << c;
		cout << endl;
	}
	return 0;
}


import java.util.*;
import java.io.*;
import static java.lang.Double.max;
import static java.lang.Integer.min;
public class Main {
    static FastReader in=new FastReader();
    public static void main(String [] args) {
       int n=in.nextInt(),sum=0,ans=0,open=0,close=0,o=0,c=0;
       if(n%2==1){System.out.println("-1");return;}
        String S=in.next();
        for(int i=0;i<n;i++){
        if(S.charAt(i)=='('){sum++;o++;open++;}
        else{
        c++;close++;
        if(sum>0)sum--;
        }
        if(o==c&&sum==0){c=0;o=0;}
        else if(o==c&&sum>0){ans+=o+c;o=0;c=0;sum=0;}
        }
        if(open==close){System.out.println(ans);}
        else System.out.println("-1");
   }
    static int binarySearch(int arr[], int l, int r, int x)
    {
        if (r >= l) {
            int mid = l + (r - l) / 2;

            if (arr[mid] == x||(arr[mid]<x&&arr[mid+1]>=x))
                return mid;

            if (arr[mid] > x)
                return binarySearch(arr, l, mid - 1, x);

            return binarySearch(arr, mid + 1, r, x);
        }

        return -1;
    }

    static long gcd(long g,long x){
        if(x<1)return g;
        else return gcd(x,g%x);

    }
}
class node implements Comparable<node>{
int f, e;
node(int tt,int ll){
f=tt;e=ll;
}
    @Override
    public int compareTo(node o) {
    return f-o.f;
    }
}
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;
        }
}

class Sorting{

 public static int[] bucketSort(int[] array, int bucketCount) {

 if (bucketCount <= 0) throw new IllegalArgumentException("Invalid bucket count");

 if (array.length <= 1) return array; //trivially sorted

 int high = array[0];

 int low = array[0];

 for (int i = 1; i < array.length; i++) { //find the range of input elements

 if (array[i] > high) high = array[i];

 if (array[i] < low) low = array[i];

 }

 double interval = ((double)(high - low + 1))/bucketCount; //range of one bucket

 ArrayList<Integer> buckets[] = new ArrayList[bucketCount];

 for (int i = 0; i < bucketCount; i++) { //initialize buckets

 buckets[i] = new ArrayList();

 }

 for (int i = 0; i < array.length; i++) { //partition the input array

 buckets[(int)((array[i] - low)/interval)].add(array[i]);

 }

 int pointer = 0;

 for (int i = 0; i < buckets.length; i++) {

 Collections.sort(buckets[i]); //mergeSort

 for (int j = 0; j < buckets[i].size(); j++) { //merge the buckets

 array[pointer] = buckets[i].get(j);

 pointer++;

 }

}

return array;

}

}

#include <bits/stdc++.h>
using namespace std;
char c[1000002];
int n, cnt = 0, v = 0;
int main() {
  scanf("%d%s", &n, c + 1);
  for (int i = 1; i <= n; i++) {
    if (c[i] == '(')
      v++;
    else
      v--;
    if (v < 0 || (v == 0 && c[i] == '(')) cnt++;
  }
  printf("%d", v ? -1 : cnt);
  return 0;
}


XX. XX.XXXXXXX
```

Each input has a length of 10 tokens and conforms to the input data format specified in the problem description.

/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;
public class GFG {
	public static void main (String[] args) {
	    Scanner sc=new Scanner(System.in);
		String s=sc.nextLine();
		String s1=sc.nextLine();
		String s2=sc.nextLine();
		StringBuffer s3=new StringBuffer(s);
		s3.reverse();StringBuffer s4=new StringBuffer(s1);
		s4.reverse();StringBuffer s5=new StringBuffer(s2);
		s5.reverse();
		if(s3.toString().equals(s2) && s4.toString().equals(s1) && s5.toString().equals(s))
		{
		    System.out.println("YES");
		}
		else System.out.println("NO");
	}
}


import sys
import math

n = int(sys.stdin.readline())
an = [int(x) for x in (sys.stdin.readline()).split()]

k = [0] * 101

for i in an:
    k[i] += 1

res = 0
for i in k:
    res += int(i / 2)

print(int(res / 2))

#include <bits/stdc++.h>
using namespace std;
int a[1001];
int main() {
  int n;
  cin >> n;
  int b[n];
  for (int i = 0; i < n; i++) {
    int x;
    cin >> x;
    a[x]++;
  }
  int cnt = 0;
  for (int i = 1; i <= 100; i++) {
    if (a[i] > 1) {
      if (a[i] % 2 != 0) {
        cnt += a[i] - 1;
      } else {
        cnt += a[i];
      }
    }
  }
  cout << cnt / 4 << '\n';
}


#import math

#def findPrimeFactor(difference):
#  if difference % 2 == 0:
#    print("YES")
#  else:
#    findOddPrimeFactor(int(difference))

num = int(input())
for i in range(num):
  x, y = input().split(" ")
  difference = int(x) - int(y)
  if difference != int(1) and difference > (0):
    print("YES")
  else:
    print("NO")
  #findPrimeFactor(difference)

/**
 * @author Juan Sebastian Beltran Rojas
 * @mail jsbeltran.valhalla@gmail.com
 * @veredict
 * @url
 * @category
 * @date
 **/

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

import static java.lang.Long.parseLong;

public class CF1238A {
    public static void main(String args[]) throws Throwable {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (long Q=parseLong(in.readLine()), q=0; q++<Q; ) {
            StringTokenizer st = new StringTokenizer(in.readLine());
            long A=parseLong(st.nextToken()), B=parseLong(st.nextToken());
            System.out.println(A-B>1?"YES":"NO");
        }
    }
}


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

public class Solution {

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

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken());
		st = new StringTokenizer(br.readLine());

		int[] a = new int[n];
		for (int i = 0; i < a.length; i++) {
			a[i] = Integer.parseInt(st.nextToken());
		}
		long count = a[n - 1];
		int prev = a[n - 1];
		for (int i = n - 2; i >= 0; i--) {
			if (a[i] < prev) {
				count += a[i];
				prev = a[i];
			} else {
				prev = Math.max(0, prev - 1);
				count += prev;
			}
		}

		System.out.println(count);

	}
}

n = int(input())
a = list(map(int,input().split()))
max = a[len(a)-1]
sum = max
for i in range(len(a)-2,-1,-1):
    # print(max)
    if (max<=0):
        break
    if (a[i]>=max):
        # print(a[i])
        max = max-1
        sum += max
    else:
        # print(a[i])
        max = a[i]
        sum += max
print(sum)


from sys import stdin, stdout

int_in = lambda: int(stdin.readline())
arr_in = lambda: [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for y in range(rows)]
str_in = lambda: stdin.readline().strip()
out = lambda o: stdout.write("{}\n".format(o))
arr_out = lambda o: out(" ".join(map(str, o)))
bool_out = lambda o: out("YES" if o else "NO")
tests = lambda: range(1, int_in() + 1)
case_out = lambda i, o: out("Case #{}: {}".format(i, o))

def solve(n, color_pairs):
    result = {}
    for i in range(1, n+1):
        result[i] = [[i, i]]
    i = n + 1
    for p in color_pairs:
        result[p[0]].append([i, p[0]])
        result[p[1]].append([i, p[1]])
        i += 1
    return result

if __name__ == "__main__":
    n, m = arr_in()
    color_pairs = mat_in(m)
    result = solve(n, color_pairs)
    for key in range(1, n+1):
        out(len(result[key]))
        for item in result[key]:
            arr_out(item)

#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e5 + 10;
const int MOD = 1e9 + 7;
int N, M, K, Q;
vector<pair<int, int>> vec[110];
int main() {
  int i, j, k, a, b;
  scanf("%d%d", &N, &M);
  int sx = 101;
  for (i = 0; i < M; ++i) {
    scanf("%d%d", &a, &b);
    int sy = (a - 1) * 100 + 1;
    sy += vec[a].size();
    vec[a].push_back({a, sy});
    vec[b].push_back({b, sy});
  }
  for (i = 1; i <= N; ++i) {
    if (vec[i].size() != 0) {
      printf("%d\n", vec[i].size());
      for (j = 0; j < vec[i].size(); ++j) {
        printf("%d %d\n", vec[i][j].first, vec[i][j].second);
      }
    } else {
      printf("1\n");
      printf("%d %d\n", i, (i - 1) * 100 + 1);
    }
  }
}


//problem: https://codeforces.com/problemset/problem/1025/A

import java.util.Scanner;
import java.util.Arrays;

public class Doggo{
    public static void main(String[] args){
        Scanner sObj = new Scanner(System.in);
        int size = Integer.parseInt(sObj.nextLine());
        if(size==1){
            System.out.println("Yes");
            return;
        }
        int[] arr = new int[128];
        for(char c: sObj.nextLine().toCharArray()){
            arr[c]++;
            if(arr[c] >= 2){
                System.out.println("Yes");
                return;
            }
        }
        System.out.println("No");
    }
}

Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes No Yes Yes Yes Yes Yes Yes No Yes Yes No Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  if (n == 1) {
    cout << "Yes";
    return 0;
  }
  string a;
  cin >> a;
  int b[125] = {0};
  for (int i = 0; i < n; i++) {
    b[a[i]]++;
  }
  for (int i = 97; i <= 122; i++) {
    if (b[i] >= 2) {
      cout << "Yes";
      return 0;
    }
  }
  cout << "No";
  return 0;
}


import os
import sys
from io import BytesIO, IOBase

def main():
    import bisect
    import math
    # import itertools
    # import heapq
    # from queue import PriorityQueue, LifoQueue, SimpleQueue

    # import sys.stdout.flush() use for interactive problems
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    inf = 1e17
    mod = 10 ** 9 + 7

    Max = 10 ** 6
    primes = []
    prime = [True for i in range(Max + 1)]
    p = 2
    while (p * p <= Max + 1):

        # If prime[p] is not
        # changed, then it is a prime
        if (prime[p] == True):

            # Update all multiples of p
            for i in range(p * p, Max + 1, p):
                prime[i] = False
        p += 1

    for p in range(2, Max + 1):
        if prime[p]:
            primes.append(p)

    def factorial(n):
        f = 1

        for i in range(1, n + 1):
            f = (f * i) % mod  # Now f never can
        # exceed 10^9+7

        return f

    def ncr(n, r):
        # initialize numerator
        # and denominator
        num = den = 1
        for i in range(r):
            num = (num * (n - i)) % mod
            den = (den * (i + 1)) % mod
        return (num * pow(den,
                          mod - 2, mod)) % mod

    def solve(n,arr):

        chance = [0]*(n+1)
        chance[-2] = arr[-1]
        for i in range(n-2,-1,-1):
            chance[i] = max(chance[i+1],sum(arr[i+1:])-chance[i+1]+arr[i])

        #print(chance)
        return sum(arr)-chance[0],chance[0]

        pass

    t = 1# int(input())
    ans = []
    for _ in range(t):
        n = int(input())
        # x = int(input())
        # y = int(input())
        # n,k = map(int, input().split())
        arr = [int(x) for x in input().split()]
        #arr2 = [int(x) for x in input().split()]
        # arr = list(input())
        # s = input()
        # t = input()
        # grid = []
        # for i in range(n):
        #     grid.append([int(x) for x in input().split()])
        # arr = []
        # for j in range(n):
        #     arr.append(int(input()))

        ans.append(solve(n,arr))

    for j in range(len(ans)):
        # print('Case #' + str(j + 1) + ": " + str(ans[j]))
        print(ans[j][0],ans[j][1])

    pass

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        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")

# endregion

if __name__ == "__main__":
    main()

import java.util.Scanner;
import java.util.StringTokenizer;

public class CF_859C {
	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int n = Integer.parseInt(s.nextLine());
		StringTokenizer st = new StringTokenizer(s.nextLine());

		int[] pies = new int[n];
		for(int i = 0; i < n; i++) {
			pies[i] = Integer.parseInt(st.nextToken());
		}
		int[] arr = new int[n];
		arr[n-1] = pies[n-1];
		int runsum = pies[n-1];

		for(int i = n-2; i >= 0; i--) {
			arr[i] = Math.max(arr[i+1], pies[i]+runsum-arr[i+1]);
			runsum += pies[i];
		}

		System.out.println((runsum-arr[0]) + " " + arr[0]);

	}
}


from sys import stdin
import re

def readInt(count=1):
    m = re.match('\s*' + ('([+-]?\d+)\s*' * count), stdin.readline())
    if m is not None:
        ret = []
        for i in range(1, m.lastindex + 1):
            ret.append(int(m.group(i)))
        return ret
    return None

taskCount, = readInt()
thinkingTime = readInt(taskCount)
onlineCount, = readInt()
online = []
for i in range(onlineCount):
    online.append(readInt(2))

totalThinking = sum(thinkingTime)
best = -1
for i in range(onlineCount):
    if online[i][0] >= totalThinking:
        if best == -1 or online[i][0] < best:
            best = online[i][0]
    elif online[i][1] >= totalThinking:
        best = totalThinking
        break
print(best)

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

public class Main {

    static class TaskF {

        void solve(InputReader in, PrintWriter out) {
            int n = in.nextInt();

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

            int m = in.nextInt();
            int currentTask = 0;
            int theLastTime = -1;
            boolean flagToBreak = false;
            for (int i = 0; i < m; i++) {

                int l = in.nextInt();
                int r = in.nextInt();
                while (a[currentTask] <= r) {
                    if (a[currentTask] > l) theLastTime = a[currentTask];
                    else theLastTime = l;
                    a[currentTask] = -1;
                    currentTask++;
                    if (currentTask == n) {
                        flagToBreak = true;
                        break;
                    }
                }
                if (flagToBreak) break;
            }

            if (currentTask == n) out.print(theLastTime);
            else out.print(-1);
        }

    }

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskF solver = new TaskF();
        solver.solve(in, out);
        out.close();
    }

    static private class InputReader {
        BufferedReader reader;
        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();
        }

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

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

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

    }
}


import java.util.*;
public class May {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		long n = sc.nextLong();
		long q = sc.nextLong();
		while(q-->0) {
			long u = sc.nextLong();
			long h = level(u);
		//	System.out.println(h);
			char[] s = sc.next().toCharArray();
			for(char c : s) {
				if(c == 'L') {
					if(h>0) {
					--h;
					u-=pow(2, h);
					}
				}else if(c == 'R') {
					if(h>0) {
					--h;
					u+=pow(2, h);
					}
				}else if(h<level((n+1)/2)){
					long temp = pow(2, h);
					if(u+temp>0 && u+temp<=n) {
						if(h+1 == level(u+temp)) {
							++h;
							u+=temp;
						}else {
							++h;
							u-=temp;
						}

					}else if(u-temp>0 && u-temp<=n) {
						if(h+1 == level(u-temp)) {
							++h;
							u-=temp;
						}else {
							++h;
							u+=temp;
						}
					}
				}
				//System.out.println(u);
			}
		System.out.println(u);
		}

	}
	private static long level(long u) {
		long ans = 0;
		long temp = 1,i=0;
		while(u>=temp) {
			if(u%temp == 0) {
				ans = i;
			}
			temp*=2; ++i;
		}
		return ans;
	}
	private static long pow(long x, long h) {
	    long res = 1;
        while (h > 0) {

            if((h & 1)==1)
                res = (res * x);

            h = h >> 1;
            x = (x * x);
        }
        return res;
}

}

7 10
3
LLULULLLR
4
LUUURLLLUURRU
1
ULURR
6
LURLLLLRLR
2
ULULURU
7
RRUUUURLRLR
7
UUURRULRRLUL
7
ULLLRUULULR
6
UURRLL
6
RULUUULLRLLLUULL

15 10
1
URUUUR
15
RRLLURRRURL
1
UURRLUR
13
LRUULUURLRRRL
6
LULUURULUURL
15
UULL
8
ULLLULRLRUU
8
ULRUULRUURLLRL
5
LLUULRLURRRULLR
10
LUULLRU

1 10
1
URLRLULUR
1
LRRRURULULL
1
LURURRUUUU
1
RRULLLRRUL
1
UULLUURL
1
RLRRULUL
1
LURRLRUULRR
1
LULLULUUUL
1
URULLULL
1
LRRLRUUUURRLRRL

from math import log
n, q = [int(i) for i in input().split()]
maxlvl = int(log(n + 1, 2)) + 1
steps = [2 ** i for i in range(maxlvl)]

def calc_lvl(m):
    for lvl in range(1, maxlvl):
        if (m - steps[lvl-1]) % steps[lvl] == 0:
            return (lvl, ((m - steps[lvl-1]) % (2 * steps[lvl]) == 0))

#print(calc_lvl(1))
#print(calc_lvl(3))
#print(calc_lvl(5))
#print(calc_lvl(7))
#print(calc_lvl(9))
#print(calc_lvl(11))
#print(calc_lvl(13))
#print(calc_lvl(15))

for i in range(q):
    strt = int(input())
    qwery = input()
    lvl, ind = calc_lvl(strt)

    for c in qwery:
        if c == 'U':
            if strt == steps[-2]:
                continue
            if not ind:
                strt -= steps[lvl - 1]
                lvl, ind = calc_lvl(strt)
            else:
                strt += steps[lvl - 1]
                lvl, ind = calc_lvl(strt)

        elif c == 'L':
            if strt % 2 != 0:
                continue
            strt -= steps[lvl - 2]
            lvl, ind = lvl - 1, 1

        else:
            if strt % 2 != 0:
                continue
            strt += steps[lvl - 2]
            lvl, ind = lvl - 1, 0

    print(strt)


#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int n, m, k;
int a[N], sz[N], c[N];
bool u[N];
vector<int> g[N];
void go(int v, int comp) {
  c[v] = comp;
  ++sz[comp];
  u[v] = true;
  for (auto to : g[v]) {
    if (u[to]) continue;
    go(to, comp);
  }
}
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 0; i < k; ++i) {
    scanf("%d", &a[i]);
    --a[i];
  }
  for (int i = 0; i < m; ++i) {
    int x, y;
    scanf("%d%d", &x, &y);
    --x;
    --y;
    g[x].push_back(y);
    g[y].push_back(x);
  }
  for (int i = 0; i < k; ++i) go(a[i], i + 1);
  int mx = 1;
  for (int i = 2; i <= k; ++i)
    if (sz[i] > sz[mx]) mx = i;
  for (int i = 0; i < n; ++i)
    if (c[i] == 0) {
      c[i] = mx;
      ++sz[mx];
    }
  int sum = 0;
  for (int i = 0; i < n; ++i) sum += sz[c[i]] - (int)g[i].size() - 1;
  printf("%d\n", sum / 2);
  return 0;
}

from collections import deque
n,m,k = map(int,input().split())
line = input().split()
gov = []
for i in range(k):
    gov.append(int(line[i])-1)
graph = {}
for i in range(m):
    u,v = map(int,input().split())
    u -= 1
    v -= 1
    if u not in graph:
        graph[u] = set()
    if v not in graph:
        graph[v] = set()
    graph[u].add(v)
    graph[v].add(u)
govgraph = {}
nottaken = set()
for i in range(n):
    nottaken.add(i)
for x in gov:
    nottaken.remove(x)
    if x in graph:
        d = deque()
        reach = set([x])
        d.append(x)
        while len(d) > 0:
            c = d.popleft()
            for i in graph[c]:
                if i not in reach:
                    reach.add(i)
                    nottaken.remove(i)
                    d.append(i)
        govgraph[x] = reach
    else:
        govgraph[x] = set([x])
ar = []
for c in govgraph:
    ar.append(govgraph[c])
ar.sort(key = lambda x: len(x), reverse=True)
meh = len(ar[0]) + len(nottaken)
ans = int((meh*(meh-1))/2)
for i in range(1,len(ar)):
    ans += int((len(ar[i])*(len(ar[i])-1))/2)
print(ans - m)


#include <bits/stdc++.h>
using namespace std;
int n, Sum = 0;
string s;
set<char> st;
int vis[200];
bool ok(int mid) {
  memset(vis, false, sizeof(vis));
  int sum = 0;
  for (int i = 0; i < mid; i++) {
    if (!vis[s[i]]) sum++;
    vis[s[i]]++;
  }
  if (sum == st.size()) return true;
  int l = 0, r = mid;
  while (r < n) {
    vis[s[l]]--;
    if (!vis[s[l]]) sum--;
    if (!vis[s[r]]) sum++;
    vis[s[r]]++;
    l++;
    r++;
    if (sum == st.size()) return true;
  }
  return false;
}
int main() {
  cin >> n >> s;
  for (int i = 0; i < n; i++) {
    st.insert(s[i]);
  }
  int l = 0, r = n, mid;
  while (l < r) {
    mid = l + (r - l) / 2;
    if (ok(mid))
      r = mid;
    else
      l = mid + 1;
  }
  cout << l << endl;
  return 0;
}

n = int(input())

s = input()
alles = {}
l, r, c, ans, le = 0, 0, 0, float("+inf"), len(set(s))

for i in s:
    if i not in alles:
        alles[i] = 0
        c += 1
    alles[i] += 1
    if c == le:
        while alles[s[l]] > 1:
            alles[s[l]] -= 1
            l += 1
        ans = min(ans, r-l+1)
    r += 1
print(ans)


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.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class C356B {

	static StringTokenizer st;
	static BufferedReader br;
	static PrintWriter pw;
	static int maxx = 1000001;
	static long[] a = new long [maxx];
	//static long[] s = new long [maxx];
	static long[] k = new long [maxx];
	static long[] p = new long [100002];

	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		for (long i = 0; i < 100002; ++i)
			p[(int)i] = i * i * i;
		int curi = 1;
		for (int i = 1; i < maxx; ++i) {
			if (p[curi + 1] <= i) {
				++curi;
			}
			k[i] = k[(int) (i - p[curi])] + 1;
		}
		int count = 0;
		for (int i = 1; i < maxx; ++i) {
			if (k[i - 1] > k[i]) {
				k[i] = k[i - 1];
				a[i] = a[i - 1];
			} else {
				//System.out.println(i + " " + k[i]);
				++count;
				a[i] = i;
			}
		}
		long[] l, r;
		l = new long [maxx];
		r = new long [maxx];
		l[12] = 330;
		int kk = 12;
		for (long i = 1; i <= 100100; ++i) {
			if ((i + 1) * (i + 1) * (i + 1) - i * i * i >= l[kk]) {
				//System.out.println(i);
				r[kk] = l[kk] + i * i * i - 1;
				++kk;
				l[kk] = r[kk - 1] + 1;
			}
		}
		r[kk] = (long)1e18;
		long m = nextLong();
		if (m < maxx) {
			pw.println(k[(int) m] + " " + a[(int) m]);
		} else {
			int kol = 12;
			for (int i = 12; i < 100; ++i) {
				if (l[i] <= m && r[i] >= m) {
					kol = i;
					break;
				}
			}
			pw.print(kol + " ");
			long ans = 0;
			while (m >= maxx) {
				int maxs = find(m);
				if (m - p[maxs] >= l[kol - 1]) {
					m -= p[maxs];
					ans += p[maxs];
					--kol;
				} else {

					m = p[maxs] - p[maxs - 1] - 1;
					ans += p[maxs - 1];
					--kol;
					//pw.println(ans + l[kol]);
					//return;
				}
			}
			pw.println(ans + a[(int) m]);
		}
		pw.close();
	}

	private static int find(long m) {
		int l = 0, r = 100001;
		int mid = (l + r) / 2;
		while (r - l > 1) {
			mid = (l + r) / 2;
			if (p[mid] <= m)
				l = mid;
			else
				r = mid;
		}
		return l;
	}

	private static int sumf(int[] fen, int id) {
		int summ = 0;
		for (; id >= 0; id = (id & (id + 1)) - 1)
 			summ += fen[id];
		return summ;
	}

	private static void addf(int[] fen, int id) {
		for (; id < fen.length; id |= id + 1)
			fen[id]++;
	}

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

999999999999999960
```

Please note that these inputs are randomly generated and may not necessarily produce the maximum number of blocks and X values.


#include <bits/stdc++.h>
using namespace std;
long long dp[2005][2005] = {};
int main() {
  std::ios_base::sync_with_stdio(0), cin.tie(0);
  int n, m;
  cin >> n >> m;
  string s;
  long long mod = 1e9 + 7;
  cin >> s;
  int d = n - m;
  int bal = 0, mn = 0;
  for (int i = 0; i < m; ++i) {
    if (s[i] == '(')
      bal++;
    else
      bal--;
    mn = min(mn, bal);
  }
  dp[0][0] = 1;
  long long ans = 0;
  for (int i = 1; i <= d; ++i) {
    dp[i][0] = dp[i - 1][1];
    for (int j = 1; j <= d; ++j) {
      dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]) % mod;
    }
  }
  for (int i = 0; i <= d; ++i) {
    for (int j = -mn; j <= d && d - i >= bal + j; ++j) {
      ans += dp[i][j] * dp[d - i][j + bal];
      ans %= mod;
    }
  }
  cout << ans;
  return 0;
}

n, m = map(int, input().split())
s = input()
mod = 10 ** 9 + 7
c, b, ans, d, k = 0, 0, 0, [[1]], n - m
for i in s:
    c += (i == '(') * 2 - 1
    b = min(c, b)
for i in range(n - m):
    nd = d[-1][1:] + [0] * 2
    for j in range(1, i + 2):
        nd[j] = (nd[j] + d[-1][j - 1]) % mod
    d.append(nd)
for i in range(k + 1):
    for j in range(-b, min(k - i - c, i) + 1):
        ans = (ans + d[i][j] * d[k - i][j + c]) % mod
print(ans)


n = int(input())
visited = [False] * n
k = 0
for i in range(n ** 2 + 1):
    k += i + 1
    visited[k % n] = True
for i in visited:
    if not i:
        print("NO")
        exit()
print("YES")

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

#include <bits/stdc++.h>
using namespace std;
const int N = 1100;
int n, d[N][N];
void df(int poz, int step) {
  int nel = (poz + step) % n, nstep = (step + 1) % n;
  if (nel == 0) nel = n;
  if (d[nel][nstep] == -1) {
    d[nel][nstep] = 1;
    df(nel, nstep);
  }
}
int main() {
  int i, j;
  cin >> n;
  for (i = 0; i < N; ++i)
    for (j = 0; j < N; ++j) d[i][j] = -1;
  d[1][1] = 1;
  df(1, 1);
  int ver = 0;
  for (i = 1; i <= n; ++i) {
    int vv = 0;
    for (j = 1; j <= n; ++j)
      if (d[i][j] != -1) vv = 1;
    if (!vv) {
      cout << "NO";
      return 0;
    }
  }
  cout << "YES";
  return 0;
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
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();
	}
}

class TaskA {
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        int N = in.nextInt(), S = in.nextInt();

        int Ans = 0;
        boolean ok = false;

        for (int i = 0; i < N; ++i) {
            int x = in.nextInt(), y = in.nextInt();

            if (x * 100 + y <= S * 100) {
                Ans = Math.max(Ans, (S * 100 - x * 100 - y) % 100);
                ok = true;
            }
        }

        if (ok)
            out.println(Ans);
        else
            out.println(-1);
    }
}

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

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

    public String nextString() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuffer res = new StringBuffer();
        do {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));

        return res.toString();
    }

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

}

# Author: SaykaT
# Problem: 463A
# Time Created: July 21(Tuesday) 2020 || 02:59:52

#>-------------------------<#

# Helper Functions. -> Don't cluster your code.

# IO Functions. -> Input output
def io():
    n, s = map(int, input().split())
    sugar = []
    for _ in range(n):
        x, y = map(int, input().split())
        dollar = x*100 + y
        sugar.append(dollar)
    return [n, s*100, sugar]

# Main functions. -> Write the main solution here
def solve():
    n, s, sugar = io()
    ans = -1
    for i in sugar:
        if s >= i:
            change = (s - i) % 100
            ans = max(change, ans)
    print(ans)
# Multiple test cases. -> When you have T test cases.
solve()


import math

def C(n,k):
    w=1
    for i in range(n-k+1,n+1):
        w*=i
    for i in range (1,k+1):
        w//=i
    return w

def multiples(limit):
    tmp = 1
    m = limit
    for j in range(2, limit + 1):
        no_multiples = 0
        while m % j == 0:
            no_multiples += 1
            m //= j
        if no_multiples:
            tmp *= C(no_multiples + k - 1, no_multiples)

    return tmp

n, k = [int(x) for x in input().split(' ')]
modulo = 1000000007
total = 0
for i in range(1, n+1):
    total += multiples(i)

print(total % modulo)

#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int INF = 1e9;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n, k;
  cin >> n >> k;
  vector<vector<int>> DP(n + 1, vector<int>(k + 1, 0));
  for (int i = 1; i <= n; i++) DP[i][1] = 1;
  for (int j = 1; j < k; j++)
    for (int i = 1; i <= n; i++)
      for (int t = 1; t * i <= n; t++)
        DP[i * t][j + 1] = (DP[i * t][j + 1] + DP[i][j]) % MOD;
  int ans = 0;
  for (int i = 1; i <= n; i++) ans = (ans + DP[i][k]) % MOD;
  cout << ans << endl;
}


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {

	/**
	 * @param args
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) throws FileNotFoundException {
		//System.setIn(new FileInputStream("data.in"));
		Scanner cin = new Scanner(new BufferedInputStream(System.in));
		int Len = 3;
		Point[] points = new Point[Len];
		long temp = -1;
		while (cin.hasNext()) {
			for (int i = 0; i < Len; i++) {
				points[i] = new Point(cin.nextLong(), cin.nextLong());
			}
			temp = xmult(points[0], points[1], points[2]);
			if (temp < 0) {
				System.out.println("RIGHT");
			} else if (temp > 0) {
				System.out.println("LEFT");
			} else {
				System.out.println("TOWARDS");
			}
		}
		cin.close();
	}

	public static long xmult(Point p1, Point p2, Point p3) {
		return (p1.x - p2.x) * (p2.y - p3.y) - (p1.y - p2.y) * (p2.x - p3.x);
	}
}

class Point {
	long x, y;

	public Point(long x, long y) {
		this.x = x;
		this.y = y;
	}
}

TOWARDS LEFT TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS RIGHT TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS RIGHT TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS RIGHT TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS TOWARDS LEFT

#include <bits/stdc++.h>
using namespace std;
struct point {
  double x, y;
} A, B, C;
double CCW(point A, point B, point C) {
  return (double)(B.x - A.x) * (C.y - A.y) - (C.x - A.x) * (B.y - A.y);
}
void Read() {
  scanf("%lf %lf", &A.x, &A.y);
  scanf("%lf %lf", &B.x, &B.y);
  scanf("%lf %lf", &C.x, &C.y);
}
void Solve() {
  double see = CCW(A, B, C);
  if (see > 0)
    printf("LEFT\n");
  else if (see == 0)
    printf("TOWARDS\n");
  else if (see < 0)
    printf("RIGHT\n");
}
int main() {
  Read();
  Solve();
  return 0;
}


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

public class Main {

	public static void quickSort(int array[], int start, int end)
	{
		int i = start;
		int k = end;
		if(end-start>0)
        {
			int pivot = array[start];
			while (k > i)
			{
				while(array[i]<=pivot && i<=end && k>i)
					i++;
				while(array[k]>pivot && k>=start && k>=i)
					k--;
				if (k > i) {
					int temp = array[i];
					array[i] = array[k];
					array[k] = temp;
				}
			}
        	int temp = array[start];
    		array[start] = array[k];
    		array[k] = temp;
			quickSort(array, start, k - 1);
			quickSort(array, k + 1, end);
        }
	}

	public static void main(String[] args) throws IOException {
		BufferedReader instream = new BufferedReader(new InputStreamReader(System.in));
		int total = Integer.parseInt(instream.readLine());
		int[] time = new int[total];
		String[] tokens = instream.readLine().split(" ");
		for(int i=0; i<total; i++)
			time[i] = Integer.parseInt(tokens[i]);

		quickSort(time, 0, time.length-1);

		int timeleft = 710;
		int penalty = 0;
		int solved = 0;
		int current = 0;

		while(current<total && timeleft>=time[current]){
			timeleft -= time[current];
			penalty += (timeleft >= 360) ? 0 : (360 - timeleft);
			solved++;
			current++;
		}

		System.out.print(solved);
		System.out.print(" ");
		System.out.println(penalty);
	}
}
/****** PCCA -Fri Feb 24 04:22:46 GMT 2012 *******/

from bisect import bisect_right
n = int(input())
t = list(map(int, input().split()))
t.sort()
for i in range(1, n):
    t[i] += t[i - 1]
i = bisect_right(t, 350)
j = bisect_right(t, 710)
print(j, sum(t[k] for k in range(i, j)) - 350 * (j - i))


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

public class Solution{
	long rem = 998244353L;

	public void solve(int test, Scanner sc){
		int n = sc.nextInt();

		long blockWays = 10;
		long[] res = new long[n+1];

		for(int i=1; i<=n; i++){
			long numPos = n-i+1L;

			long midPos = Math.max(numPos-2L, 0L);
			long cornerPos = Math.min(2L, numPos);

			long mid = 81L*power(10L, Math.max(n-i-2L, 0L));
			mid %= rem;
			long corner = 9L*power(10L, Math.max(n-i-1L, 0L));
			if((n-i) == 0){
				corner = 1L;
			}
			corner %= rem;

			res[i] = ((((midPos*mid)%rem)*blockWays)%rem);
			res[i] += ((((cornerPos*corner)%rem)*blockWays)%rem);
			res[i] %= rem;
		}

		for(int i=1; i<n; i++){
			System.out.print(res[i] + " ");
		}
		System.out.println(res[n]);
	}

	public long power(long a, long b){
		if(b == 0L){
			return 1L;
		}
		if(b%2L == 0L){
			return (power(((a*a)%rem), b/2L));
		}
		else{
			return ((a*power(((a*a)%rem), b/2L))%rem);
		}
	}

	public Solution(){
		Scanner sc = new Scanner(System.in);
		int tests = 1;

        for(int t=1; t<=tests; t++){
			solve(t, sc);
        }
	}

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

#                                               |
#   _` |  __ \    _` |   __|   _ \   __ \    _` |   _` |
#  (   |  |   |  (   |  (     (   |  |   |  (   |  (   |
# \__,_| _|  _| \__,_| \___| \___/  _|  _| \__,_| \__,_|

import sys

def read_line():
	return sys.stdin.readline()[:-1]

def read_int():
	return int(sys.stdin.readline())

def read_int_line():
	return [int(v) for v in sys.stdin.readline().split()]

def power(x, y, p) :
    res = 1     # Initialize result

    # Update x if it is more
    # than or equal to p
    x = x % p

    while (y > 0) :

        # If y is odd, multiply
        # x with result
        if ((y & 1) == 1) :
            res = (res * x) % p

        # y must be even now
        y = y >> 1      # y = y/2
        x = (x * x) % p

    return res

n = read_int()
d = [0]*n
p = 998244353
d[n-1] = 10
if n>1:
	d[n-2] = 180
	for i in range(n-3,-1,-1):
		a1 = ((10*(n-(i+1)-1)*9*9)%p*power(10,n-i-3,p))%p
		a2 = (2*10*9*power(10,n-i-2,p))%p
		d[i] = (a1+a2)%p
print(*d)


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

public class e implements Runnable {

	public void solve(FS in, PrintWriter out) {
		int n = in.nextInt();
		int[] a = new int[n];
		for(int i = 0; i < n; ++i) a[i] = in.nextInt();
		int idx = 0;
		ArrayList<BitSet> ans = new ArrayList<>();
		for(int i = 0; i < n + 1; ++i) ans.add(new BitSet());
		for(int curVal = n; curVal >= 1; --curVal) {
			for(int i = 0; i < n; ++i) if(a[i] == curVal) {
				for(int times = 0; times < a[i]; ++times) {
					int cidx = (idx + times) % (n + 1);
					ans.get(cidx).set(i);
				}
				idx++;
			}
		}
		ArrayList<BitSet> nans = new ArrayList<>();
		for(BitSet cur : ans) if(cur.cardinality() > 0) nans.add(cur);
		out.println(nans.size());
		for(BitSet cur : nans) {
			for(int i = 0; i < n; ++i) out.print(cur.get(i) ? 1 : 0);
			out.println();
		}
	}

	public void run() {
		System.err.println("go!");
		FS in = new FS();
		PrintWriter out = new PrintWriter(System.out);
		solve(in, out);
		out.close();
	}

	public static void main(String[] args) {
		new Thread(null, new e(), "lmao", 1L<<28).start();
	}
	static class FS {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");
		String next() {
			while(!st.hasMoreElements()) {
				try { st = new StringTokenizer(br.readLine()); }
				catch(Exception e) {}
			}
			return st.nextToken();
		}
		int nextInt() {
			return Integer.parseInt(next());
		}
		long nextLong() {
			return Long.parseLong(next());
		}
	}
}

#include <bits/stdc++.h>
using namespace std;
const int N_MAX = 1002;
int n;
int a[N_MAX];
bool ans[N_MAX][N_MAX];
bool ok[N_MAX];
int pos = 1;
void f(int l, int r) {
  if (l >= r) return;
  int cnt = a[pos];
  int x = l - 1;
  for (int i = l; i < r && cnt > 0; i++) {
    x = i;
    ans[i][pos] = ok[i] = true;
    cnt--;
  }
  for (int i = 1; i <= n + 1 && cnt > 0; i++)
    if (i < l || r < i) {
      ans[i][pos] = ok[i] = true;
      cnt--;
    }
  pos++;
  f(l, x);
  f(x + 1, r);
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  f(1, n + 1);
  int lg = n + 1;
  while (lg > 0 && ok[lg] == false) lg--;
  cout << lg << "\n";
  for (int i = 1; i <= lg; i++, cout << "\n")
    for (int j = 1; j <= n; j++) cout << ans[i][j];
  return 0;
}


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

public class Notes {
	/**
	 * int to string-> Integer.toString(int);
	 * string to int-> Integer.parseInt(string)
	 * string to char array-> string.toCharArray();
	 *
	 */
	public static void main(String args[]) {
		InputReader obj =new InputReader(System.in);
		int n=obj.nextInt();
		int m=obj.nextInt();
		String str[] = new String[n];
		for(int i=0;i<n;i++) {
			str[i]=obj.next();
		}
		int arr[] = new int [m];
		int sum=0;
		for(int i=0;i<m;i++) {
			arr[i]=obj.nextInt();
		}
		for(int i=0;i<m;i++) {
			int cnt[]=new int [5];
			for(int j=0;j<n;j++) {
				cnt[str[j].charAt(i)-65]++;
			}
			int max=0;

			for(int j=0;j<5;j++) {
				if(max<cnt[j]) {
					max=cnt[j];
				}
			}
			sum+=max*arr[i];
		}
		System.out.println(sum);
	}
	public 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());
	    }

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

	}

}

10 10
CBBBBBBBBB
ABBBBEBBBB
BDBBBBBBBB
BBBBBBBBBB
BABBBBBEBB
EBBBBBBBBB
BBBCBDCBBB
BEBBEBBBBB
BBBBBBBBBB
BBBDBBBABB
840 678 490 900 683 84 256 233 468 856

5 5
DDDDD
DDDDD
DDDDD
DDDDD
DDDDD
269 404 573 794 923

def get_ints():
    return list(map(int, input().split()))

N, M = get_ints()
a = [input() for i in range(N)]
s = get_ints()
ans=0
for i in range(M):
    d = {}
    for row in a:
        c = ord(row[i])-65
        if c in d:
            d[c]+=1
        else:
            d[c]=1

    ans += max(d.values())*s[i]
print(ans)