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

public class Test {
    int readInt() {
        int ans = 0;
        boolean neg = false;
        try {
            boolean start = false;
            for (int c = 0; (c = System.in.read()) != -1; ) {
                if (c == '-') {
                    start = true;
                    neg = true;
                    continue;
                } else if (c >= '0' && c <= '9') {
                    start = true;
                    ans = ans * 10 + c - '0';
                } else if (start) break;
            }
        } catch (IOException e) {
        }
        return neg ? -ans : ans;
    }

    int r, c;
    Scanner sca = new Scanner(System.in);
    long[][] C = new long[64][64];
    long best = Long.MAX_VALUE;

    void dfs(long x, long y, int v1, int v2) {
        long d = Math.abs(x - y);
        if (best <= 1 || d - C[v1][r]*C[v2][r] >= best) return;
        if (v1 == r - 1 && v2 == r - 1) {
            if (d < best) best = d;
            return;
        }
        if (v1 >= r) {
            long c1 = C[v1][r] - C[v1-1][r], s2 = C[v2][r];
            dfs(x, y + c1*s2, v1 - 1, v2);
        }
        if (v2 >= r) {
            long s1 = C[v1][r], c2 = C[v2][r] - C[v2-1][r];
            dfs(x + s1*c2, y, v1, v2 - 1);
        }
    }

    int[] cntA = new int[64], cntB = new int[64];
    Map<Long, Long> cache = new TreeMap<>();
    char[] cs;

    long solve(long x, long y, int v1, int v2) {
        long k = x*10000 + v1*100  + v2;
        Long v = cache.get(k);
        if (v != null) return v;
        v = 0l;
        long d = Math.abs(x - y);
        if (d - C[v1][r]*C[v2][r] > best) {
            cache.put(k, v);
            return v;
        }
        if (v1 < r || v2 < r) {
            int sum = v1 + v2;
            if (v1 >= cntA[sum] && v2 >= cntB[sum]) {
                v1 -= cntA[sum];
                v2 -= cntB[sum];
                v = C[v1+v2][v1];
                cache.put(k, v);
                return v;
            }
            cache.put(k, v);
            return v;
        }
        char c = cs[v1 + v2 - 1];
        if (c != 'B') {
            long c1 = C[v1][r] - C[v1 - 1][r], s2 = C[v2][r];
            v += solve(x, y + c1*s2, v1 - 1, v2);
        }
        if (c != 'A') {
            long s1 = C[v1][r], c2 = C[v2][r] - C[v2-1][r];
            v += solve( x + s1*c2, y, v1, v2 - 1);
        }
        cache.put(k, v);
        return v;
    }

    void start() {
        r = sca.nextInt(); c = sca.nextInt(); sca.nextLine();
        cs = sca.nextLine().toCharArray();
        for (int i = 0; i <= 2*(r + c); i++)
            for (int j = 0; j <= 2*(r + c); j++) {
                if (j == 0) C[i][j] = 1;
                else if (i == 0) C[i][j] = 0;
                else C[i][j] = C[i-1][j - 1] + C[i - 1][j];
            }
        int v1 = r + c, v2 = r + c;
        long x = 0, y = 0;
        while (v1 >= r && v2 >= 0) {
            if (x > y) {
                long c1 = C[v1][r] - C[v1 - 1][r], s2 = C[v2][r];
                y += c1*s2;
                v1--;
            } else {
                long s1 = C[v1][r], c2 = C[v2][r] - C[v2-1][r];
                x += s1*c2;
                v2--;
            }
        }
        best = Math.abs(x - y);
        dfs(0, 0, r + c, r + c);
        for (int i = 0; i < 2*(r+c); i++) {
            cntA[i + 1] = cntA[i] + (cs[i] == 'A' ? 1 : 0);
            cntB[i + 1] = cntB[i] + (cs[i] == 'B' ? 1 : 0);
        }
        long ans = solve(0, 0, r + c, r + c);
        System.out.println(ans);
    }

    public static void main(String[] args) {

        new Test().start();

    }
}


import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class Test {
  static PrintWriter writer =
      new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
  int R, C;
  long[][] ch = new long[31][31];
  int[] cntA = new int[61], cntB = new int[61];
  long best = Long.MAX_VALUE;
  String str;

  public static void main(String[] args) {
    Test te = new Test();
    te.start();
    writer.flush();
  }

  static int readInt() {
    int ans = 0;
    boolean neg = false;
    try {
      boolean start = false;
      for (int c = 0; (c = System.in.read()) != -1; ) {
        if (c == '-') {
          start = true;
          neg = true;
          continue;
        } else if (c >= '0' && c <= '9') {
          start = true;
          ans = ans * 10 + c - '0';
        } else if (start) break;
      }
    } catch (IOException e) {
    }
    return neg ? -ans : ans;
  }

  static long readLong() {
    long ans = 0;
    boolean neg = false;
    try {
      boolean start = false;
      for (int c = 0; (c = System.in.read()) != -1; ) {
        if (c == '-') {
          start = true;
          neg = true;
          continue;
        } else if (c >= '0' && c <= '9') {
          start = true;
          ans = ans * 10 + c - '0';
        } else if (start) break;
      }
    } catch (IOException e) {
    }
    return neg ? -ans : ans;
  }

  static String readString() {
    StringBuilder b = new StringBuilder();
    try {
      boolean start = false;
      for (int c = 0; (c = System.in.read()) != -1; ) {
        if (Character.isLetterOrDigit(c) || c == '?') {
          start = true;
          b.append((char) c);
        } else if (start) break;
      }
    } catch (IOException e) {
    }
    return b.toString();
  }

  static int readChars(char[] a, int off) {
    int cnt = 0;
    try {
      boolean start = false;
      for (int c = 0; (c = System.in.read()) != -1; ) {
        if (Character.isLetterOrDigit(c)) {
          start = true;
          a[off + cnt++] = (char) c;
        } else if (start) break;
      }
    } catch (IOException e) {
    }
    return cnt;
  }

  void dfs(long x, long y, int v1, int v2) {
    long diff = Math.abs(x - y);
    if (best <= 1 || diff - ch[v1][R] * ch[v2][R] >= best) return;
    if (v1 == R - 1 && v2 == R - 1) {
      if (diff < best) best = diff;
      return;
    }
    if (v1 >= R) {
      long cur = ch[v1][R] - ch[v1 - 1][R];
      long other = ch[v2][R];
      dfs(x, y + cur * other, v1 - 1, v2);
    }
    if (v2 >= R) {
      long cur = ch[v2][R] - ch[v2 - 1][R];
      long other = ch[v1][R];
      dfs(x + cur * other, y, v1, v2-1);
    }
  }

  long solve(long x, long y, int v1, int v2) {
    long diff = Math.abs(x - y);
    if (diff - ch[v1][R] * ch[v2][R] > best) return 0;
    if (v1 < R || v2 < R) {
      if (v1 >= cntA[v1 + v2] && v2 >= cntB[v1 + v2]) {
        int sum = v1 + v2;
        v1 -= cntA[sum];
        v2 -= cntB[sum];
        return ch[v1 + v2][v1];
      }
      return 0;
    }
    long ans = 0;
    char c = str.charAt(v1 + v2 - 1);
    if (c != 'B') {
      long cur = ch[v1][R] - ch[v1 - 1][R];
      long other = ch[v2][R];
      ans += solve(x, y + cur * other, v1 - 1, v2);
    }
    if (c != 'A') {
      long cur = ch[v2][R] - ch[v2 - 1][R];
      long other = ch[v1][R];
      ans += solve(x + cur * other, y, v1, v2 - 1);
    }
    return ans;
  }

  void start() {
    R = readInt();
    C = readInt();
    for (int i = 0; i <= R + C; i++)
      for (int j = 0; j <= i; j++)
        if (j == 0 || j == i) ch[i][j] = 1;
        else ch[i][j] = ch[i - 1][j - 1] + ch[i - 1][j];
    long x = 0, y = 0;
    int v1 = R + C, v2 = R + C;
    while (v1 >= R && v2 >= R)
      if (x > y) {
        long cur = ch[v1][R] - ch[v1 - 1][R];
        long other = ch[v2][R];
        y += cur * other;
        v1--;
      } else {
        long cur = ch[v2][R] - ch[v2 - 1][R];
        long other = ch[v1][R];
        x += cur * other;
        v2--;
      }
    best = Math.abs(x - y);
    dfs(0, 0, R + C, R + C);
    str = readString();
    for (int i = 0; i < 2 * (R + C); i++) {
      cntA[i + 1] = cntA[i] + (str.charAt(i) == 'A' ? 1 : 0);
      cntB[i + 1] = cntB[i] + (str.charAt(i) == 'B' ? 1 : 0);
    }
    long ans = solve(0, 0, R + C, R + C);
    writer.println(ans);
  }
}


import java.util.Scanner;

public class MinXorMst {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		long n = in.nextLong();
		int cost = 0;
		//System.out.println("Calculating");
		for(long i=1;i<n;i++) {
			cost+=(i^(i&(i-1)));
		}
		System.out.println(cost);
		in.close();
	}
   //1000000000000

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.StringTokenizer;

public class d {
    static double EPS = 1e-6;
    public static void main(String[] args) {
        FS in = new FS(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int n = in.nextInt();

        Vec com = new Vec(0, 0);
        Vec[] vecs = new Vec[n];
        for(int i = 0; i < n; i++) {
            com = com.add(vecs[i] = new Vec(in.nextInt(), in.nextInt()));
        }
        com = com.scaleR(n);

        boolean[] works = new boolean[n];
        Arrays.fill(works, true);
        int num = n;
        for(int i = 0; i < n; i++) {
            if(vecs[i].equals(com)) {
                works[i] = false;
                num--;
                continue;
            }
            for(int j = 0; j < i; j++) {
                if(works[j] && vecs[i].sub(com).equals(com.sub(vecs[j]))) {
                    works[i] = works[j] = false;
                    num -= 2;
                    break;
                }
            }
        }
        Vec[] act = new Vec[num];
        int curr = 0;
        for(int i = 0; i < n; i++) if(works[i]) act[curr++] = vecs[i];
        n = num;
        if(n == 0) {
            System.out.println(-1);
            return;
        }
        int res = 0;

        Vec[] norms = new Vec[n];

        outer: for(int i = 0; i < n; i++) {
            Vec diff = act[i].sub(act[0]);
            Vec mid = act[0].add(diff.scaleR(2));
            Vec perp = com.sub(mid).rot90();
            if(perp.equals(new Vec(0, 0))) continue;
            Vec norm = perp;
            norm = norm.scaleR(Math.sqrt(norm.dot(norm)));
            if(norm.x < 0) {
                norm.x *= -1;
                norm.y *= -1;
            }
            norms[i] = norm;
            for(int j = 0; j < i; j++) {
                if(norms[j].equals(norm)) continue outer;
            }
            double[] arr = new double[n];
            for(int j = 0; j < n; j++) arr[j] = perp.dot(act[j]);
            Arrays.sort(arr);
            double cent = (arr[0]+arr[n-1])/2;
            for(int j = 0; j < n; j++) {
                if(!eq(cent-arr[j], arr[n-1-j]-cent)) continue outer;
            }
            res++;
        }
        System.out.println(res);
        out.close();
    }

    static class Vec {
        double x, y;

        public Vec(double A, double B) {
            x = A;
            y = B;
        }

        public Vec add(Vec o) {
            return new Vec(x+o.x, y+o.y);
        }

        public Vec sub(Vec o) {
            return new Vec(x-o.x, y-o.y);
        }

        public Vec scale(double s) {
            return new Vec(x*s, y*s);
        }

        public Vec scaleR(double s) {
            return new Vec(x/s, y/s);
        }

        public Vec rot90() {
            return new Vec(-y, x);
        }

        public double dot(Vec o) {
            return x*o.x + y*o.y;
        }

        @Override
        public boolean equals(Object o) {
            return eq(x, ((Vec)o).x) && eq(y, ((Vec)o).y);
        }
    }

    static boolean eq(double a, double b) {
        return Math.abs(a-b) <= EPS;
    }

    static class FS {
        BufferedReader in;
        StringTokenizer token;

        public FS(InputStream str) {
            in = new BufferedReader(new InputStreamReader(str));
        }

        public String next() {
            if(token == null || !token.hasMoreElements()) {
                try {
                    token = new StringTokenizer(in.readLine());
                } catch (IOException ex) {
                }
                return next();
            }
            return token.nextToken();
        }

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


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.util.StringTokenizer;
import java.io.BufferedReader;
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;
        FastScanner in = new FastScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int n = in.nextInt();
            Point[] p = new Point[n];
            long sx = 0;
            long sy = 0;
            for (int i = 0; i < n; i++) {
                long x = in.nextLong();
                long y = in.nextLong();
                x *= n;
                y *= n;
                p[i] = new Point(x, y);
                sx += x;
                sy += y;
            }
            sx /= n;
            sy /= n;
            for (int i = 0; i < n; i++) {
                p[i].x -= sx;
                p[i].y -= sy;
            }
            p = removeSymmetrical(p);
            n = p.length;

            if (n <= 1) {
                out.println(-1);
                return;
            }

            Set<Point> ans = new TreeSet<>();
            for (int i = 0; i < n; i++) {
                Point dir = p[0].add(p[i]).rotate90();
                dir.normalizeDirection();
                long[] xs = new long[n];
                for (int j = 0; j < n; j++) {
                    xs[j] = dot(dir, p[j]);
                }
                Arrays.sort(xs);

                boolean ok = true;
                for (int j = 0; j < n; j++) {
                    if (xs[0] + xs[n - 1] != xs[j] + xs[n - 1 - j]) {
                        ok = false;
                        break;
                    }
                }
                if (ok) {
                    ans.add(dir);
                }
            }
            out.println(ans.size());
        }

        private Point[] removeSymmetrical(Point[] p) {
            int n = p.length;
            boolean[] dead = new boolean[n];
            for (int i = 0; i < n; i++) {
                for (int j = i + 1; j < n; j++) {
                    if (!dead[i] && !dead[j] && p[i].x == -p[j].x && p[i].y == -p[j].y) {
                        dead[i] = true;
                        dead[j] = true;
                    }
                }
            }

            int k = 0;
            for (int i = 0; i < n; i++) {
                if (!dead[i]) {
                    p[k++] = p[i];
                }
            }
            return Arrays.copyOf(p, k);
        }

        private long dot(Point a, Point b) {
            return a.x * b.x + a.y * b.y;
        }

        private long gcd(long a, long b) {
            return b == 0 ? a : gcd(b, a % b);
        }

        class Point implements Comparable<Point> {
            long x;
            long y;

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

            Point add(Point o) {
                return new Point(x + o.x, y + o.y);
            }

            Point rotate90() {
                return new Point(-y, x);
            }

            void normalizeDirection() {
                long d = gcd(Math.abs(x), Math.abs(y));
                if (y > 0 || y == 0 && x > 0) {

                } else {
                    x = -x;
                    y = -y;
                }
                x /= d;
                y /= d;
            }

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

        }

    }

    static class FastScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public FastScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

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

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

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

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String[] str = br.readLine().split(" ");
    int n = Integer.parseInt(str[0]);
    int m = Integer.parseInt(str[1]);

    int N = 0;
    List<Integer> v = new ArrayList<>();
    List<Integer> w = new ArrayList<>();

    for(int i=0; i<m; ++i){
      str = br.readLine().split(" ");
      int a = Integer.parseInt(str[0]);
      int b = Integer.parseInt(str[1]);
      N += a;
      for(int j=0; j<a; ++j){
        w.add(1);
        v.add(b);
      }
    }
    //System.out.println(N);
    int[][] dp = new int[N+1][n+1];

    for(int i=0; i<=N; ++i){
      for(int j=0; j<=n; ++j){
        if(i==0) dp[i][j] = 0;
        else if(j==0) dp[i][j] = 0;
        else
          dp[i][j] = Math.max(v.get(i-1) + dp[i-1][j-w.get(i-1)], dp[i-1][j]);
      }
    }
//    for(int i=0; i<=N; ++i)
//      System.out.println(Arrays.toString(dp[i]));
    System.out.println(dp[N][n]);

  }
}


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

public class ProblemB_51 {

	final boolean ONLINE_JUDGE=System.getProperty("ONLINE_JUDGE")!=null;
	BufferedReader in;
	PrintWriter out;
	StringTokenizer tok=new StringTokenizer("");

	void init() throws FileNotFoundException{
		if (ONLINE_JUDGE){
			in=new BufferedReader(new InputStreamReader(System.in));
			out =new PrintWriter(System.out);
		}
		else{
			in = new BufferedReader(new FileReader("input.txt"));
			out = new PrintWriter("output.txt");
		}
	}

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

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

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

	public void run(){
		try{
			long t1=System.currentTimeMillis();
			init();
			solve();
			out.close();
			long t2=System.currentTimeMillis();
			System.err.println("Time = "+(t2-t1));
		}catch (Exception e){
			e.printStackTrace(System.err);
			System.exit(-1);
		}
	}

	void solve() throws IOException{
		long[] a=new long[6];
		for (int i=0; i<4; i++){
			a[i]=readInt();
		}
		a[5]=0;
		String[] c=new String[3];
		for (int i=0; i<3; i++){
			c[i]=readString();
		}
		HashSet<Integer> b=new HashSet<Integer>();
		long min=Long.MAX_VALUE;
		for (int i1=0; i1<4; i1++){
			b.clear();
			a[5]=0;
			a[4]=a[i1];
			b.add(i1);
			for (int i2=0; i2<4; i2++){
				if (!b.contains(i2)){
					b.add(i2);
					if (c[0].charAt(0)=='+'){
						a[4]+=a[i2];
					}else{
						a[4]*=a[i2];
					}
					for (int i3=0; i3<5; i3++){
						if (!b.contains(i3)){
							b.add(i3);
							a[5]=a[i3];
							for (int i4=0; i4<5; i4++){
								if (!b.contains(i4)){
									b.add(i4);
									if (c[1].charAt(0)=='+'){
										a[5]+=a[i4];
									}else{
										a[5]*=a[i4];
									}
									for (int i=0; i<5; i++){
										if(!b.contains(i)){
												if (c[2].charAt(0)=='+'){
													a[5]+=a[i];
												}else{
													a[5]*=a[i];
												}
												if (a[5]<min){
													min=a[5];
												}
												if (c[2].charAt(0)=='+'){
													a[5]-=a[i];
												}else{
													a[5]/=a[i];
												}
											}
										}
									b.remove(i4);
									a[5]=a[i3];
								}
							}
							b.remove(i3);
							a[5]=0;
						}
					}
					b.remove(i2);
					if (c[0].charAt(0)=='+'){
						a[4]-=a[i2];
					}else{
						a[4]/=a[i2];
					}
				}
			}
		}
		out.print(min);
	}
}


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

public class cf215A {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int d = sc.nextInt();
        sc.nextLine();
        String[] s = sc.nextLine().split(" ");
        int[] a = new int[s.length];
        for (int i = 0; i < s.length; i++) {
            a[i] = Integer.parseInt(s[i]);
        }
        Arrays.sort(a);
        int m = sc.nextInt();
        int profit = 0;
        for (int i = 0; i < m && i < a.length; i++) {
            profit += a[i];
        }
        profit += (n-m)*d;
        System.out.println(profit);
    }
}


import java.util.*;
import java.io.*;
import java.util.stream.IntStream;

public class Solution
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        String a1[]=sc.nextLine().split(" ");
        String a2[]=sc.nextLine().split(" ");
        int a[]=new int[a1.length];
        int b[]=new int[a2.length];
        for(int i=0;i<a1.length;i++)
        {
           a[i]=(Integer.parseInt(a1[i]));
            b[i]=(Integer.parseInt(a2[i]));

        }

        int n=Integer.parseInt(sc.nextLine());
        int sum_a=IntStream.of(a).sum();
        int count;
        if(sum_a%5!=0) {
             count = (sum_a / 5) + 1;
        }
        else
            count=sum_a/5;
        if(count>=n)
        {
            System.out.println("NO");
            return;
        }
        int sum_b=IntStream.of(b).sum();
       if(sum_b%10!=0)
        count+=(sum_b/10)+1;
       else
           count+=(sum_b/10);

        if(count<=n)
            System.out.println("YES");
        else
            System.out.println("NO");

    }
}


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

import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;

public class  Main  {

	//ArrayList<Integer> lis = new ArrayList<Integer>();
	//ArrayList<String> lis = new ArrayList<String>();
	//ArrayList<test> lis = new ArrayList<test>();
//	static long sum=0;
//	static boolean f=false;
	//static String s[],r="";
//	static int dx[]={1,-1,0,0,1,1,-1,-1};
  //  static int dy[]={0,0,1,-1,1,-1,1,-1},n,m,w=0;
	//static int dp[][][][],co,r=0;
	//throws IOException
	//static char c[][];
	static boolean b=false,me[][][][][];

public  static void main(String[] args)  {
   //googlein.txt C-small-attempt0.in
//	Scanner sc =new Scanner(new File("file.txt"));
	 Scanner sc =new Scanner(System.in);
	  //File file = new File("file.txt");
	//	PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
	//	sc.useDelimiter("(\\s)+|[,]");

	  while(sc.hasNext()){
		   //long sum=0;
	//	  int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt();
		int   n=sc.nextInt();
		b=false;
	//	db((int)sc.next().charAt(0));
      char  c[][]=new char[2][n];
	 me=new boolean [2][100][100][100][n];
		 for(int i=0;i<n;i++){
			 String s=sc.next();
			 c[0][i]=s.charAt(0);
			 c[1][i]=s.charAt(1);
		 }

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

		 rep(n-1,c);

	  System.out.println(b? "YES":"NO");

		 }

}
	// db("Case #"+(k)+": "+c);
	 //	pw.println("Case #"+(k)+": "+c);

	 	//pw.flush();
	 	//pw.close();

   static void rep(int a,char p[][]){

	   if( b )return;
	   if(a==0){ b=true; return; }
	  // db(p[0],p[1]);

	   if(3<a && me[0][p[0][a-2]][p[0][a-1]][p[0][a]][a] && me[1][p[1][a-2]][p[1][a-1]][p[1][a]][a] )return;

	   if(  p[0][a]==p[0][a-1]   ||  p[1][a]==p[1][a-1]   ){
	   char np[][]=new char[2][a];
	   for(int i=0;i<a;i++){np[0][i]=p[0][i]; np[1][i]=p[1][i];}  np[0][a-1]=p[0][a];np[1][a-1]=p[1][a];
	     rep(a-1,np ); }

	   if(  0<=a-3 && (  p[0][a]==p[0][a-3]  || p[1][a]==p[1][a-3] ) ){
	   char np[][]=new char[2][a];
	   for(int i=0;i<a;i++){np[0][i]=p[0][i]; np[1][i]=p[1][i];}  np[0][a-3]=p[0][a];np[1][a-3]=p[1][a];
	     rep(a-1,np ); }

	 if(3<a)  me[1][p[1][a-2]][p[1][a-1]][p[1][a]][a] = me[1][p[1][a-2]][p[1][a-1]][p[1][a]][a]=true;

   }

    static void db(Object... os){
	         System.err.println(Arrays.deepToString(os));

	}

}

/*class P implements Comparable<P>{
    int v,vv,t;
	P(int v,int vv,int t){
		this.v=v;
	    this.vv=vv;
	    this.t=t;
	}
	  public int compareTo(P x){
          return t-x.t;
	   }

}*/


import java.util.HashSet;
import java.util.Scanner;

public class Main {

    /**
     * @param args
     */
    static int n;
    static StringBuilder[] strs;
    static HashSet<String> hs=new HashSet<String>();
    static boolean ok(int x,int y)
    {
        return strs[x].charAt(0)==strs[y].charAt(0)
                || strs[x].charAt(1)==strs[y].charAt(1);
    }

    static boolean dfs(int x){
        if(x==0)return true;
        if(x>1){
            if(hs.contains(strs[x].append(strs[x-1]).append(strs[x-2]).append(x)))return false;
            if(x>2&&ok(x,x-3)){
                StringBuilder t=strs[x-3];
                strs[x-3]=strs[x];
                if(dfs(x-1))return true;
                strs[x-3]=t;
            }
        }
        if(ok(x,x-1)){
            StringBuilder t=strs[x-1];
            strs[x-1]=strs[x];
            if(dfs(x-1))return true;
            strs[x-1]=t;
        }
        if(x>1)hs.add(strs[x].append(strs[x-1]).append(strs[x-2]).append(x).toString());
        return false;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        n=in.nextInt();strs=new StringBuilder[n];
        for(int i=0;i<n;i++)strs[i]=new StringBuilder(in.next());
        System.out.println(dfs(n-1)?"YES":"NO");
    }

}


import java.io.*;
import java.util.*;
public class CodeForces {

    /**
     * @param args the command line arguments
     */
    public long preprocess(long n)
    {
        HashSet<Long> lovely=new HashSet<Long>();
        for(long i=2;i*i<=n;i++)
        {
            for(long j=1;j*i*i<=n;j++)
            {
                lovely.add(j*i*i);
            }
        }
        long result=0;
        for(long i=n;i>=1;i--)
        {
            if(!lovely.contains(i)&&n%i==0)
            {
                result=i;
                break;
            }
        }
        return result;
    }
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner ss=new Scanner(System.in);
        long num=ss.nextLong();
        CodeForces xx=new CodeForces();
        long result=xx.preprocess(num);
        System.out.println(result);

    }

}


import java.util.Scanner;

public class q1
{

    public static void main(String args[])
    {
        Scanner s=new Scanner(System.in);
        int n=s.nextInt();
        int k1=s.nextInt();
        int a[]=new int[n];
        int of=0;
        int tf=0;
        for(int i=0;i<n;i++)
        {

        a[i]=s.nextInt()%2;
        if(a[i]==0)
            tf++;
        else
            of++;
        }

        int ans=Integer.MAX_VALUE;
        for(int k=1;k<=k1;k++)
        {
            if(k1%k!=0)
                continue;
            for(int i=0;i<n;i+=n/k)
        {
            int tmp=0;
            for(int j=0;j<n;j++)
            {
                tmp+=(a[i+j%k]^a[j]);
            }
            //System.out.println(tmp+" "+k+" "+i*k);
            ans=Math.min(ans,tmp);
        }

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


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

public class Playground{
	static int [] arrTemp;
	public static void main(String [] args) {

		Scanner input = new Scanner(System.in);
		arrTemp= new int[input.nextInt()];
		String number = input.next();
		for(int x=0;x<arrTemp.length;x++) {
			arrTemp[x]= Integer.parseInt(number.substring(x, x+1));
		}

		for(int x=1;x<=arrTemp.length;x++) {
		place(x,new HashMap<>());

		}
		System.out.println("NO");

	}

	public static void place(int markers,HashMap<Integer,Integer> pos) {
		for(int x=1;x<arrTemp.length;x++) {
			if(pos.containsKey(x)) {
				continue;
			}
			pos.put(x,-1);
			if(markers==1) {
				if(simulate(pos)) {
					System.out.println("YES");
					System.exit(0);
				};
			}else {

				place(markers-1,pos);

			}
			pos.remove(x);

		}

	}

	public static boolean simulate(HashMap<Integer,Integer> pos) {
		int truePostion=0;

		int sum=-1;
		for(int x:pos.keySet()) {
			int subSum=0;
			int limit = x;

			for(int i=truePostion;i<x;i++) {
				subSum+=arrTemp[i];

				if(subSum>sum&&sum!=-1) {

					return false;
				}
			}
			if(sum>subSum) {
				return false;
			}

			sum=subSum;
			//System.out.println(sum);

			truePostion=x;

		}

		for(int i=truePostion;i<arrTemp.length;i++) {
			sum-=arrTemp[i];
			if(sum<0) {

				return false;
			}

		}

		return sum==0;
	}

}


import java.util.Scanner;

public class lcm {

    static void SieveOfEratosthenes(int n, boolean prime[], boolean primesquare[], int a[]) {

        for (int i = 2; i <= n; i++)
            prime[i] = true;

        for (int i = 0; i < ((n * n) + 1); i++)
            primesquare[i] = false;

        prime[1] = false;

        for (int p = 2; p * p <= n; p++) {

            if (prime[p]) {
                // Update all multiples of p
                for (int i = p * 2; i <= n; i += p)
                    prime[i] = false;
            }
        }

        int j = 0;
        for (int p = 2; p <= n; p++) {
            if (prime[p]) {
                a[j] = p;
                primesquare[p * p] = true;
                j++;
            }
        }
    }

    static int countDivisors(int n) {

        if (n == 1)
            return 1;

        boolean prime[] = new boolean[n + 1];
        boolean primesquare[] = new boolean[(n * n) + 1];

        int a[] = new int[n];

        SieveOfEratosthenes(n, prime, primesquare, a);

        int ans = 1;

        for (int i = 0; ; i++) {

            if (a[i] * a[i] * a[i] > n)
                break;

            int cnt = 1;

            while (n % a[i] == 0) {
                n = n / a[i];
                cnt = cnt + 1;
            }
            ans = ans * cnt;
        }

        if (prime[n])
            ans = ans * 2;
        else if (primesquare[n])
            ans = ans * 3;
        else if (n != 1)
            ans = ans * 4;
        return ans;
    }

    public static void main(String args[]) {
        Scanner scn = new Scanner(System.in);
        int b = scn.nextInt();
        System.out.println(countDivisors(b));
    }
}


    import java.util.Scanner;

    public class A {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            long b = sc.nextLong();
            long a;
            int[] arr = new int[100000000];

            int count = 0;
            for (a = 1; a<=b; a++){
                if (arr[(int)(b/gcd(a,b))] != 1){
                    count++;
                    arr[(int)(b/gcd(a,b))] = 1;
                }
            }
            System.out.println(count);
        }

        public static long gcd(long a, long b){
            long g = 1;
            for (long i = Math.min(a,b); i >= 1 ; i--) {
                if (a % i == 0 && b % i == 0){
                    g = i;
                    return g;
                }
            }
            return g;
        }
    }


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main
{
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[(int)(1e9)]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }

    public static void main(String[] args) throws IOException
    {
        Reader  sc= new Reader();
        PrintWriter w = new PrintWriter(System.out);
        int[] Count= new int[4];
        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
        String s =sc.readLine();
        for(int i=0;i<s.length();i++){
        	if(s.charAt(i)!='!'){
        		hm.put(s.charAt(i), (i%4));
        	}else{
        		Count[(i%4)]++;
        	}
        }

        w.println(Count[hm.get('R')]+" "+Count[hm.get('B')]+" "+Count[hm.get('Y')]+" "+Count[hm.get('G')]);

        w.close();
    }
}


import java.util.Scanner;

public class DefiniteGame {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		if (n == 1) {
			System.out.println(1);
			return;
		}
		int i = 2;
		while (n != 0) {
			if (n % i != 0)
				n = n - i;
			i++;
		}
		System.out.println(n);
	}
}


import java.util.Scanner;

public class Solution {

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

		long num = sc.nextLong();

		while (num > 1) {
			long i=num-1;
			boolean found = false;
			for(; i > 1; i--) {
				if (num % i != 0) {
					found = true;
					break;
				}
			}
			if (found) num = num - i;
		}

		System.out.println(num);
	}

}


import java.util.Scanner;

public class samp{
    public static void main(String args[]){
    Scanner s=new Scanner(System.in);
    double a=s.nextDouble(),b=s.nextDouble(),c=s.nextDouble(),d=s.nextDouble();
    double ans=Math.ceil(Math.ceil(b/c) * a / d);
    System.out.println("%.0f",ans);
    }
}


5 3 2 3
import java.util.*;
public class Paper_Airplanes
{
    public static void main(String args[])
    {
        Scanner s1 = new Scanner(System.in);
        double k,n,s,p;
        k = s1.nextDouble();
        n = s1.nextDouble();
        s = s1.nextDouble();
        p = s1.nextDouble();
        // System.out.println((k*n)/(s*p));
        double ans = Math.ceil((Math.ceil(n/s) * k)/p);
        String ans1 = Double.toString(ans);
        int pos = -1;
        for(int i=0;i<ans1.length();i++)
            if(ans1.charAt(i) == '.')
            {
                pos = i;
                break;
            }
        System.out.println(Integer.parseInt(ans1.substring(0,pos)));
        // System.out.println(Math.ceil((Math.ceil(n/s) * k)/p));
        s1.close();
    }
}


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

public class C
{

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        BigInteger x = sc.nextBigInteger();
        BigInteger k = sc.nextBigInteger();
        BigInteger zero = new BigInteger("0");
        BigInteger one = new BigInteger("1");
        BigInteger two = new BigInteger("2");
        BigInteger b = (k.add(one)).mod(modulo);
        BigInteger a = k.mod(modulo);
        BigInteger modulo = new BigInteger("1000000006");
        BigInteger ans = two.modPow(b,modulo);
        ans = ans.multiply(x);
        ans = ans.subtract(two.modPow(a,modulo));
        ans = ans.add(one);
        ans = ans.mod(modulo);
        if (x.equals(zero))
        {
         System.out.println(0);
         }
         else
         {
        System.out.println(ans);
        }
    }
}


package code;

import iensen.IO.InputReader;

import java.io.PrintWriter;
import java.util.HashMap;

public class Task
{
    public void solve(int testNumber, InputReader in, PrintWriter out)
    {
        int n = in.nextInt();
        int m = in.nextInt();
        String[] Viruses = new String[m];
        for (int i = 0; i < m; i++)
        {
            Viruses[i] = in.nextToken();
        }
        HashMap<String, Integer> Index = new HashMap<String, Integer>();
        int lastIndex = 1;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < Viruses[i].length(); j++)
            {
                Index.put(Viruses[i].substring(0, j + 1), lastIndex++);
            }
        }
        Index.put("",0);
        int[][] replaceMent = new int[lastIndex][26];
        int[] longestSuffix = new int[lastIndex];
        //Найдем строку, которая заканчиывает каждый префикс и является наибольшей:
        for (String s : Index.keySet())
            for (String t : Viruses)
                if (s.endsWith(t))
                    longestSuffix[Index.get(s)] = Math.max(longestSuffix[Index.get(s)], t.length());

        //Допустим мы в позиции I, и пишем букву CH. Найдем максимальный префикс который в итоге получитcя:

        for (String s : Index.keySet()) {
            int start = Index.get(s);
            for (char ch = 'A'; ch <= 'Z'; ch++) {
                String candidate=s.concat(Character.toString(ch));//берем по максимуму
                while (!Index.containsKey(candidate))
                    candidate = candidate.substring(1);//отрезаем первый символ
                replaceMent[start][ch-'A'] = Index.get(candidate);
            }
        }

        int[][] dp = new int[lastIndex][20]; //За состояние в индексе I примем последний
                                                //префикс И удаленность первого ненакрытого символа
        int modulo=1000000009;
        dp[Index.get("")][0] = 1;//Существует ровно одна пустая строка
        for (int idx = 0; idx < n; ++idx) {
            int[][] newDp = new int[lastIndex][20];
            for (int oldprefix = 0; oldprefix < lastIndex; oldprefix++)
                for (int oldCover = 0; oldCover < 20; oldCover++) {
                    for (char ch='A'; ch <='Z'; ch++) {
                        int newPrefix = replaceMent[oldprefix][ch-'A'];
                        int newCover = oldCover + 1; //теперь нам надо на 1 больше,так как мы продвинулись на 1
                        if (newCover <= longestSuffix[newPrefix])
                            newCover = 0;//если мы накрыли то что было ненакрыто, то we are happy!
                        if (newCover >=20)//тяжелый случай
                            continue;
                        newDp[newPrefix][newCover] = (newDp[newPrefix][newCover]+dp[oldprefix][oldCover])%modulo;

                    }
                }
            dp=newDp;
            //cnt = oneStep(cnt, maxLength, last, isFinish, next);
        }
        int answer = 0;
        for (int i = 0; i < lastIndex; i++) {
            answer = (answer+dp[i][0])%modulo;

        }
        out.println(answer);
    }
}


//package yandex2011.r2;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;

public class C {
	Scanner in;
	PrintWriter out;
//	String INPUT = "1000 10\r\n" +
//			"CAT\r\n" +
//			"TACT\r\nAAAAAAAAAA CCCCCCCCCC GGGGGGGGGG TTTTTTTTTT AAAAACCCCG CCCCCGGGGT TTTTTGGGAA AAAGTCCCCC";
//	String INPUT = "6 2 CAT TACT";
//	String INPUT = "2 1 A";
//	String INPUT = "6 3 CA AT CATG";
	String INPUT = "";

	long MOD = 1000000009;

	void solve()
	{
		int n = ni();
		int m = ni();
		String[] s = new String[m];
		int p = 0;
		for(int i = 0;i < m;i++){
			String x = in.next();
			if(x.length() <= n)s[p++] = in.next();
		}
		Trie t = new Trie(Arrays.copyOf(s, p));
		out.println(t.go(n));
	}

	void run() throws Exception
	{
		in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(INPUT);
		out = new PrintWriter(System.out);

		solve();
		out.flush();
	}

	public static class Trie {
		public int[][] trie;
		public BitSet[] hit;
		public int[] failure;
		public int nq; // クエリの個数
		public int[] amap;
		public int[] back;
		public int[] backc;

		public Trie(String[] strs)
		{
			amap = new int[100];
			amap['A'] = 0;
			amap['C'] = 1;
			amap['G'] = 2;
			amap['T'] = 3;
			build(strs);
		}

		public void build(String[] strs)
		{
			int n = strs.length;
			int m = 1;
			for(String s : strs)m += s.length();
			trie = new int[m][4];
			back = new int[m];
			backc = new int[m];
			Arrays.fill(back, -1);
			hit = new BitSet[m];
			for(int i = 1;i < m;i++) {
				Arrays.fill(trie[i], -1);
			}

			int p = 1;
			for(int i = 0;i < n;i++) {
				int st = 0;
				for(int j = 0;j < strs[i].length();j++) {
					int c = amap[strs[i].charAt(j)];
					if(trie[st][c] > 0) {
						st = trie[st][c];
					}else {
						trie[st][c] = p;
						back[p] = st;
						backc[p] = c;
						st = p;
						p++;
					}
				}
				if(hit[st] == null)hit[st] = new BitSet();
				hit[st].set(i);
			}

			trie = Arrays.copyOf(trie, p);
			hit = Arrays.copyOf(hit, p);
			nq = n;

			buildFailure();
		}

		public void buildFailure()
		{
			Queue<Integer> q = new ArrayDeque<Integer>();
			q.add(0);
			failure = new int[trie.length];
			Arrays.fill(failure, -1);
			failure[0] = 0;
			while(q.size() > 0) {
				int cur = q.poll();
				for(int i = 0;i < 4;i++) {
					int nex = trie[cur][i];
					if(nex != -1 && failure[nex] == -1) {
						q.add(nex);
						if(cur == 0) {
							failure[nex] = 0;
							continue;
						}

						failure[nex] = 0;
						for(int fc = failure[cur]; (failure[nex] = trie[fc][i]) == -1;fc = failure[fc]) {
							if(fc == 0)break;
						}
						if(failure[nex] > 0 && hit[failure[nex]] != null) {
							if(hit[nex] == null)hit[nex] = new BitSet();
							hit[nex].or(hit[failure[nex]]);
						}
					}
				}
			}
		}

		public long go(int n)
		{
			int m = trie.length;
			long[][] dp = new long[n][m];
			for(int i = 0;i < 4;i++){
				if(trie[0][i] > 0){
					dp[0][trie[0][i]]++;
				}
			}
			for(int i = 0;i < n-1;i++){
				for(int j = 1;j < m;j++){ // state
					for(int k = 0;k < 4;k++){
						if(hit[j] == null && trie[j][k] == -1){
							List<Integer> hist = new ArrayList<Integer>();
							List<Integer> histc = new ArrayList<Integer>();
							hist.add(j);
							histc.add(backc[j]);
							boolean ok = false;
							outer:
							for(int q = back[j];q > 0;hist.add(q), histc.add(backc[q]), q = back[q]){
								if(hit[q] != null){
									int sss = 0;
									for(int l = hist.size()-1;l >= 0;l--){
										while(trie[sss][histc.get(l)] == -1)sss = failure[sss];
										sss = trie[sss][histc.get(l)];
										if(sss <= 0)continue outer;
									}
									if(hit[sss] != null){
										ok = true;
										break outer;
									}
								}
							}
							if(!ok)continue;
						}
						int st = j;
						while(trie[st][k] == -1)st = failure[st];
						int des = trie[st][k];
						if(des > 0){
							dp[i+1][des] += dp[i][j];
							dp[i+1][des] %= MOD;
						}
					}
				}
				tr(dp[i+1]);
			}

			long ret = 0;
			for(int j = 1;j < m;j++){
				if(hit[j] != null){
					ret += dp[n-1][j];
				}
			}
			return ret % MOD;
		}
		long MOD = 1000000009L;

		void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }

		public Map<Integer, List<Integer>> query(String text)
		{
			Map<Integer, List<Integer>> ret = new HashMap<Integer, List<Integer>>();
			int st = 0;
			for(int i = 0;i < text.length();i++) {
				int c = amap[text.charAt(i)];
				while(trie[st][c] == -1) {
					st = failure[st];
				}
				st = trie[st][c];
				if(hit[st] != null) {
					for(int j = hit[st].nextSetBit(0); j != -1; j = hit[st].nextSetBit(j + 1)) {
						if(!ret.containsKey(j))ret.put(j, new ArrayList<Integer>());
						ret.get(j).add(i);
					}
				}
			}
			return ret;
		}
	}

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

	int ni() { return Integer.parseInt(in.next()); }
	double nd() { return Double.parseDouble(in.next()); }
	void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        int f1 = sc.nextInt();
        int f2 = sc.nextInt();
        int n = sc.nextInt();
        int [] arr = new int [n];
        arr[0] = f1;
        arr[1] =f2;
        for (int i = 2; i < n; i++) {
            arr[i] = arr[i-1]-arr[i-2];
        }
        if(arr[n-1]>=0){
            System.out.println(arr[n-1]%(1000000007));
        }
        else{
            System.out.println((1000000007+arr[n-1])%1000000007);
        }

    }

}


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
  static final int num = 1000000007;

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

    int f1 = mod(scan.nextInt());
    int f2 = mod(scan.nextInt());
    int n = scan.nextInt();

    if (n == 1) {
      System.out.println(f1);
      return;
    } else if (n == 2) {
      System.out.println(f2);
      return;
    }

    int[] mods = new int[n];
    mods[0] = f1;
    mods[1] = f2;

    for (int i = 1; i < n - 1; i++) {
      mods[i + 1] = mod(mods[i] - mods[i - 1]);
    }

    System.out.println(mods[n - 1]);
  }

  private static int mod(int x) {
    int m = x % num;
    return m < 0 ? m + num : m;
  }
}


import java.util.Scanner;

public class JzzhuandSequences {

	static int mod=1000000007;
	public static void main(String[] args) {

		Scanner sc=new Scanner(System.in);
		int x=sc.nextInt();
		int y=sc.nextInt();
		int n=sc.nextInt();
		int[] arr=new int[n+1];
		arr[1]=x;
		arr[2]=y;
		for(int i=3;i<=n;i++)
		{
			arr[i]=arr[i-1]-arr[i-2];
			arr[i]=arr[i]%mod;
		}
		if(arr[n]>=mod)
		{
			arr[n]-=mod;
		}
		else
			if(arr[n]<0)
				arr[n]+=mod;
		System.out.println(arr[n]);
	}

}


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.io.InputStream;

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

    static class C887 {
        private int sequences = new int[][]{
                {1, 3, 5, 7, 9, 11, 24, 22},
                {2, 4, 6, 8, 10, 12, 23, 21},
                {13, 14, 5, 6, 17, 18, 21, 22},
                {15, 16, 7, 8, 19, 20, 23, 24},
                {3, 4, 17, 19, 10, 9, 16, 14},
                {1, 2, 22, 24, 12, 11, 15, 13}
        };

        public void solve(int testNumber, ScanReader in, PrintWriter out) {
            int cube[] = new int[25];
            for (int i = 1; i <= 24; i++) cube[i] = in.scanInt();
            for (int i = 0; i < 6; i++) {
                for (int k = 0; k < 2; k++) {
                    rotate(cube, sequences[i], k);
                    if (checkit(cube)) {
                        out.println("YES");
                        return;
                    }
                    rotate(cube, sequences[i], 1 ^ k);
                }
            }
            out.println("NO");
        }

        private void rotate(int[] cube, int[] seq, int state) {
            if (state == 1) {
                int temp1 = cube[seq[0]];
                int temp2 = cube[seq[1]];
                for (int i = 0; i < 6; i++) cube[seq[i]] = cube[seq[i + 2]];
                cube[seq[6]] = temp1;
                cube[seq[7]] = temp2;
            } else {
                int temp1 = cube[seq[6]];
                int temp2 = cube[seq[7]];
                for (int i = 7; i >= 2; i--) cube[seq[i]] = cube[seq[i - 2]];
                cube[seq[0]] = temp1;
                cube[seq[1]] = temp2;
            }
        }

        private boolean checkit(int cube[]) {
            for (int i = 1; i <= 24; i++) {
                if (cube[i] != cube[(((i / 4) - (i % 4 == 0 ? 1 : 0)) * 4) + 1]) return false;
            }
            return true;
        }

    }

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

    }
}


import java.util.*;

public class 1060A {
 public static void main(String[] args){
  Scanner sc = new Scanner(System.in);
  int n = sc.nextInt();
  String s = sc.next();

  int count=0;
  for (int i=0;i<n;i++){
   if (s.charAt(i) == '8'){
    count++;
   }
  }
  int floor = (int) Math.floor(n/11);
  int asdf = Math.min(count,floor);
  System.out.println(asdf);
 }
}


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

import static java.lang.Math.*;

public class Cf182 implements Runnable
{
	static class InputReader
	{
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;
		private SpaceCharFilter filter;
		private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		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 String nextLine()
		{
			String str = "";
			try
			{
				str = br.readLine();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			return str;
		}
		public int nextInt()
		{
			int c = read();

			while(isSpaceChar(c))
				c = read();

			int sgn = 1;

			if (c == '-')
			{
				sgn = -1;
				c = read();
			}

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

			return res * sgn;
		}

		public long nextLong()
		{
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-')
			{
				sgn = -1;
				c = read();
			}
			long res = 0;

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

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

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

			return res.toString();
		}

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

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

		public interface SpaceCharFilter
		{
			public boolean isSpaceChar(int ch);
		}
	}
	public static void main(String args[]) throws Exception
	{
		new Thread(null, new Cf182(),"Main",1<<27).start();
	}

	public static long gcd(long a, long b)
	{
		if (a == 0)
			return b;
		return gcd(b % a, a);
	}
	//  array sorting by colm
public static void sortbyColumn(int arr[][], int col)
    {

        Arrays.sort(arr, new Comparator<int[]>() {

          @Override
          public int compare(final int[] entry1,
                             final int[] entry2) {

            if (entry1[col] > entry2[col])
                return 1;
            else
                return -1;
          }
        });
    }

	// gcd

	public static long findGCD(long arr[], int n)
	{
		long result = arr[0];
		for (int i = 1; i < n; i++)
			result = gcd(arr[i], result);
		return result;
	}
	// fibonaci
	static int fib(int n)
    {
        int a = 0, b = 1, c;
        if (n == 0)
            return a;
        for (int i = 2; i <= n; i++)
        {
            c = a + b;
            a = b;
            b = c;
        }
        return b;
    }

// sort a string
    public static String sortString(String inputString)
    {

        char tempArray[] = inputString.toCharArray();

        Arrays.sort(tempArray);

        return new String(tempArray);
    }
    // pair function

    // list.add(new Pair<>(sc.nextInt(), i + 1));
    //     Collections.sort(list, (a, b) -> Integer.compare(b.first, a.first));
    private static class Pair<F, S> {

        private F first;

        private S second;

        public Pair() {}

        public Pair(F first, S second) {
            this.first = first;
            this.second = second;
        }
    }
    static long negProdSubArr(int arr[], int n)
    {
        long positive = 1, negative = 0;
        for (int i = 0; i < n; i++)
        {
            if (i > 0)
                arr[i] *= arr[i - 1];

            if (arr[i] == 1)
                positive++;
            else
                negative++;
        }

        return (positive * negative);
    }

	public void run()
	{
		InputReader sc = new InputReader(System.in);
		PrintWriter w = new PrintWriter(System.out);
		String s1 = sc.next();
		String s2 = sc.next();
		String s3 = sc.next();
		int c1 = s1.charAt(0)-48;
		int c2 = s2.charAt(0)-48;
		int c3 = s3.charAt(0)-48;
		if(s1.equals(s2) && s2.equals(s3))
		    w.println("0");
		else if(s1.charAt(1)==s2.charAt(1) && s2.charAt(1)==s3.charAt(1))
	    {
	        if(c1+1==c2 && c2+1==c3)
	            w.println("0");
	        else if(c1+1==c3 && c3+1==c2)
	            w.println("0");
	        else if(c2+1==c1 && c1+1==c3)
	            w.println("0");
	        else if(c2+1==c3 && c3+1==c1)
	            w.println("0");
	        else if(c3+1==c2 && c2+1==c1)
	            w.println("0");
	       else if(c3+1==c1 && c1+1==c2)
	            w.println("0");
	       else if(c1+1==c2 || c1+1==c3 || c2+1==c3 || c2+1==c1 || c3+1==c2 || c3+1==c1)
	            w.println("1");
	        else if(c1+2==c2 || c1+2==c3 || c2+2==c3 || c2+2==c1 || c3+2==c2 || c3+2==c1)
	            w.println("1");
	        else
	            w.println("2");
	    }
		else
		{
		    int ans = 5;
		    if((c1+1==c2 || c2+1==c1) && s1.charAt(1)==s2.charAt(1))
		        ans = Math.min(ans,1);
		    else if((c1+1==c3 || c3+1==c1) && s1.charAt(1)==s3.charAt(1))
		        ans = Math.min(ans,1);
		    else if((c2+1==c3 || c3+1==c2 ) && s2.charAt(1)==s3.charAt(1))
		        ans = Math.min(ans,1);
		    else if((c1+2==c2 || c2+2==c1) && s1.charAt(1)==s2.charAt(1))
		        ans = Math.min(ans,1);
		    else if((c1+2==c3 || c3+2==c1) && s1.charAt(1)==s3.charAt(1))
		        ans = Math.min(ans,1);
		    else if((c2+2==c3 || c3+2==c2 ) && s2.charAt(1)==s3.charAt(1))
		        ans = Math.min(ans,1);
		    else if(s1.equals(s2))
		        ans = Math.min(ans,1);
		    else if(s1.equals(s3))
		        ans = Math.min(ans,1);
		    else if(s2.equals(s3))
		        ans = Math.min(ans,1);
		    else
		        ans = Math.min(ans,2);
		    w.println(ans);
		}
        w.flush();
	    w.close();
	}
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 *
 *
 * 3 2 3 5
 * -2 -1 4 -1 2 7 3
 *
 * 10 1 -10617 30886 -7223 -63085 47793 -61665 -14614 60492 16649 -58579 3 8 1
 * 10 4 7 1 7 3 7
 *
 * 22862 -34877
 *
 * @author pttrung
 */
public class B_CodeStrike2014_Final {

    public static long MOD = 1000000007;
    static int[] X = {0, 1};
    static int[] Y = {1, 0};
    static int[][][] dp;

    public static void main(String[] args) throws FileNotFoundException {
        // PrintWriter out = new PrintWriter(new FileOutputStream(new File(
        // "output.txt")));
        PrintWriter out = new PrintWriter(System.out);
        Scanner in = new Scanner();
        int n = in.nextInt();
        int m = in.nextInt();
        boolean[] check = new boolean[n];
        Arrays.fill(check, true);
        HashSet<Integer> cur = new HashSet();
        HashSet<Integer> pre = new HashSet();
        for (int i = 0; i < m; i++) {
            char op = in.next().charAt(0);
            int num = in.nextInt() - 1;

            if (op == '+') {
                if (cur.size() > 0 || (pre.size() > 0 && !pre.contains(num))) {
                    check[num] = false;
                }
                cur.add(num);
                if (pre.contains(num)) {
                    pre.remove(num);
                }
                for(int v : pre){
                    check[v] = false;
                }
            } else {
                if (cur.contains(num)) {
                    if (cur.size() > 1) {
                        check[num] = false;
                    }
                    cur.remove(num);
                    pre.add(num);
                } else {
                    if (cur.size() > 0) {
                        check[num] = false;
                    }
                    for (int v : cur) {
                        check[v] = false;
                    }
                    for (int v : pre) {
                        check[v] = false;
                    }
                    pre.add(num);
                }
            }
        }
        int c = 0;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < n; i++) {
            if (check[i]) {
                c++;
                builder.append(i + 1).append(" ");
            }
        }
        out.println(c);
        out.println(builder.toString());
        out.close();
    }

    public static int[] KMP(String val) {
        int i = 0;
        int j = -1;
        int[] result = new int[val.length() + 1];
        result[0] = -1;
        while (i < val.length()) {
            while (j >= 0 && val.charAt(j) != val.charAt(i)) {
                j = result[j];
            }
            j++;
            i++;
            result[i] = j;
        }
        return result;

    }

    public static boolean nextPer(int[] data) {
        int i = data.length - 1;
        while (i > 0 && data[i] < data[i - 1]) {
            i--;
        }
        if (i == 0) {
            return false;
        }
        int j = data.length - 1;
        while (data[j] < data[i - 1]) {
            j--;
        }
        int temp = data[i - 1];
        data[i - 1] = data[j];
        data[j] = temp;
        Arrays.sort(data, i, data.length);
        return true;
    }

    public static int digit(long n) {
        int result = 0;
        while (n > 0) {
            n /= 10;
            result++;
        }
        return result;
    }

    public static double dist(long a, long b, long x, long y) {
        double val = (b - a) * (b - a) + (x - y) * (x - y);
        val = Math.sqrt(val);
        double other = x * x + a * a;
        other = Math.sqrt(other);
        return val + other;

    }

    public static class Point implements Comparable<Point> {

        int x, y;

        public Point(int start, int end) {
            this.x = start;
            this.y = end;
        }

        @Override
        public int hashCode() {
            int hash = 5;
            hash = 47 * hash + this.x;
            hash = 47 * hash + this.y;
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Point other = (Point) obj;
            if (this.x != other.x) {
                return false;
            }
            if (this.y != other.y) {
                return false;
            }
            return true;
        }

        @Override
        public int compareTo(Point o) {
            return x - o.x;
        }
    }

    public static class FT {

        long[] data;

        FT(int n) {
            data = new long[n];
        }

        public void update(int index, long value) {
            while (index < data.length) {
                data[index] += value;
                index += (index & (-index));
            }
        }

        public long get(int index) {
            long result = 0;
            while (index > 0) {
                result += data[index];
                index -= (index & (-index));
            }
            return result;

        }
    }

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

    public static long pow(long a, long b) {
        if (b == 0) {
            return 1;
        }
        if (b == 1) {
            return a;
        }
        long val = pow(a, b / 2);
        if (b % 2 == 0) {
            return val * val % MOD;
        } else {
            return val * (val * a % MOD) % MOD;

        }
    }

    static class Scanner {

        BufferedReader br;
        StringTokenizer st;

        public Scanner() throws FileNotFoundException {
            // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
            br = new BufferedReader(new InputStreamReader(System.in));
            //  br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
        }

        public String next() {

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

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

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

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

        public String nextLine() {
            st = null;
            try {
                return br.readLine();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }

        public boolean endLine() {
            try {
                String next = br.readLine();
                while (next != null && next.trim().isEmpty()) {
                    next = br.readLine();
                }
                if (next == null) {
                    return true;
                }
                st = new StringTokenizer(next);
                return st.hasMoreTokens();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
}


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

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);
    solve(in,out);
    out.close();
  }

  private static final int MOD = (int)1e9 + 7;

  private static long add(long a, long b) {
	  a += b;
	  if (a >= MOD) {
		  a -= MOD;
	  }
	  return a;
  }

  private static long pow(long a, int b) {
	  long ans = 1;
	  while (b > 0) {
		  if ((b % 2) > 0) {
			  ans = ans * a %MOD;
		  }
		  a = a * a % MOD;
		  b >>= 1;
	  }
	  return ans;
  }

  private static void solve(InputReader in, PrintWriter out) {
	  int n = in.nextInt();
	  long m = in.nextLong();
	  long dp[] = new long[n + 1];
	  dp[0] = 1;
	  for (int i = 1; i <= n; i++) {
		  dp[i] = 0;
		  for (int j = 0; j < i; j++) {
			  dp[i] = add(dp[i], dp[j] * m % MOD * pow(m - 1, i - j - 1) % MOD);
		  }
	  }
	  long ans = 0;
	  for (int i = 0; i <= n; i++) {
		  ans = add(ans, dp[i] * pow(m, n - i) % MOD);
	  }
	  out.print(ans);
  }

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

  }
}


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

public final class diff_subs
{
    static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	static FastScanner sc=new FastScanner(br);
    static PrintWriter out=new PrintWriter(System.out);
	static Random rnd=new Random();
	static long mod=(long)(1e9+7);
	static long[] fact,inv_fact;
	static int maxn=(int)(1e6+6);

	static long pow(long a,long b)
	{
		long x=1,y=a;

		while(b>0)
		{
			if(b%2==1)
			{
				x=(x*y)%mod;
			}

			y=(y*y)%mod;b=b/2;
		}

		return x;
	}

	static void build()
	{
		fact=new long[maxn];inv_fact=new long[maxn];fact[0]=1;

		for(int i=1;i<maxn;i++)
		{
			fact[i]=(fact[i-1]*i)%mod;
		}

		inv_fact[maxn-1]=pow(fact[maxn-1],mod-2);

		for(int i=maxn-2;i>=0;i--)
		{
			inv_fact[i]=(inv_fact[i+1]*(i+1))%mod;
		}
	}

	static long C(int n,int r)
	{
		long val1=fact[n],val2=inv_fact[r],val3=inv_fact[n-r];

		long mul=(val2*val3)%mod;

		return (val1*mul)%mod;
	}

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

		int n=sc.nextInt(),m=sc.nextInt();

		long curr=m,res=0,xx=pow(m-1,n-1),zz=pow(m-1,mod-2);

		for(int s=1;s<=n;s++)
		{
			// for all i+j=s...

			long now=(curr*xx)%mod;

			// sum of all binomial cofficients, such that i+j=s, i>=1,j>=0...

			long sum=C(n,s-1);

			long mul=(now*sum)%mod;

			res=(res+mul)%mod;

			curr=(curr*m)%mod;

			xx=(xx*zz)%mod;
		}

		res=(res+pow(m,n))%mod;

		out.println(res);out.close();
    }
}
class FastScanner
{
    BufferedReader in;
    StringTokenizer st;

    public FastScanner(BufferedReader in) {
        this.in = in;
    }

    public String nextToken() throws Exception {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }

	public String next() throws Exception {
		return nextToken().toString();
	}

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

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

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


import java.util.Scanner;

// https://codeforces.com/contest/1384/problem/C
public class C {
	public static final Scanner INPUT = new Scanner(System.in);

	public static void main(String[] args) {
		int t = Integer.parseInt(INPUT.nextLine());
		while (t > 0) {
			t--;
			int n = Integer.parseInt(INPUT.nextLine());
			String a = INPUT.nextLine().trim();
			String b = INPUT.nextLine().trim();
			// System.out.println("n = " + n);
			// System.out.println("a = " + a);
			// System.out.println("b = " + b);
			int[][] c = trans2matrix(a, b, n);
			while (reduce(c)) {
			}
			System.out.println(counter(c));
		}
	}

	private static final int N_SIZE = 20;

	private static boolean reduce(int[][] c) {
		if (c == null) {
			return false;
		}
		boolean canReduce = false;
		for (int i = 0; i < N_SIZE; i++) {
			int last = -1;
			for (int j = i + 1; j < N_SIZE; j++) {
				if (c[i][j] > 0) {
					if (last == -1) {
						last = j;
					} else {
						c[i][last] += c[i][j];
						c[last][j] += c[i][j];
						c[i][j] = 0;
						canReduce = true;
					}
				}
			}
		}
		return canReduce;
	}

	private static int counter(int[][] c) {
		if (c == null) {
			return -1;
		}
		int counter = 0;
		for (int i = 0; i < N_SIZE; i++) {
			for (int j = i + 1; j < N_SIZE; j++) {
				if (c[i][j] > 0) {
					counter++;
				}
			}
		}
		return counter;
	}

	private static int[][] trans2matrix(String a, String b, int n) {
		if (a == null || b == null) {
			return null;
		}
		if ((a.length() != n) || (b.length() != n)) {
			return null;
		}
		int[][] c = new int[N_SIZE][N_SIZE];
		for (int id = 0; id < n; id++) {
			int cA = a.charAt(id) - 'a';
			int cB = b.charAt(id) - 'a';
			if (cA > cB) {
				return null;
			}
			if (cA < cB) {
				c[cA][cB]++;
			}
		}
		return c;
	}
}
/*
 * 5 3 aab bcc 4 cabc abcb 3 abc tsr 4 aabd cccd 5 abcbd bcdda
 */


import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

// https://codeforces.com/contest/1384/problem/E
public class E {
	public static final Scanner IN = new Scanner(System.in);
	public static final int N_SIZE = 20;
	public static final int NN_SIZE = N_SIZE * 2;
	public static int[][] MC = new int[N_SIZE][N_SIZE];
	public static int[][] MMC = new int[NN_SIZE][NN_SIZE];
	public static int[] degs = new int[N_SIZE];
	public static int[] ddegs = new int[NN_SIZE];
	public static int[] ffas = new int[NN_SIZE];
	// coding continue

	public static void main(String[] args) {
		int nTest = Integer.parseInt(IN.nextLine());

		while (nTest > 0) {
			nTest--;
			int n = Integer.parseInt(IN.nextLine());
			String a = IN.nextLine().trim();
			String b = IN.nextLine().trim();
			trans2matrix(a, b, n);
			int solution = NN_SIZE;
			for (int state = 0; state < (1 << N_SIZE); state++) {
				solution = Math.min(solution, cal(state));
			}
			System.out.println(solution);
		}
	}

	private static int cal(int state) {
		doubleMatrix(state);
		for (int id = 0; id < NN_SIZE; id++) {
			ffas[id] = id;
		}
		int nComponent = NN_SIZE;
		Queue<Integer> queue = new LinkedList<Integer>();
		for (int id = 0; id < NN_SIZE; id++) {
			if (ddegs[id] == 0) {
				queue.add(id);
			}
		}
		while (queue.size() > 0) {
			int u = queue.poll();
			for (int v = 0; v < NN_SIZE; v++) {
				if (MMC[u][v] > 0) {
					ddegs[v] -= MMC[u][v];
					if (ddegs[v] == 0) {
						queue.add(v);
					}
					int faU = findFa(ffas, u);
					int faV = findFa(ffas, v);
					if (faU != faV) {
						ffas[faV] = faU;
						nComponent--;
					}
				}
			}
		}
		for (int id = 0; id < NN_SIZE; id++) {
			if (ddegs[id] > 0) {
				return NN_SIZE;
			}
		}
		return NN_SIZE - nComponent;
	}

	private static int findFa(int[] fas, int u) {
		if (fas[u] == u) {
			return u;
		}
		fas[u] = findFa(fas, fas[u]);
		return fas[u];
	}

	private static void doubleMatrix(int state) {
		for (int idi = 0; idi < NN_SIZE; idi++) {
			ddegs[idi] = 0;
			for (int idj = 0; idj < NN_SIZE; idj++) {
				MMC[idi][idj] = 0;
			}
		}
		for (int idi = 0; idi < N_SIZE; idi++) {
			for (int idj = 0; idj < N_SIZE; idj++) {
				if (MC[idi][idj] > 0) {
					if ((state & (1 << idj)) > 0) {
						MMC[idi][idj + N_SIZE] = MC[idi][idj];
						ddegs[idj + N_SIZE] += MC[idi][idj];
					} else {
						MMC[idi][idj] = MC[idi][idj];
						ddegs[idj] += MC[idi][idj];
					}
				}
			}
		}
	}

	private static void trans2matrix(String a, String b, int n) {
		for (int idi = 0; idi < N_SIZE; idi++) {
			degs[idi] = 0;
			for (int idj = 0; idj < N_SIZE; idj++) {
				MC[idi][idj] = 0;
			}
		}
		for (int id = 0; id < n; id++) {
			int valueA = a.charAt(id) - 'a';
			int valueB = b.charAt(id) - 'a';
			if (valueA != valueB) {
				MC[valueA][valueB]++;
				degs[valueA]++;
				degs[valueB]++;
			}
		}
	}
}


/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
import java.util.*;
public class Main
{
	public static void main(String[] args) {
	//	System.out.println("Hello World");
	Scanner sc=new Scanner(System.in);
	int n=sc.nextInt();
	int c=0,i;
	String s=sc.next();
	int n1=n/11;
	char a[]=s.toCharArray();
	for(i=0;i<a.length;i++)
	{
	    if(a[i]=='8')
	    c++;
	}
	if(c>=n1)
System.out.println(n1);
else if(c<n1)
{
 System.out.println(c);
}
else if(c==0)
{
    System.out.println(c);
}
	}
}


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

public class C {
	static StringBuilder st = new StringBuilder();
	static int n, m;
	static int memoAns[][][];
	static HashMap<Long, Integer> map;

	static final int MOD = 998244353;

	static int add(int a, int b) {
		return (a + b) % MOD;
	}

	static int dpAns(int idx, int lst, int k) {

		if (n == idx && k == 0)
			return 1;

		if (idx == n || k < 0)
			return 0;

		if(memoAns[idx][lst][k] != -1)
			return memoAns[idx][lst][k] ;

		int ans = dpAns(idx + 1, lst, k);

		for (int i = 0; i < m; i++)
			if (i != lst)
				ans = add(ans, dpAns(idx + 1, i, k - 1));

		return memoAns[idx][lst][k] = ans;

	}

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		n = sc.nextInt();
		m = sc.nextInt();
		int k = sc.nextInt();

		map = new HashMap<>();

		memoAns = new int [n][m][k+1];
		for(int i = 0 ;i < n ;i++)
			for(int j = 0 ;j < m ;j++)
				Arrays.fill(memoAns[i][j], -1);

		int ans = 0;
		for (int i = 0; i < m; i++)
			ans = add(ans, dpAns(1, i, k));

		out.println(ans);

		out.flush();
		out.close();

	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s) {
			br = new BufferedReader(new InputStreamReader(s));
		}

		public String next() throws Exception {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

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

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

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

	static void shuffle(long[] a) {
		int n = a.length;
		for (int i = 0; i < n; i++) {
			int r = i + (int) (Math.random() * (n - i));
			long tmp = a[i];
			a[i] = a[r];
			a[r] = tmp;
		}
	}

	private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;

	private static void tr(Object... o) {
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}

}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
/*
 * Java Input / Output Class using Buffered/ Input Straem
 * Created by @neelbhallabos
 * File Created at: Mar 25, 2019
 */
public class BrickEnumeration {
	public static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
	public static StringTokenizer st;
	public static PrintWriter pw = new PrintWriter(System.out);
	final static boolean debugmode = true;
	public static int k = 7; // for 10^9 + k mods.
	public static long STMOD = 1000000000 + k; // 10^9 + k

	public static void main(String[] args) throws IOException {
		int nbricks = getInt();
		int paintbuckets = getInt();
		int numtransitions = getInt();
		long[][][] dp = new long[nbricks][numtransitions + 1][paintbuckets+1];
		dp[0][0][0] = paintbuckets; // the first brick will have 0 transitions
		for(int cbrick = 1; cbrick < nbricks;cbrick++) {
			// handle the no transition case prior.
			dp[cbrick][0][0] = dp[cbrick-1][0][0];
			for(int ctransition = 1; ctransition < numtransitions + 1;ctransition++) {

				for(int paintused = 1; paintused < paintbuckets + 1;paintused++) {
					dp[cbrick][ctransition][paintused] = dp[cbrick-1][ctransition][paintused];
					dp[cbrick][ctransition][paintused] %= 998244353;
					dp[cbrick][ctransition][paintused] += dp[cbrick-1][ctransition -1][paintused] * (paintused);
					dp[cbrick][ctransition][paintused] %= 998244353;
					//System.out.println("product: "+paintused + " "+(paintbuckets-paintused-1));
					dp[cbrick][ctransition][paintused] += dp[cbrick-1][ctransition -1][paintused-1]*(paintbuckets-paintused);
					dp[cbrick][ctransition][paintused] %= 998244353;
				}
			}
		}
		long csum = 0;
		for( long f : dp[dp.length-1][numtransitions]) {
			//System.out.println(f);
			csum = (csum + f)%998244353;
		}
		submit(csum,true);
	}
	public static int nchoosekmod(int n, int k, int mod) {
		//(n!)/ (n-k)! k!
		int res = 1;

        // Since C(n, k) = C(n, n-k)
        if ( k > n - k )
            k = n - k;

        // Calculate value of [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
        for (int i = 0; i < k; ++i)
        {
        res *= (n - i);
        res /= (i + 1);
        res %= mod;

        }

        return res;

	}
	public static void setInputFile(String fn) throws IOException {
		sc = new BufferedReader(new FileReader(fn));
	}

	public static void setOutputFile(String fn) throws IOException {
		pw = new PrintWriter(new BufferedWriter(new FileWriter(fn)));
	}

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

	public static double log(int k, int v) {
		return Math.log(k) / Math.log(v);
	}

	public static long longpower(int a, int b) {
		long[] vals = new long[(int) (log(b, 2) + 2)];
		vals[0] = a;
		vals[1] = a * a;
		for (int i = 1; i < vals.length; i++) {
			vals[i] = vals[i - 1] * vals[i - 1];
		}
		long ans = 1;
		int cindex = 0;
		while (b != 0) {
			if (b % 2 == 1) {
				ans *= vals[cindex];
			}
			cindex += 1;
			b /= 2;
		}
		return ans;

	}

	public static void debug(String toPrint) {
		if (!debugmode) {
			return;
		}
		pw.println("[DEBUG]: " + toPrint);
	}

	public static void submit(int[] k, boolean close) {
		pw.println(Arrays.toString(k));
		if (close) {
			pw.close();
		}
	}

	public static void submit(int p, boolean close) {
		pw.println(Integer.toString(p));
		if (close) {
			pw.close();
		}
	}

	public static void submit(String k, boolean close) {
		pw.println(k);
		if (close) {
			pw.close();
		}
	}

	public static void submit(double u, boolean close) {
		pw.println(Double.toString(u));
		if (close) {
			pw.close();
		}
	}

	public static void submit(long lng, boolean close) {
		pw.println(Long.toString(lng));
		if (close) {
			pw.close();
		}

	}

	public static void submit() {
		pw.close();
	}

	public static int getInt() throws IOException {
		if (st != null && st.hasMoreTokens()) {
			return Integer.parseInt(st.nextToken());
		}
		st = new StringTokenizer(sc.readLine());
		return Integer.parseInt(st.nextToken());
	}

	public static long getLong() throws IOException {
		if (st != null && st.hasMoreTokens()) {
			return Long.parseLong(st.nextToken());
		}
		st = new StringTokenizer(sc.readLine());
		return Long.parseLong(st.nextToken());
	}

	public static double getDouble() throws IOException {
		if (st != null && st.hasMoreTokens()) {
			return Double.parseDouble(st.nextToken());
		}
		st = new StringTokenizer(sc.readLine());
		return Double.parseDouble(st.nextToken());
	}

	public static String getString() throws IOException {
		if (st != null && st.hasMoreTokens()) {
			return st.nextToken();
		}
		st = new StringTokenizer(sc.readLine());
		return st.nextToken();
	}

	public static String getLine() throws IOException {
		return sc.readLine();
	}

	public static int[][] readMatrix(int lines, int cols) throws IOException {
		int[][] matrr = new int[lines][cols];
		for (int i = 0; i < lines; i++) {
			for (int j = 0; j < cols; j++) {
				matrr[i][j] = getInt();
			}
		}
		return matrr;
	}

	public static int[] readArray(int lines) throws IOException {
		int[] ar = new int[lines];
		for (int i = 0; i < lines; i++)
			ar[i] = getInt();
		return ar;
	}

}
/*

public class BrickEnumeration {

}

*/


import java.util.*;
public class codeforces{
	public static void main(String[] args){
		Scanner s=new Scanner(System.in);
		long n=s.nextLong();
		long k=s.nextLong();
		if(n==1||n+(n-1)<k) System.out.println("0");
		else{
			if(k<=n+1) System.out.println((k-1)/2);
			else System.out.println(n-(k+22/2+1);
		}
	}
}


import java.util.Scanner;

public class File1{
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int m = in.nextInt();
		int s= in.nextInt();
		int x = (n-1)/s;
		int y = (m-1)/s;
		long ans = (x+1);
		ans*=(y+1);
		if(ans==1){
			ans = n;
			ans*=m;
		}
		System.out.println(ans);
	}
}


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

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader r= new BufferedReader(new InputStreamReader(System.in));

		String[] input = r.readLine().split("[ ]+");
		int width = Integer.parseInt(input[0]);
		int height = Integer.parseInt(input[1]);
		int jump = Integer.parseInt(input[2]);

		int maximum = 1;
		int counter=0;

		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				boolean[][] grid= new boolean[width][height];
				int temp = calc(grid,i,j,jump);
				if(temp>maximum){
					maximum = temp;
					counter=1;
				}else if(temp == maximum){
					counter++;
				}
			}
		}

		System.out.println(counter);
	}

	private static int calc(boolean[][] grid, int i, int j,int jump) {
		if(grid[i][j]==true)return 0;

		grid[i][j]=true;
		int down = i+jump<grid.length?calc(grid,i+jump,j,jump):0;
		int up = i-jump>=0?calc(grid,i-jump,j,jump):0;
		int right = j+jump<grid[0].length?calc(grid,i,j+jump,jump):0;
		int left = j-jump>=0?calc(grid,i,j-jump,jump):0;

		return 1+down+up+right+left;
	}
}


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

public class Main {
	  public static void main(String[] args) {
	        InputStream inputStream = System.in;
	        OutputStream outputStream = System.out;
	        InputReader in = new InputReader(inputStream);
	            try (PrintWriter out = new PrintWriter(outputStream)) {
	            	TaskC solver = new TaskC();
	                solver.solve(in, out);
	            }
	    }
}
class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;

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

    public String nextLine(){
    	String fullLine=null;
    	while (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
              fullLine=reader.readLine();
            } catch (IOException e) {
              throw new RuntimeException(e);
            }
            return fullLine;
          }
          return fullLine;
    }
	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 long nextLong() {
	      return Long.parseLong(next());
	    }
    public int nextInt() {
      return Integer.parseInt(next());
    }
  }
class TaskC {
	void solve(InputReader in,PrintWriter out){
		long w=in.nextInt();
		long m=in.nextInt();
		int count=1;
		long ww=w;
		ArrayList<Integer> l1=new ArrayList<Integer>();
		l1.add(1);
		long tmp1=1,tmp2=1;
		long up=2;
		while((Math.pow(w, up)*(w*w-w-1)+1)/(w-1)<=m)
			up++;
		up+=2;
		//System.out.println(up);
		if(m==1){
			out.println("YES");
			return;
		}
		while(count<=up){
			long qwerty=l1.size();
			for(int i=0;i<qwerty;i++){
				tmp1=ww+l1.get(i);
				tmp2=ww-l1.get(i);
				//System.out.println(ww+" "+tmp1+" "+tmp2);
				if(tmp1==m || tmp2==m){
					out.println("YES");
					return;
				}
				l1.add((int)tmp1);
				l1.add((int)tmp2);
			}
			//System.out.println(count+"<-");
			ww*=w;
			count++;
		}
		out.println("NO");
	}
}


package codeforces;

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

public class AA {
	public static void main(String[]args) throws IOException{
	BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	String x = bf.readLine();
	String [] xx = x.split(" ");
	int n = Integer.parseInt(xx[0]);
	int k = Integer.parseInt(xx[1]);
    String y = bf.readLine();
    String [] yy = y.split(" ");
    int [] put = new int[n];
    for(int i =0; i<n; i++){
    	put[i]= Integer.parseInt(yy[i]);
    }
    if(n==k){
    	System.out.println(0);
    	}
    else{
    	if(n==2 && k==1){
    		if(put[0]!=put[1]) System.out.println("1");
    		else{
    			System.out.println("0");
    		}
    	}

    else{
    int counter=0;
    int moves = n/k;

    for(int i =0; i<k; i++){
    int two =0;
    int one =0;
    int counter2 =0;
    for(int j =i; j>=(k*counter2)-1+i && j<n;j=j+k){

    	if(put[j]==1){
    		one++;
    	}
    	else two++;
    	counter2++;
    	}

   if(two==one){
	   counter=counter+one;
   }
   if(two>one){

    	if(one!= 0){

    		counter=counter+one;
    	}
    }
    if(one>two){
    	if(two!=0){
    		counter=counter+two;
    	}
    }
    }
    System.out.println(counter);

	}
}}
}


import java.util.*;
public class GenerateLogin
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        String name = in.next();
        String[] nameSplit = name.split(" ");

        String login = "";
        login += nameSplit[0].charAt(0);
        int i = 1;

        while(i < nameSplit[0].length())
        {
            if(nameSplit[0].charAt(i) < nameSplit[1].charAt(0))
            {
                login += nameSplit[0].charAt(i);
                i++;
            }
            else
            {
                break;
            }
        }

        login += nameSplit[1].charAt(0);
        System.out.println(login);

    }
}


import java.util.*;
import java.io.*;
public class Test{
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		String first = ns();
		String last  = ns();
		String ans = ""+first.charAt(0);
		for(int i = 1 ; i<first.length();i++)
		{
			if(first.charAt(i)<last.charAt(0))
			{
				ans+=""+first.charAt(i);
			}
			else
				break;
		}
		out.print(ans+""+last.charAt(0));
	}
	void run() throws Exception{
		is = oj ? System.in: new ByteArrayInputStream(INPUT.getBytes());
		//is = new ByteArrayInputStream(System.in);
		out = new PrintWriter(System.out);
		solve();
		out.flush();
	}
	public static void main(String[] args)throws Exception {
		new Test().run();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") == null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


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

public class CF139D {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		char[] cc = br.readLine().toCharArray();
		int[] aa = new int[10];
		for (int i = 0; i < cc.length; i++) {
			int d = cc[i] - '0';
			aa[d]++;
		}
		int[] a0 = new int[10];
		int[] a1 = new int[10];
		int[] a2 = new int[10];
		int max = 0, z_ = 0, x_ = 0;
		for (int z = 0; z <= aa[0]; z++) {
			for (int d = 0; d <= 9; d++)
				a0[d] = aa[d];
			a0[0] -= z;
			for (int x = 1; x <= 5; x++)
				if (a0[x] > 0 && a0[10 - x] > 0) {
					for (int d = 0; d <= 9; d++)
						a1[d] = a2[d] = a0[d];
					a1[x]--;
					a2[10 - x]--;
					int cnt = 0;
					for (int d = 0; d <= 9; d++)
						cnt += Math.min(a1[d], a2[9 - d]);
					if (max < cnt + 1 + z) {
						max = cnt + 1 + z;
						z_ = z;
						x_ = x;
					}
				}
		}
		StringBuilder s1 = new StringBuilder();
		StringBuilder s2 = new StringBuilder();
		for (int d = 0; d <= 9; d++)
			a0[d] = aa[d];
		a0[0] -= z_;
		for (int i = 0; i < z_; i++) {
			s1.append('0');
			s2.append('0');
		}
		for (int d = 0; d <= 9; d++)
			a1[d] = a2[d] = a0[d];
		a1[x_]--;
		a2[10 - x_]--;
		s1.append(x_);
		s2.append(10 - x_);
		for (int d = 0; d <= 9; d++)
			while (a1[d] > 0 && a2[9 - d] > 0) {
				a1[d]--;
				a2[9 - d]--;
				s1.append(d);
				s2.append(9 - d);
			}
		for (int d = 0; d <= 9; d++) {
			for (int i = 0; i < a1[d]; i++)
				s1.append(d);
			for (int i = 0; i < a2[d]; i++)
				s2.append(d);
		}
		System.out.println(s1.reverse());
		System.out.println(s2.reverse());
	}
}