/**
 * DA-IICT
 * Author : Savaliya Sagar
 */
import java.io.*;
import java.math.*;
import java.util.*;

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

public class B887
{
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		int p[][] = null;
		if(n==1) {
			p = new int[1][n];
			p[0][0] = 0;
		}else if(n==2) {
			p = new int[2][n];
			p[0][0] = 0;
			p[0][1] = 1;
			p[0][0] = 1;
			p[0][1] = 0;
		}else if(n==3) {
			p = new int[12][];
			p[0] = new int[] {0,1,2};
			p[1] = new int[] {1,0,2};
			p[2] = new int[] {0,2,1};
			p[3] = new int[] {2,1,0};
			p[4] = new int[] {2,0,1};
			p[5] = new int[] {1,2,0};
			p[6] = new int[] {0,1};
			p[7] = new int[] {0,2};
			p[8] = new int[] {1,0};
			p[9] = new int[] {1,2};
			p[10] = new int[] {2,0};
			p[11] = new int[] {2,1};
		}
		HashSet<Integer> h[] = new HashSet[n];
		for (int i = 0; i < n; i++)
		{
			h[i] = new HashSet<>();
			for (int j = 0; j < 6; j++)
			{
				h[i].add(ni());
			}
		}
		if(n==1) {
			int x = 1;
			for(x=1;x<=9;) {
				if(h[0].contains(x))
					x++;
				else
					break;
			}
			out.println(x-1);
		}else if(n==2) {
			int x = 1;
			for(x=1;x<=9;) {
				if(h[0].contains(x) || h[1].contains(x))
					x++;
				else
					break;
			}
			if(x!=10)
			{
				out.println(x-1);
				return;
			}
			for(;x<=99;) {
				int f = 0;
				for(int i=0;i<2;i++) {
					if(h[p[i][0]].contains(x/10) && h[p[i][1]].contains(x%10))
						f = 1;
				}
				if(f==1)
					x++;
				else
					break;
			}
			out.println(x-1);
		}else {
			int x = 1;
			for(x=1;x<=9;) {
				if(h[0].contains(x) || h[1].contains(x) || h[2].contains(x))
					x++;
				else
					break;
			}
			if(x!=10)
			{
				out.println(x-1);
				return;
			}
			for(;x<=99;) {
				int f = 0;
				for(int i=6;i<=11;i++) {
					if(h[p[i][0]].contains(x/10) && h[p[i][1]].contains(x%10))
						f = 1;
				}
				if(f==1)
					x++;
				else
					break;
			}
			if(x!=100)
			{
				out.println(x-1);
				return;
			}
			for(;x<=999;) {
				int f = 0;
				for(int i=0;i<=6;i++) {
					int a = x/100;
					int b = (x/10)%10;
					int c = x%10;
					if(h[p[i][0]].contains(a) && h[p[i][1]].contains(b) && h[p[i][2]].contains(c))
						f = 1;
				}
				if(f==1)
					x++;
				else
					break;
			}
			out.println(x-1);
		}
	}

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

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		if (!INPUT.isEmpty())
			tr(System.currentTimeMillis() - s + "ms");
	}

	public static void main(String[] args) throws Exception
	{
		new Thread(null, new Runnable()
		{
			public void run()
			{
				try
				{
					new B887().run();
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}, "1", 1 << 26).start();
	}

	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 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 void tr(Object... o)
	{
		System.out.println(Arrays.deepToString(o));
	}
}


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.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.StringTokenizer;

public class Template {

    static class Solver {
        public void solve(InputReader in, PrintWriter out) {
        		int a1 = in.nextInt();
            int counter = 1;
        		ArrayList<Integer> t = new ArrayList<Integer>();

        		for (int i = 0; i < a1 ; i++) {
                for (int j = 0; j < 6 ; j++) {
                		t.add(in.nextInt());

                }
             }

        		if(a1==2) {

	        		for (int i = 0; i < 6; i++) {
	        			for (int j = 0; j < 6; i++) {
		        			t.add((t.get(i)*10)+t.get(j+6));
		        			t.add((t.get(j+6)*10)+t.get(i));
	        			}
	        		}
        		}

        		if(a1==3) {

	        		for (int i = 0; i < 6; i++) {
	        			for (int j = 0; j < 6; j++) {

	        				t.add((t.get(i)*10)+t.get(j+6));
		        			t.add((t.get(j+6)*10)+t.get(i));
	        			}
	        		}
	        		for (int i = 0; i < 6; i++) {
	        			for (int j = 0; j < 6; j++) {

	        				t.add((t.get(i+6)*10)+t.get(j+12));
	            			t.add((t.get(j+12)*10)+t.get(i+6));

	        			}
	        		}
	        		for (int i = 0; i < 6; i++) {
	        			for (int j = 0; j < 6; j++) {

	        				t.add((t.get(i)*10)+t.get(j+12));
	            			t.add((t.get(j+12)*10)+t.get(i));

	        			}
	        		}

        		}

        		Collections.sort(t);

        		while(counter<=100 && t.contains(counter) ) {
        			counter++;
			}

        		if(!t.contains(1)) {
        			counter = 0;
        		}else{
        			counter--;
        		}

        		out.print(counter);

        }
    }

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

    }

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;

public class Hello {
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

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

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return str;
        }

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

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

        long nextLong() {

            return Long.parseLong(next());
        }

        BigInteger nextBigIntger() {
            BigInteger bb = new BigInteger(next());
            return bb;
        }
    }
    Node root;
    public static void main(String args[]) {
        FastReader sc= new FastReader();
        int n =sc.nextInt(), arr[] = new int[10];
        int xx = n;
        while (xx-->0){
            for (int i=0;i<6;i++){ arr[sc.nextInt()]++; }
        }

       /* for (int i=0;i<10;i++)
            System.out.print(arr[i]+" ");*/
       boolean flag = false;
        for (int i=1;i<10;i++){
            if(arr[i]==0){
                System.out.println(arr[1]==0?0:(i-1));
                flag = true;
                break;
            }
        }
        int yy;
        if (!flag){
            if(arr[0]>=1){
                int min = Integer.MAX_VALUE,ind =0;
                for (int ii=1;ii<10;ii++){
                    if(arr[ii]<min){
                        min = arr[ii];
                        ind = ii;
                    }
                }
                yy=ind-1;
                System.out.println(ind+""+yy);
            }

        }
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

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

    static class TaskB {
        static int a;
        static int n;

        public void solve(int testNumber, FastReader in, PrintWriter out) {
            n = in.nextInt();
            int i;
            a = new int[n][6];
            for (i = 0; i < n; i++) a[i] = in.nextIntArray(6);
            for (i = 1; ; i++) {
                if (!play(i, false, false, false)) break;
            }
            out.println(i - 1);
        }

        static boolean f(int i, int x) {
            for (int j = 0; j < 6; j++) if (a[i][j] == x) return true;
            return false;
        }

        static boolean play(int x, boolean p, boolean q, boolean r) {
            if (x == 0) return true;
            if (!p && f(0, x % 10) && play(x / 10, true, q, r)) return true;
            if (n >= 2 && !q && f(1, x % 10) && play(x / 10, p, true, r)) return true;
            if (n == 3 && !r && f(2, x % 10) && play(x / 10, p, q, true)) return true;
            return false;
        }

    }

    static class FastReader {
        private InputStream stream;
        private byte[] buf = new byte[8192];
        private int curChar;
        private int pnumChars;
        private FastReader.SpaceCharFilter filter;

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

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

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

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

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

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

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

        }

    }
}


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

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

@SuppressWarnings("unused")
public class D {

	private final static boolean autoflush = false;

	private static final int MOD = (int) 1e9 + 7;
	private static BigInteger BMOD = valueOf(MOD);
	private static final double eps = 1e-9;
	private static final int INF = (int) 1e9;
	private static final Error NO = new Error("NO");

	public D () {
		N = sc.nextInt();
		M = sc.nextInt();

		int X = sc.nextInt();
		int Y = sc.nextInt();

		int [] T = dir(sc.next());

		A = new int [N]; B = new int [N];
		C = new int [M]; D = new int [M];

		Z = 2 * (N/2 + M/2); int P = (X+Y) % 2;
		if (N % 2 == 1 && P == 0) ++Z;
		if (N % 2 == 1 && P == (1 + M) % 2) ++Z;
		if (M % 2 == 1 && P == 0) ++Z;
		if (M % 2 == 1 && P == (1 + N) % 2) ++Z;

		long res = 1;
		for (;;) {
			if (mark(X, Y))
				break;
			res += next(X, Y, T);
			X = W[0]; Y = W[1];
		}

		exit(res);
	}

	int N, M, Z, K = 0;
	int [] A, B, C, D, W = new int [2];

	int next(int X, int Y, int [] T) {
		if (X == 1) T[0] = 1;
		if (X == N) T[0] = -1;
		if (Y == 1) T[1] = 1;
		if (Y == M) T[1] = -1;

		int t = INF, dx = T[0], dy = T[1];
		if (dx ==  1) t = min(t, N - X);
		if (dx == -1) t = min(t, X - 1);
		if (dy ==  1) t = min(t, M - Y);
		if (dy == -1) t = min(t, Y - 1);

		X += t * dx; Y += t * dy;
		W[0] = X; W[1] = Y;
		return t;
	}

	void set(int [] T, int dx, int dy) {
		T[0] = dx; T[1] = dy;
	}

	boolean mark(int X, int Y) {
		boolean res = false;
		if (Y == 1)
			res = res || inc(A, X);
		if (Y == M)
			res = res || inc(B, X);
		if (X == 1)
			res = res || inc(C, Y);
		if (X == N)
			res = res || inc(D, Y);
		return res;
	}

	boolean inc(int [] A, int X) {
		if (A[X-1] == 0) ++K; ++A[X-1];
		if (A[X-1] == 3)
			exit(-1);
		return K == Z;
	}

	int [] dir (String D) {
		String [] S = { "UL", "UR", "DL", "DR" };
		int [][] T = { { -1, -1 }, { -1, 1 }, { 1, -1 }, { 1, 1 }};
		for (int i : rep(4))
			if (D.equals(S[i]))
				return T[i];
		throw new Error();
	}

	////////////////////////////////////////////////////////////////////////////////////
	private static int [] rep(int N) { return rep(0, N); }
	private static int [] rep(int S, int T) { int [] res = new int [max(T-S, 0)]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
	private static int [] req(int S, int T) { return rep(S, T+1); }
	private static int [] sep(int N) { return sep(0, N); }
	private static int [] sep(int S, int T) { int [] res = new int [max(T-S, 0)]; for (int i = S; i < T; ++i) res[T-1-i] = i; return res; }
	private static int [] seq(int S, int T) { return sep(S, T+1); }
	private static int [] ccw (int [] D) { return new int [] { -D[1], D[0] }; }
	private static int [] cw (int [] D) { return new int [] { D[1], -D[0] }; }
	private static <T> T ceiling(SortedSet<T> S, T x) { // Java 1.5 and below
		SortedSet<T> T = S.tailSet(x);
		return T.isEmpty() ? null : T.first();
	}
	private static <T> T floor(SortedSet<T> S, T x) { // Java 1.5 and below
		if (S.contains(x))
			return x;
		else {
			SortedSet<T> T = S.headSet(x);
			return T.isEmpty() ? null : T.last();
		}
	}
	private static int [] digits(long N, int B, int sz) {
		int [] res = new int [sz];
		for (int i : sep(sz))
			if (N > 0) {
				res[i] = (int)(N % B);
				N /= B;
			}
		return res;
	}
	private static int digitSum(long N) {
		int res = 0;
		for (; N > 0; res += N % 10, N /= 10);
		return res;
	}
	private static <T extends Comparable<T>> T max(T x, T y) { return x.compareTo(y) > 0 ? x : y; }
	private static long mod(long x) { return mod(x, MOD); }
	private static long mod(long x, long mod) { return ((x % mod) + mod) % mod; }
	private static long modPow(long b, long e) { return valueOf(b).modPow(valueOf(e), BMOD).longValue(); }
	private static long pow(long b, long e) { return round(Math.pow(b, e)); }
	private static String reverse (String S) { return new StringBuilder(S).reverse().toString(); }
	private static char [][] toCharArrays(String [] S) {
		int N = S.length;
		char [][] res = new char [N][];
		for (int i : rep(N))
			res[i] = S[i].toCharArray();
		return res;
	}
	////////////////////////////////////////////////////////////////////////////////////
	private final static MyScanner sc = new MyScanner();
	private static class MyScanner {
		private String next() {
			newLine();
			return line[index++];
		}
		private char nextChar() {
			return next().charAt(0);
		}
		private int nextInt() {
			return Integer.parseInt(next());
		}
		private long nextLong() {
			return Long.parseLong(next());
		}
		private double nextDouble() {
			return Double.parseDouble(next());
		}
		private String nextLine() {
			line = null;
			return readLine();
		}
		private String [] nextStrings() {
			line = null;
			return readLine().split(" ");
		}
		private char [] nextChars() {
			return next ().toCharArray ();
		}
		private Integer [] nextInts() {
			String [] L = nextStrings();
			Integer [] res = new Integer [L.length];
			for (int i : rep(L.length))
				res[i] = Integer.parseInt(L[i]);
			return res;
		}
		private Long [] nextLongs() {
			String [] L = nextStrings();
			Long [] res = new Long [L.length];
			for (int i : rep(L.length))
				res[i] = Long.parseLong(L[i]);
			return res;
		}
		private Double [] nextDoubles() {
			String [] L = nextStrings();
			Double [] res = new Double [L.length];
			for (int i : rep(L.length))
				res[i] = Double.parseDouble(L[i]);
			return res;
		}
		private String [] next (int N) {
			String [] res = new String [N];
			for (int i : rep(N))
				res[i] = next();
			return res;
		}
		private Integer [] nextInt (int N) {
			Integer [] res = new Integer [N];
			for (int i : rep(N))
				res[i] = nextInt();
			return res;
		}
		private Long [] nextLong (int N) {
			Long [] res = new Long [N];
			for (int i : rep(N))
				res[i] = nextLong();
			return res;
		}
		private Double [] nextDouble (int N) {
			Double [] res = new Double [N];
			for (int i : rep(N))
				res[i] = nextDouble();
			return res;
		}
		private String [][] nextStrings (int N) {
			String [][] res = new String [N][];
			for (int i : rep(N))
				res[i] = nextStrings();
			return res;
		}
		private Integer [][] nextInts (int N) {
			Integer [][] res = new Integer [N][];
			for (int i : rep(N))
				res[i] = nextInts();
			return res;
		}
		private Long [][] nextLongs (int N) {
			Long [][] res = new Long [N][];
			for (int i : rep(N))
				res[i] = nextLongs();
			return res;
		}
		private Double [][] nextDoubles (int N) {
			Double [][] res = new Double [N][];
			for (int i : rep(N))
				res[i] = nextDoubles();
			return res;
		}
		//////////////////////////////////////////////
		private boolean eol() {
			return index == line.length;
		}
		private String readLine() {
			try {
				return r.readLine();
			} catch (Exception e) {
				throw new Error (e);
			}
		}
		private final java.io.BufferedReader r;
		private MyScanner () {
			this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in)));
		}
		private MyScanner (java.io.BufferedReader r) {
			try {
				this.r = r;
				while (!r.ready())
					Thread.sleep(1);
				start();
			} catch (Exception e) {
				throw new Error(e);
			}
		}
		private String [] line;
		private int index;
		private void newLine() {
			if (line == null || eol()) {
				line = readLine().split(" ");
				index = 0;
			}
		}
	}
	private static void print (Object o, Object... a) {
		printDelim(" ", o, a);
	}
	private static void cprint (Object o, Object... a) {
		printDelim("", o, a);
	}
	private static void printDelim (String delim, Object o, Object... a) {
		pw.println(build(delim, o, a));
	}
	private static void exit (Object o, Object... a) {
		print(o, a);
		exit();
	}
	private static void exit() {
		pw.close();
		System.out.flush();
		System.err.println("------------------");
		System.err.println("Time: " + ((millis() - t) / 1000.0));
		System.exit(0);
	}
	private static void NO() {
		throw new Error("NO!");
	}
	////////////////////////////////////////////////////////////////////////////////////
	private static String build (String delim, Object o, Object... a) {
		StringBuilder b = new StringBuilder();
		append(b, o, delim);
		for (Object p : a)
			append(b, p, delim);
		return b.toString().trim();
	}
	private static void append(StringBuilder b, Object o, String delim) {
		if (o.getClass().isArray()) {
			int L = java.lang.reflect.Array.getLength(o);
			for (int i : rep(L))
				append(b, java.lang.reflect.Array.get(o, i), delim);
		} else if (o instanceof Iterable<?>)
			for (Object p : (Iterable<?>)o)
				append(b, p, delim);
		else
			b.append(delim).append(o);
	}
	////////////////////////////////////////////////////////////////////////////////////
	private static void start() {
		t = millis();
	}
	private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out, autoflush);
	private static long t;
	private static long millis() {
		return System.currentTimeMillis();
	}
	private static void statics() {
		abs(0); valueOf(0); asList(new Object [0]); reverseOrder();
	}
	public static void main (String[] args) {
		new D();
		exit();
	}
}


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

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

class AC {
    class Node extends Object{
        int x,y,dx,dy;
        Node() {}
        Node(int x,int y,int dx,int dy)
        {
            this.x = x;
            this.y = y;
            this.dx = dx;
            this.dy = dy;
        }
        @Override public boolean equals (Object cmp)  {
            if(cmp instanceof Node) {
                Node tmp = (Node) cmp;
                return tmp.x == x && tmp.y == y && tmp.dx==dx && tmp.dy == dy ;
            }
            return false;
        }
        @Override public int hashCode() {
            return x*dx * 100000+ y*dy;
        }
    }
    class pair extends Object{
        int x,y;
        pair() {}
        pair(int x,int y)
        {
            this.x = x;
            this.y = y;
        }
        @Override public boolean equals (Object cmp)  {
            if(cmp instanceof pair) {
                pair tmp = (pair) cmp;
                return tmp.x == x && tmp.y == y;
            }
            return false;
        }
        @Override public int hashCode () {
            return x*100000+y;
        }
    }
    int n , m;
    boolean judge(int x,int y) {
        return 1<=x && x <= n && 1 <= y && y <= m;
    }
    Node go(int x,int y,int dx,int dy) {
         int delta;
         if(dx < 0) {
             if(dy < 0)  {
                 delta = Math.min(x-1, y-1);
             } else {
                 delta = Math.min(m-y, x-1);
             }
         } else {
             if(dy < 0) {
                 delta = Math.min(n-x, y-1);
             } else {
                 delta = Math.min(n-x,m-y);
             }
         }
         x += dx * delta;
         y += dy * delta;
         if(x+dx<1 || x+dx>n) dx *= -1;
         if(y+dy<1 || y+dy>m) dy *= -1;
         return new Node(x,y,dx,dy);
    }
    public void solve(InputReader in, PrintWriter out) {
          int x0 , y0;
          String cmd;
          HashMap<Node,Integer> mp = new HashMap<Node,Integer>();
          HashMap<pair,Integer> M = new HashMap<pair,Integer>();
          n = in.nextInt();
          m = in.nextInt();
          x0 = in.nextInt(); y0 = in.nextInt();
          cmd = in.next();
          int tot = n + m - 2;
          int dx , dy;
          if(cmd.charAt(0)=='D') {
              dx = 1;
          } else dx = -1;
          if(cmd.charAt(1)=='R') {
              dy = 1;
          } else dy = -1;
          long long ans = 1;
          pair A = new pair(1,2);
          pair B = new pair(1,2);
          if(x0==1 || x0==n || y0==1 || y0==m){
              M.put(new pair(x0, y0) , 1 );
              tot --;
          }
          while(true) {
              Node tmp = go(x0,y0,dx,dy);
              ans += Math.abs( tmp.x - x0);
              x0 = tmp.x ; y0 = tmp.y ;
              dx = tmp.dx ; dy = tmp.dy;
              pair t = new pair(x0,y0);
              Integer flag = M.get(t);
              if(flag == null) {
                  M.put(t, 1);
                  if(--tot == 0) break;
              }
              if(mp.get(tmp)!=null){
                 ans = -1;
                 break;
              } else {
                  mp.put(tmp, 1);
              }
          }
          out.println(ans);
    }
}
class InputReader {
    BufferedReader reader;
    StringTokenizer tokenizer;
    public InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream));
        tokenizer = null;
    }

    public String next() {
        if (!hasNext())
            throw new RuntimeException();
        return tokenizer.nextToken();
    }

    boolean hasNext() {
        while (tokenizer == null || !tokenizer.hasMoreTokens())
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (Exception e) {
                return false;
            }
        return true;
    }

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

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

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


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

public class D {

	private static final int UL = 0;
	private static final int UR = 1;
	private static final int DL = 2;
	private static final int DR = 3;

	private static class Result {
		public boolean inCorner;
		public long cellsPassed;
		public int steps;
		public int x;
		public int y;
		public int dir;

		public Result(boolean inCorner, long cellsPassed, int steps, int x, int y, int dir) {
			this.inCorner = inCorner;
			this.cellsPassed = cellsPassed;
			this.steps = steps;
			this.x = x;
			this.y = y;
			this.dir = dir;
		}
	}

	private Result go(int n, int m, int x0, int y0, int dir0) {
		long res = 0;
		int x = x0;
		int y = y0;
		int dir = dir0;
		int steps = 0;

		do {

			if (dir == UR) {
				int dx = x - 1;
				int dy = m - y;
				int d = Math.min(dx, dy);
				x -= d;
				y += d;
				res += d;

				if (d != 0) {
					steps++;
				}

				if (dy < dx) {
					dir = UL;
				} else if (dx < dy) {
					dir = DR;
				} else {
					break;
				}
			} else if (dir == UL) {
				int dx = x - 1;
				int dy = y - 1;
				int d = Math.min(dx, dy);
				x -= d;
				y -= d;
				res += d;

				if (d != 0) {
					steps++;
				}

				if (dx < dy) {
					dir = DL;
				} else if (dy < dx) {
					dir = UR;
				} else {
					break;
				}
			} else if (dir == DL) {
				int dx = n - x;
				int dy = y - 1;
				int d = Math.min(dx, dy);
				x += d;
				y -= d;
				res += d;

				if (d != 0) {
					steps++;
				}

				if (dx < dy) {
					dir = UL;
				} else if (dy < dx) {
					dir = DR;
				} else {
					break;
				}
			} else if (dir == DR) {
				int dx = n - x;
				int dy = m - y;
				int d = Math.min(dx, dy);
				x += d;
				y += d;
				res += d;

				if (d != 0) {
					steps++;
				}

				if (dx < dy) {
					dir = UR;
				} else if (dy < dx) {
					dir = DL;
				} else {
					break;
				}
			}
		} while (x != x0 || y != y0 || dir != dir0);

		if (isCorner(x, y, n, m)) {
			return new Result(true, res, steps, x, y, dir);
		} else {
			return new Result(false, res, steps, x, y, dir);
		}
	}

	private boolean isCorner(int x, int y, int n, int m) {
		return (x == 1 && y == 1 || x == 1 && y == m ||
				x == n && y == 1 || x == n && y == m);
	}

	private int reverseDirection(int dir) {
		if (dir == UL) {
			return DR;
		} else if (dir == UR) {
			return DL;
		} else if (dir == DL) {
			return UR;
		} else if (dir == DR) {
			return UL;
		} else {
			throw new RuntimeException();
		}
	}

	private void solve() throws IOException {
		int n = nextInt();
		int m = nextInt();

		int x = nextInt();
		int y = nextInt();

		String s = nextToken();
		int dir = 0;
		if ("UL".equals(s)) {
			dir = UL;
		} else if ("UR".equals(s)) {
			dir = UR;
		} else if ("DL".equals(s)) {
			dir = DL;
		} else {
			dir = DR;
		}

		int stepsNeeded = (n + n + m + m - 4) / 2 - 1;

		Result r1 = go(n, m, x, y, dir);
		if (r1.inCorner) {
			r1.cellsPassed++;

			if (isCorner(x, y, n, m) && (r1.x != x || r1.y != y)) {
				if (r1.steps == stepsNeeded) {
					println(r1.cellsPassed);
				} else {
					println("-1");
				}
			} else {
				Result r2 = go(n, m, r1.x, r1.y, reverseDirection(r1.dir));
				if (r2.steps == stepsNeeded) {
					println(r1.cellsPassed + r2.cellsPassed);
				} else {
					println("-1");
				}
			}
		} else {
			if (r1.steps == stepsNeeded + 1) {
				println(r1.cellsPassed);
			} else {
				println("-1");
			}
		}
	}

	private String nextToken() throws IOException {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			tokenizer = new StringTokenizer(reader.readLine());
		}
		return tokenizer.nextToken();
	}

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

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

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

	private void print(Object o) {
		writer.print(o);
	}

	private void println(Object o) {
		writer.println(o);
	}

	private void printf(String format, Object... o) {
		writer.printf(format, o);
	}

	public static void main(String[] args) {
		long time = System.currentTimeMillis();
		Locale.setDefault(Locale.US);
		new D().run();
		System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time));
	}

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter writer;

	private void run() {
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			writer = new PrintWriter(System.out);
			solve();
			reader.close();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(13);
		}
	}
}


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

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

class AC {
    class Node extends Object{
        int x,y,dx,dy;
        Node() {}
        Node(int x,int y,int dx,int dy)
        {
            this.x = x;
            this.y = y;
            this.dx = dx;
            this.dy = dy;
        }
        @Override public boolean equals (Object cmp)  {
            if(cmp instanceof Node) {
                Node tmp = (Node) cmp;
                return tmp.x == x && tmp.y == y && tmp.dx==dx && tmp.dy == dy ;
            }
            return false;
        }
    }
    class pair extends Object{
        int x,y;
        pair() {}
        pair(int x,int y)
        {
            this.x = x;
            this.y = y;
        }
        @Override public boolean equals (Object cmp)  {
            if(cmp instanceof pair) {
                pair tmp = (pair) cmp;
                return tmp.x == x && tmp.y == y;
            }
            return false;
        }
        @Override public int hashCode () {
            return x*100000+y;
        }
    }
    int n , m;
    boolean judge(int x,int y) {
        return 1<=x && x <= n && 1 <= y && y <= m;
    }
    Node go(int x,int y,int dx,int dy) {

         int delta;
         if(dx < 0) {
             if(dy < 0)  {
                 delta = Math.min(x-1, y-1);
             } else {
                 delta = Math.min(m-y, x-1);
             }
         } else {
             if(dy < 0) {
                 delta = Math.min(n-x, y-1);
             } else {
                 delta = Math.min(n-x,m-y);
             }
         }
         x += dx * delta;
         y += dy * delta;
         if(x+dx<1 || x+dx>n) dx *= -1;
         if(y+dy<1 || y+dy>m) dy *= -1;
         return new Node(x,y,dx,dy);
    }
    public void solve(InputReader in, PrintWriter out) {
          int x0 , y0;
          String cmd;
          HashMap<Node,Integer> mp = new HashMap<Node,Integer>();
          HashMap<pair,Integer> M = new HashMap<pair,Integer>();
          n = in.nextInt();
          m = in.nextInt();
          x0 = in.nextInt(); y0 = in.nextInt();
          cmd = in.next();
          int tot = n + m - 2;
          int dx , dy;
          if(cmd.charAt(0)=='D') {
              dx = 1;
          } else dx = -1;
          if(cmd.charAt(1)=='R') {
              dy = 1;
          } else dy = -1;
          long ans = 1;
          pair A = new pair(1,2);
          pair B = new pair(1,2);
          if(x0==1 || x0==n || y0==1 || y0==m){
              M.put(new pair(x0, y0) , 1 );
              tot --;
          }
          while(true) {
              Node tmp = go(x0,y0,dx,dy);
              ans += Math.abs( tmp.x - x0);
              x0 = tmp.x ; y0 = tmp.y ;
              //out.println(x0+" "+y0);
              dx = tmp.dx ; dy = tmp.dy;
              pair t = new pair(x0,y0);
              Integer flag = M.get(t);
              if(flag == null) {
                 // out.println(x0+" "+y0);
                  M.put(t, 1);
                  if(--tot == 0) break;
              }
            //  out.println(M.get(t));
              if(mp.get(tmp)!=null){
                 ans = -1;
                 break;
              } else {
                  mp.put(tmp, 1);
              }
          }
          out.println(ans);
    }
}
class InputReader {
    BufferedReader reader;
    StringTokenizer tokenizer;
    public InputReader(InputStream stream) {
        reader = new BufferedReader(new InputStreamReader(stream));
        tokenizer = null;
    }

    public String next() {
        if (!hasNext())
            throw new RuntimeException();
        return tokenizer.nextToken();
    }

    boolean hasNext() {
        while (tokenizer == null || !tokenizer.hasMoreTokens())
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (Exception e) {
                return false;
            }
        return true;
    }

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

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

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


import java.util.*;

public class E {

    final int N = 100_000;
    final int W = 7;
    final int MOD = 1_000_000_007;

    int[][] mem;
    long[][][] memG;
    int[] w;
    int ans;

    void read() {
        Scanner scanner = new Scanner(System.in);

        w = new int[W];

        for (int i = 0; i < w.length; i++) {
            w[i] = scanner.nextInt();
        }

        scanner.close();
    }

    boolean good(int w, int a, int b, int c) {
        c = (((1 << w) | c) << 1) | 1;
        for (int i = 0; i <= w; i++) {
            if ((a & (1 << i)) > 0 && (b & (1 << i)) > 0 && (c & (1 << i)) > 0 && (c & (2 << i)) > 0) {
                return false;
            }
        }
        return true;
    }

    long[][] mul(long [][] a, long[][] b) {
        long[][] t = new long[1 << W][1 << W];

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a.length; j++) {
                for (int k = 0; k < a.length; k++) {
                    t[i][j] = (t[i][j] + a[i][k] * b[k][j]) % MOD;
                }
            }
        }

        return t;
    }

    long[][] pow(long[][] base, int p) {
        long[][] ans = new long[base.length][base.length];
        for (int i = 0; i < ans.length; i++) {
            ans[i][i] = 1;
        }
        for (; p > 0; p >>= 1) {
            if ((p & 1) > 0) {
                ans = mul(ans, base);
            }
            base = mul(base, base);
        }
        return ans;
    }

    long g(int w, int a, int b) {
        return memG[w][a][b];
    }

    long f(int mask, int pos) {
        if (mem[mask][pos] == 0) {
            int realMask = 1 << pos | mask;
            long res = 0;
            int lastMask = 1 << (pos + 1);

            if (pos == w.length - 1) {
                res = g(pos, realMask, lastMask - 1);
            } else {
                for (int i = 0; i < lastMask; i++) {
                    res = (res + g(pos, realMask, i) * f(i, pos + 1)) % MOD;
                }
            }

            mem[mask][pos] = (int) res + 1;
        }
        return mem[mask][pos] - 1;
    }

    void solve() {
        mem = new int[1 << W][W];
        memG = new long[W][1 << W][1 << W];

        for (int w = 0; w < W; w++) {
            int m = 1 << w + 1;

            for (int i = 0; i < m; i++) {
                for (int j = 0; j < m; j++) {
                    int res = 0;
                    int n = 1 << w;
                    for (int k = 0; k < n; k++) {
                        if (good(w, i, j, k)) {
                            res++;
                        }
                    }
                    memG[w][i][j] = res;
                }
            }

            memG[w] = pow(memG[w], this.w[w]);
        }

        ans = (int) f(0, 0);
    }

    void write() {
        System.out.println(ans);
    }

    public static void main(String[] args) {
        //long time = System.currentTimeMillis();
        E e = new E();
        e.read();
        e.solve();
        e.write();
        //System.out.println(System.currentTimeMillis() - time);
    }

}


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

public class E_faster {

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

	static final int P = 1_000_000_007;

	void solve() throws IOException {
		int[] ws = new int[7];
		for (int i = 0; i < 7; i++) {
			ws[i] = nextInt();
		}

		int[] dp = new int[1];
		dp[0] = 1;
		int prevH = 0;

		for (int h = 1; h <= 7; h++) {
			int w = ws[h - 1];
			if (w == 0) {
				continue;
			}
			dp = Arrays.copyOf(dp, 1 << h);
			int[] next = new int[1 << h];
			for (int i = 0; i < w; i++) {
				for (int j = 0; j < h; j++) {
					Arrays.fill(next, 0);
					boolean canDown = j != 0;
					boolean canLeft = j < prevH;
					for (int was = 0; was < (1 << h); was++) {
						if (dp[was] == 0) {
							continue;
						}
						int dpwas = dp[was];
						boolean needLeft = (was & 1) == 1;
						// down and left
						if (canDown && canLeft) {
							int tmp = (was & ~(1 << h - 1)) >> 1;
							int tmp2 = next[tmp] + dpwas;
							if (tmp2 >= P) {
								tmp2 -= P;
							}
							next[tmp] = tmp2;

						}
						// down
						if (canDown && !needLeft) {
							int tmp = (was & ~(1 << h - 1)) >> 1;
							int tmp2 = next[tmp] + dpwas;
							if (tmp2 >= P) {
								tmp2 -= P;
							}
							next[tmp] = tmp2;

						}
						// left
						if (canLeft) {
							int tmp = was >> 1;
							int tmp2 = next[tmp] + dpwas;
							if (tmp2 >= P) {
								tmp2 -= P;
							}
							next[tmp] = tmp2;

						}
						// nothing
						if (!needLeft) {
							int tmp = was >> 1 | (1 << h - 1);
							int tmp2 = next[tmp] + dpwas;
							if (tmp2 >= P) {
								tmp2 -= P;
							}
							next[tmp] = tmp2;

						}

					}
					int[] tmp = dp;
					dp = next;
					next = tmp;
				}
				prevH = h;
			}
		}

		out.println(dp[0]);
	}

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

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

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

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

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

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

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


import java.util.*;

public class E {

    final int N = 100_000;
    final int W = 7;
    final int MOD = 1_000_000_007;

    int[][] mem;
    long[][][] memG;
    int[] w;
    int ans;
    boolean memGood[][][][];
    boolean memGood1[][][][];

    void read() {
        Scanner scanner = new Scanner(System.in);

        w = new int[W];

        for (int i = 0; i < w.length; i++) {
            w[i] = scanner.nextInt();
        }

        scanner.close();
    }

    boolean good(int w, int a, int b, int c) {
        if (w < 0) {
            return true;
        }
        if (!memGood1[w][a][b][c]) {
            memGood1[w][a][b][c] = true;
            int x = 1 << w;
            memGood[w][a][b][c] = !((a & x) > 0 && (b & x) > 0 && (c & x) > 0 && (c & (x << 1)) > 0) && good(w - 1, a, b, c);
        }
        return memGood[w][a][b][c];
    }

    long[][] mul(long [][] a, long[][] b) {
        long[][] t = new long[a.length][a.length];

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a.length; j++) {
                for (int k = 0; k < a.length; k++) {
                    t[i][j] = (t[i][j] + a[i][k] * b[k][j]) % MOD;
                }
            }
        }

        return t;
    }

    long[][] pow(long[][] base, int p) {
        long[][] ans = new long[base.length][base.length];
        for (int i = 0; i < ans.length; i++) {
            ans[i][i] = 1;
        }
        for (; p > 0; p >>= 1) {
            if ((p & 1) > 0) {
                ans = mul(ans, base);
            }
            base = mul(base, base);
        }
        return ans;
    }

    long f(int mask, int pos) {
        if (mem[pos][mask] == 0) {
            int realMask = 1 << pos | mask;
            long res = 0;
            int lastMask = 1 << (pos + 1);

            if (pos == w.length - 1) {
                res = memG[pos][realMask][lastMask - 1];
            } else {
                for (int i = 0; i < lastMask; i++) {
                    res = (res + memG[pos][realMask][i] * f(i, pos + 1)) % MOD;
                }
            }

            mem[pos][mask] = (int) res + 1;
        }
        return mem[pos][mask] - 1;
    }

    void solve() {
        mem = new int[W][1 << W];
        memG = new long[W][][];
        memGood = new boolean[W][1 << W + 1][1 << W + 1][1 << W + 2];
        memGood1 = new boolean[W][1 << W + 1][1 << W + 1][1 << W + 2];

        for (int w = 0; w < W; w++) {
            int m = 1 << w + 1;
            long[][] t = new long[m][m];

            for (int i = 0; i < m; i++) {
                for (int j = 0; j < m; j++) {
                    int res = 0;
                    int n = 1 << w;
                    for (int k = 0; k < n; k++) {
                        if (good(w, i, j, ((n | k) << 1) | 1)) {
                            res++;
                        }
                    }
                    t[i][j] = res;
                }
            }

            memG[w] = pow(t, this.w[w]);
        }

        ans = (int) f(0, 0);
    }

    void write() {
        System.out.println(ans);
    }

    public static void main(String[] args) {
        //long time = System.currentTimeMillis();
        E e = new E();
        e.read();
        e.solve();
        e.write();
        //System.out.println(System.currentTimeMillis() - time);
    }

}


import java.util.*;

public class E {

    final int N = 100_000;
    final int W = 7;
    final int MOD = 1_000_000_007;

    int[] w;
    int[][] mem;
    int[][][] memG;
    int ans;

    void read() {
        Scanner scanner = new Scanner(System.in);

        int[] t = new int[W];
        int s = 0;

        for (int i = 0; i < t.length; i++) {
            t[i] = scanner.nextInt();
            s += t[i];
        }

        w = new int[s];

        for (int i = 0, j = 0; i < t.length; i++) {
            for (int k = 0; k < t[i]; k++) {
                w[j++] = i + 1;
            }
        }

        scanner.close();
    }

    int calcRealMask(int mask, int pos) {
        int prev = pos == 0 ? 0 : w[pos - 1];
        return mask | (((1 << prev) - 1) ^ ((1 << w[pos]) - 1));
    }

    boolean good(int w, int a, int b, int c) {
        c = (((1 << (w - 1)) | c) << 1) | 1;
        for (int i = 0; i < w; i++) {
            if ((a & (1 << i)) > 0 && (b & (1 << i)) > 0 && (c & (1 << i)) > 0 && (c & (2 << i)) > 0) {
                return false;
            }
        }
        return true;
    }

    int g(int w, int a, int b) {
        if (memG[w][a][b] == 0) {
            int res = 0;

            int n = 1 << (w - 1);
            for (int i = 0; i < n; i++) {
                if (good(w, a, b, i)) {
                    res++;
                }
            }

            memG[w][a][b] = res + 1;
        }
        return memG[w][a][b] - 1;
    }

    long f(int mask, int pos) {
        if (mem[mask][pos] == 0) {
            int realMask = calcRealMask(mask, pos);
            long res = 0;
            int lastMask = 1 << w[pos];

            if (pos == w.length - 1) {
                res = g(w[pos], realMask, lastMask - 1);
            } else {
                for (int i = 0; i < lastMask; i++) {
                    res = (res + g(w[pos], realMask, i) * f(i, pos + 1)) % MOD;
                }
            }

            mem[mask][pos] = (int) res + 1;
        }
        return mem[mask][pos] - 1;
    }

    void solve() {
        mem = new int[1 << w[w.length - 1]][w.length];
        memG = new int[W + 1][1 << W][1 << W];
        ans = f(0, 0);
    }

    void write() {
        System.out.println(ans);
    }

    public static void main(String[] args) {
        E e = new E();
        e.read();
        e.solve();
        e.write();
    }

}


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

public class Test {
  static PrintWriter writer =
      new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
  int n, k;
  int N = 1 << 16;
  int[][] f = new int[5][N];
  int idx = 0;

  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)) {
          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 solve(int n) {
    if (n == 1) {
      f[0][0] = 1;
      f[0][1] = 0;
      f[1][0] = 1;
      f[1][1] = 1;
      idx = 1;
      return;
    }
    if (n == 2) {
      f[1][0] = 1;
      f[1][1] = 1;
      f[2][0] = 1;
      f[2][1] = 3;
      f[2][2] = 1;
      idx = 2;
      return;
    }
    if (n % 2 == 1) {
      solve(n - 1);
      int nidx = (idx + 1) % 3, pidx = (idx + 3 - 1) % 3;
      f[nidx][0] = 1;
      for (int i = 1; i <= k; i++)
        f[nidx][i] = Ntt.add(Ntt.add(f[idx][i], f[idx][i - 1]), f[pidx][i - 1]);
      idx = nidx;
      return;
    }

    solve(n / 2);
    int nidx = (idx + 1) % 3, pidx = (idx + 3 - 1) % 3, ppidx = 3;
    for (int i = 0; i + 1 <= k; i++)
      f[ppidx][i] = Ntt.add(f[idx][i + 1], Ntt.M - Ntt.add(f[pidx][i], f[pidx][i + 1]));
//
//    Arrays.fill(f[idx], k + 1, N, 0);
//    Arrays.fill(f[pidx], k + 1, N, 0);
//    Arrays.fill(f[ppidx], k + 1, N, 0);

    Ntt.fft(f[idx], 0, N);
    Ntt.fft(f[pidx], 0, N);
    Ntt.fft(f[ppidx], 0, N);

    for (int i = 0; i < N; i++) f[nidx][i] = Ntt.mul(f[idx][i], f[idx][i]);
    Ntt.ifft(f[nidx], 0, N);

    for (int i = 0; i < N; i++) f[4][i] = Ntt.mul(f[pidx][i], f[pidx][i]);
    Ntt.ifft(f[4], 0, N);
    for (int i = 1; i <= k; i++) f[nidx][i] = Ntt.add(f[nidx][i], f[4][i - 1]);

    for (int i = 0; i < N; i++) f[idx][i] = Ntt.mul(f[idx][i], f[pidx][i]);
    Ntt.ifft(f[idx], 0, N);

    for (int i = 0; i < N; i++) f[pidx][i] = Ntt.mul(f[pidx][i], f[ppidx][i]);
    Ntt.ifft(f[pidx], 0, N);
    for (int i = 1; i <= k; i++) f[idx][i] = Ntt.add(f[idx][i], f[pidx][i - 1]);

    idx = nidx;
  }

  void start() {
    n = readInt();
    k = readInt();
    solve(n);
    for (int i = 1; i <= k; i++) writer.print(f[idx][i] + " ");
  }

  static class Ntt {
    static final int pri = 3;
    static final int M = 998_244_353;
    static int[] xy = new int[2];

    static int pmod(int b, int e) {
      int i = 1 << 31;
      int r = 1;
      while (i != 0) {
        r = mul(r, r);
        if ((e & i) != 0) r = mul(r, b);
        i >>>= 1;
      }
      return r;
    }

    static void fft(int[] a, int off, int len) {
      for (int i = 0; i < len; i++) {
        int j = i, x = 0, y = len - 1;
        while (y > 0) {
          x = (x << 1) + (j & 1);
          j >>>= 1;
          y >>>= 1;
        }
        if (i < x) {
          int t = a[off + i];
          a[off + i] = a[off + x];
          a[off + x] = t;
        }
      }
      for (int i = 1; i < len; i *= 2) {
        int s = pmod(pri, (M - 1) / 2 / i);
        for (int j = 0; j < len; j += 2 * i) {
          int w = 1;
          for (int k = 0; k < i; k++) {
            int u = a[off + j + k], v = mul(a[off + j + k + i], w);
            a[off + j + k] = add(u, v);
            a[off + j + k + i] = add(u, M - v);
            w = mul(w, s);
          }
        }
      }
    }

    static void ifft(int[] a, int off, int len) {
      int ll = 1, rr = len - 1;
      while (ll < rr) {
        int t = a[off + ll];
        a[off + (ll++)] = a[off + rr];
        a[off + (rr--)] = t;
      }
      fft(a, off, len);
      int inv = pmod(len, M - 2);
      for (int i = 0; i < len; i++) a[off + i] = mul(inv, a[off + i]);
    }

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

    static int mul(int a, int b) {
      return (int) ((a * (long) b) % M);
    }

    static int inverse(int a, int b) {
      if (b == 0) {
        xy[0] = 1;
        xy[1] = 0;
        return a;
      }
      int d = inverse(b, a % b);
      swap(xy, 0, 1);
      xy[1] -= a / b * xy[0];
      return d;
    }

    static void swap(int[] a, int i, int j) {
      int t = a[i];
      a[i] = a[j];
      a[j] = t;
    }
  }
}


import java.util.*;

public class Test {

    class F {
        int[] f;
        int m;

        F(int m) {
            f = new int[m + 1];
            this.m = m;
        }

        void add(int i, int v) {
            while (i <= m) {
                f[i] += v;
                i += i & (-i);
            }
        }

        int sum(int i) {
            int s = 0;
            while (i > 0) {
                s += f[i];
                i -= i & (-i);
            }
            return s;
        }

        int rsum(int i, int j) {
            return sum(j) - sum(i - 1);
        }
    }

    F f;
    int n, k;

    Scanner sca = new java.util.Scanner(System.in);

    void start() {
        n = sca.nextInt(); k = sca.nextInt();
        if (k + k > n) k = n - k;
        f = new F(n + 1);
        int a = 1, it = n;
        long c = 1;
        while (it > 0) {
            c++;
            int from = a - k + 1, to = a + k - 1;
            if (from < 1) c += f.rsum(1, to) + f.rsum(from + n, n);
            else {
                if (to > n) c += f.rsum(1, to - n) + f.rsum(from, n);
                else c += f.rsum(from, to);
            }

            System.out.print(c + " ");

            f.add(a, 1);
            a += k;
            if (a > n) a -= n;
            it--;
        }
        System.out.println();
    }

    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 n, k;
  int[][] dp = new int[3][1 << 16];
  int[] buf = new int[1 << 16], buf2 = new int[1 << 16];
  int idx = 0;

  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)) {
          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 solve(int n) {
    if (n == 1) {
      dp[0][0] = 1;
      dp[0][1] = 0;
      dp[1][0] = 1;
      dp[1][1] = 1;
      idx = 1;
      return;
    }
    if (n == 2) {
      dp[0][0] = 1;
      dp[0][1] = 0;
      dp[1][0] = 1;
      dp[1][1] = 1;
      dp[2][0] = 1;
      dp[2][1] = 3;
      dp[2][2] = 1;
      idx = 2;
      return;
    }
    if (n % 2 == 1) {
      solve(n - 1);
      int nidx = (idx + 1) % 3, pidx = (idx + 3 - 1) % 3;
      dp[nidx][0] = 1;
      for (int i = 1; i <= k; i++)
        dp[nidx][i] = Ntt.add(Ntt.add(dp[idx][i], dp[idx][i - 1]), dp[pidx][i - 1]);
      idx = nidx;
      return;
    }
    solve(n / 2);
    int nidx = (idx + 1) % 3, pidx = (idx + 3 - 1) % 3;
    System.arraycopy(dp[idx], 0, buf, 0, buf.length);
    Ntt.fft(buf, 0, buf.length);

    for (int i = 0; i < buf.length; i++) buf[i] = Ntt.mul(buf[i], buf[i]);
    Ntt.ifft(buf, 0, buf.length);
    for (int i = 0; i < buf.length; i++) dp[nidx][i] = buf[i];

    System.arraycopy(dp[pidx], 0, buf2, 0, buf2.length);
    Ntt.fft(buf2, 0, buf2.length);

    for (int i = 0; i < buf2.length; i++) buf2[i] = Ntt.mul(buf2[i], buf2[i]);
    Ntt.ifft(buf2, 0, buf2.length);
    for (int i = 1; i < buf.length; i++) dp[nidx][i] = Ntt.add(dp[nidx][i], buf2[i - 1]);

    for (int i = 0; i + 1 < buf.length; i++)
      buf[i] = Ntt.add(dp[idx][i + 1], Ntt.M - Ntt.add(dp[pidx][i], dp[pidx][i + 1]));
    Ntt.fft(buf, 0, buf.length);
    for (int i = 0; i < buf.length; i++) buf[i] = Ntt.mul(buf[i], buf[i]);
    Ntt.ifft(buf, 0, buf.length);
    dp[pidx][0] = 1;
    for (int i = 1; i < buf.length; i++) dp[pidx][i] = Ntt.add(buf2[i], buf[i - 1]);
    dp[idx][0] = 1;
    for (int i = 1; i < buf.length; i++)
      dp[idx][i] = Ntt.add(dp[nidx][i], Ntt.M - Ntt.add(dp[idx][i - 1], dp[pidx][i - 1]));
    idx = nidx;
  }

  void start() {
    n = readInt();
    k = readInt();
    solve(n);
    for (int i = 1; i <= k; i++) writer.print(dp[idx][i] + " ");
  }

  static class Ntt {
    static final int pri = 3;
    static final int M = 998_244_353;
    static int[] xy = new int[2];

    static int pmod(int b, int e) {
      int i = 1 << 31;
      int r = 1;
      while (i != 0) {
        r = mul(r, r);
        if ((e & i) != 0) r = mul(r, b);
        i >>>= 1;
      }
      return r;
    }

    static void fft(int[] a, int off, int len) {
      for (int i = 0; i < len; i++) {
        int j = i, x = 0, y = len - 1;
        while (y > 0) {
          x = (x << 1) + (j & 1);
          j >>>= 1;
          y >>>= 1;
        }
        if (i < x) {
          int t = a[off + i];
          a[off + i] = a[off + x];
          a[off + x] = t;
        }
      }
      for (int i = 1; i < len; i *= 2) {
        int s = pmod(pri, (M - 1) / 2 / i);
        for (int j = 0; j < len; j += 2 * i) {
          int w = 1;
          for (int k = 0; k < i; k++) {
            int u = a[off + j + k], v = mul(a[off + j + k + i], w);
            a[off + j + k] = add(u, v);
            a[off + j + k + i] = add(u, M - v);
            w = mul(w, s);
          }
        }
      }
    }

    static void ifft(int[] a, int off, int len) {
      int ll = 1, rr = len - 1;
      while (ll < rr) {
        int t = a[off + ll];
        a[off + (ll++)] = a[off + rr];
        a[off + (rr--)] = t;
      }
      fft(a, off, len);
      int inv = pmod(len, M - 2);
      for (int i = 0; i < len; i++) a[off + i] = mul(inv, a[off + i]);
    }

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

    static int mul(int a, int b) {
      return (int) ((a * (long) b) % M);
    }

    static int inverse(int a, int b) {
      if (b == 0) {
        xy[0] = 1;
        xy[1] = 0;
        return a;
      }
      int d = inverse(b, a % b);
      swap(xy, 0, 1);
      xy[1] -= a / b * xy[0];
      return d;
    }

    static void swap(int[] a, int i, int j) {
      int t = a[i];
      a[i] = a[j];
      a[j] = t;
    }
  }
}


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 n, k;
  int[][] dp = new int[3][1 << 16];
  int[] buf = new int[1 << 16], buf2 = new int[1 << 16];
  int idx = 0;

  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)) {
          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 solve(int n) {
    if (n == 1) {
      dp[0][0] = 1;
      dp[0][1] = 0;
      dp[1][0] = 1;
      dp[1][1] = 1;
      idx = 1;
      return;
    }
    if (n == 2) {
      dp[0][0] = 1;
      dp[0][1] = 0;
      dp[1][0] = 1;
      dp[1][1] = 1;
      dp[2][0] = 1;
      dp[2][1] = 3;
      dp[2][2] = 1;
      idx = 2;
      return;
    }
    if (n % 2 == 1) {
      solve(n - 1);
      int nidx = (idx + 1) % 3, pidx = (idx + 3 - 1) % 3;
      dp[nidx][0] = 1;
      for (int i = 1; i < buf.length; i++)
        dp[nidx][i] = Ntt.add(Ntt.add(dp[idx][i], dp[idx][i - 1]), dp[pidx][i - 1]);
      idx = nidx;
      return;
    }
    solve(n / 2);
    int nidx = (idx + 1) % 3, pidx = (idx + 3 - 1) % 3;
    System.arraycopy(dp[idx], 0, buf, 0, buf.length);
    Ntt.fft(buf, 0, buf.length);

    for (int i = 0; i < buf.length; i++) buf[i] = Ntt.mul(buf[i], buf[i]);
    Ntt.ifft(buf, 0, buf.length);
    for (int i = 0; i < buf.length; i++) dp[nidx][i] = buf[i];

    System.arraycopy(dp[pidx], 0, buf2, 0, buf2.length);
    Ntt.fft(buf2, 0, buf2.length);

    for (int i = 0; i < buf2.length; i++) buf2[i] = Ntt.mul(buf2[i], buf2[i]);
    Ntt.ifft(buf2, 0, buf2.length);
    for (int i = 1; i < buf.length; i++) dp[nidx][i] = Ntt.add(dp[nidx][i], buf2[i - 1]);

    for (int i = 0; i + 1 < buf.length; i++)
      buf[i] = Ntt.add(dp[idx][i + 1], Ntt.M - Ntt.add(dp[pidx][i], dp[pidx][i + 1]));
    Ntt.fft(buf, 0, buf.length);
    for (int i = 0; i < buf.length; i++) buf[i] = Ntt.mul(buf[i], buf[i]);
    Ntt.ifft(buf, 0, buf.length);
    dp[pidx][0] = 1;
    for (int i = 1; i < buf.length; i++) dp[pidx][i] = Ntt.add(buf2[i], buf[i - 1]);
    dp[idx][0] = 1;
    for (int i = 1; i < buf.length; i++)
      dp[idx][i] = Ntt.add(dp[nidx][i], Ntt.M - Ntt.add(dp[idx][i - 1], dp[pidx][i - 1]));
    idx = nidx;
  }

  void start() {
    n = readInt();
    k = readInt();
    solve(n);
    for (int i = 1; i <= k; i++) writer.print(dp[idx][i] + " ");
  }

  static class Ntt {
    static final int pri = 3;
    static final int M = 998_244_353;
    static int[] xy = new int[2];

    static int pmod(int b, int e) {
      int i = 1 << 31;
      int r = 1;
      while (i != 0) {
        r = mul(r, r);
        if ((e & i) != 0) r = mul(r, b);
        i >>>= 1;
      }
      return r;
    }

    static void fft(int[] a, int off, int len) {
      for (int i = 0; i < len; i++) {
        int j = i, x = 0, y = len - 1;
        while (y > 0) {
          x = (x << 1) + (j & 1);
          j >>>= 1;
          y >>>= 1;
        }
        if (i < x) {
          int t = a[off + i];
          a[off + i] = a[off + x];
          a[off + x] = t;
        }
      }
      for (int i = 1; i < len; i *= 2) {
        int s = pmod(pri, (M - 1) / 2 / i);
        for (int j = 0; j < len; j += 2 * i) {
          int w = 1;
          for (int k = 0; k < i; k++) {
            int u = a[off + j + k], v = mul(a[off + j + k + i], w);
            a[off + j + k] = add(u, v);
            a[off + j + k + i] = add(u, M - v);
            w = mul(w, s);
          }
        }
      }
    }

    static void ifft(int[] a, int off, int len) {
      int ll = 1, rr = len - 1;
      while (ll < rr) {
        int t = a[off + ll];
        a[off + (ll++)] = a[off + rr];
        a[off + (rr--)] = t;
      }
      fft(a, off, len);
      int inv = pmod(len, M - 2);
      for (int i = 0; i < len; i++) a[off + i] = mul(inv, a[off + i]);
    }

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

    static int mul(int a, int b) {
      return (int) ((a * (long) b) % M);
    }

    static int inverse(int a, int b) {
      if (b == 0) {
        xy[0] = 1;
        xy[1] = 0;
        return a;
      }
      int d = inverse(b, a % b);
      swap(xy, 0, 1);
      xy[1] -= a / b * xy[0];
      return d;
    }

    static void swap(int[] a, int i, int j) {
      int t = a[i];
      a[i] = a[j];
      a[j] = t;
    }
  }
}


import java.lang.Math;

public class HelloWorld
{
  List<String> lines;
  boolean vis = false;
  public static void main(String[] args)
  {
    lines = Files.readAllLines(Paths.get(FILE_NAME), StandardCharsets.UTF_8);
    pnt(0, 3);
    pnt(0, 4);
    pnt(1, 3);
    pnt(1, 4);

    pnt(2, 3);
    pnt(2, 4);
    pnt(3, 3);
    pnt(3, 4);
    pnt(0, 0);
    pnt(0, 1);
    pnt(0, 6);
    pnt(0, 7);
    pnt(1, 0);
    pnt(1, 1);
    pnt(1, 6);
    pnt(1, 7);

    pnt(4, 3);
    pnt(4, 4);
    pnt(5, 3);
    pnt(5, 4);
    pnt(2, 0);
    pnt(2, 1);
    pnt(2, 6);
    pnt(2, 7);
    pnt(3, 0);
    pnt(3, 1);
    pnt(3, 6);
    pnt(3, 7);

    pnt(4, 0);
    pnt(4, 1);
    pnt(4, 6);
    pnt(4, 7);
    pnt(5, 0);
    pnt(5, 1);
    pnt(5, 6);
    pnt(5, 7);
    for (String line: lines) {
     	System.out.println(line);
    }
  }

  void pnt(int x, int y) {
    if (!vis && lines[x][y] == '.'){
     	lines[x][y] = 'P';
      	vis = true;
    }
  }
}


public class Sol{
	public static void main(String[] argc){
		int seat[][] = {
				{3, 3, 0, 4, 4, 0, 3, 3},
				{3, 3, 0, 4, 4, 0, 3, 3},
				{2, 2, 0, 3, 3, 0, 2, 2},
				{2, 2, 0, 3, 3, 0, 2, 2},
				{1, 1, 0, 2, 2, 0, 1, 1},
				{1, 1, 0, 2, 2, 0, 1, 1}
		};
		String plan[] = new String[6];
		Scanner sc = new Scanner(System.in);
		int best = 0;
		int row = -1;
		int col = -1;
		for (int i = 0; i < 6; ++i) {
			String cur = sc.nextLine();
			plan[i] = cur;
			for (int j = 0; j < 8; ++j) {
				if (cur.charAt(j) == '.') {
					if (seat[i][j] > best) {
						best = seat[i][j];
						row = i;
						col = j;
					}
				}
			}
		}
		for (int i = 0; i < 6; ++i) {
			if (i != row) {
				System.out.println(plan[i].toString());
			}
			else {
				for (int j = 0; j < 8; ++j) {
					if (j != col) {
						System.out.print(plan[i].charAt(j));
					}
					else {
						System.out.print('P');
					}
				}
				System.out.println();
			}
		}
	}
}


package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        String[] res = new String[6];
        boolean flag = false;

        for (int x = 0; x < 6; x++)
        {
            String s = input.next();
            for (int i = 3; i < 5; ++i)
            {
                if (s.charAt(i) != '*' && !flag)
                {
                    char[] st = s.toCharArray();
                    st[i] = 'P';
                    s = String.valueOf(st);
                    flag = true;
                    break;
                }
            }
            for (int i = 0; i < 8; ++i)
            {
                if (i != 3 && i != 4 && s.charAt(i) == '.' && !flag)
                {
                    char[] st = s.toCharArray();
                    st[i] = 'P';
                    s = String.valueOf(st);
                    flag = true;
                    break;
                }
            }
            res[x] = s;
        }

        for (int x = 0; x < 6; x++)
        {
            System.out.println(res[x]);
        }
    }
}


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

public class EMain {
    String noResultMessage = "NoResult";
    Parser in = new Parser();
    PrintWriter out;

    long n = in.nextLong();
    int k = in.nextInteger();

    Matrix[] upRow(Matrix[] row){
        Matrix[] result = new Matrix[k];
        for(int i = 0; i < k; ++i){
            Matrix m = Matrix.oneMatrix(k+1);
            for(int j = 0; j < k; ++j){
                m = Matrix.mul(m, row[(i+j)%k]);
            }
            result[i] = m;
        }
        return result;
    }

    public void solve() {

        Matrix[][] matrixes = new Matrix[100][k];

        for(int i = 0; i < k; ++i){
            Matrix m = Matrix.oneMatrix(k + 1);
            matrixes[0][i] = m;
            for(int j = 0; j <= k; ++j){
                m.set(j, i, 1);
            }
        }
        int[] digits = new int[100];
        int index = 0;
        long limit = n;
        digits[index++] = (int) (limit % k);
        for(int row = 1; row < 100; ++row){
            limit /= k;
            if(limit == 0)break;
            digits[index++] = (int) (limit % k);
            matrixes[row] = upRow(matrixes[row-1]);
        }

        Matrix result = Matrix.oneMatrix(k+1);
        int pos = 0;
        while(index-- > 0){
            while(digits[index]-- > 0){
                result = Matrix.mul(result, matrixes[index][pos++]);
            }
        }
        Vector vec = new Vector(k+1);
        vec.set(k, 1);
        out.println(Vector.mul(vec, result).sum());

    }

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

    static public class Matrix {
        int[][] data;

        public Matrix(int size) {
            this.data = new int[size][size];
        }

        Matrix(Matrix other) {
            int size = other.data.length;
            this.data = new int[size][];
            for(int i = 0; i < size; ++i){
                this.data[i] = Arrays.copyOf(other.data[i], size);
            }
        }
        public void set(int row, int column, int value){
            data[row][column] = value;
        }

        public static Matrix oneMatrix(int size){
            Matrix result = new Matrix(size);
            for(int i = 0; i < size; ++i){
                result.data[i][i] = 1;
            }
            return result;
        }

        public static Matrix mul(Matrix left, Matrix right){
            int size = left.data.length;
            assert size == right.data.length;
            Matrix result = new Matrix(size);
            for(int i = 0; i < size; ++i){
                for(int j = 0; j < size; ++j){
                    int val = 0;
                    for(int k = 0; k < size; ++k){
                        val += 1l * left.data[i][k] * right.data[k][j] % MOD;
                        val += MOD;
                        val %= MOD;
                    }
                    result.data[i][j] = val;
                }
            }
            return result;
        }

        static Matrix degree(Matrix matrix, long degree){
            Matrix result = Matrix.oneMatrix(matrix.data.length);
            while(degree > 0){
                if((degree & 1) == 1){
                    result = Matrix.mul(result, matrix);
                }
                result = Matrix.mul(result, result);
                degree >>= 1;
            }
            return result;
        }
    }

    static public class Vector{
        int[] data;

        public Vector(int size) {
            this.data = new int[size];
        }

        Vector(Vector other) {
            this.data = Arrays.copyOf(other.data, other.data.length);
        }

        public void set(int pos, int val){
            data[pos] = val;
        }

        int get(int pos){
            return data[pos];
        }

        public int sum(){
            long sum = 0;
            for(int i : data){
                sum += i;
            }
            sum %= MOD;
            sum += MOD;
            sum %= MOD;
            return (int) sum;
        }

        public static Vector mul(Vector vec, Matrix matrix){
            int size = vec.data.length;
            assert size == matrix.data.length;
            Vector result = new Vector(size);
            for(int i = 0; i < size; ++i){
                int val = 0;
                for(int j = 0; j < size; ++j){
                    val += 1l * vec.data[j] * matrix.data[j][i] % MOD;
                    val += MOD;
                    val %= MOD;
                }
                result.data[i] = val;
            }
            return result;
        }
    }

    static public class Parser{
        Scanner scanner;

        public Parser() {
            scanner = new Scanner(System.in).useLocale(Locale.ENGLISH);
        }

        public Parser(String str) {
            scanner = new Scanner(str).useLocale(Locale.ENGLISH);
        }

        long nextLong(){
            return scanner.nextLong();
        }

        int nextInteger(){
            return scanner.nextInt();
        }

        double nextDouble(){
            return scanner.nextDouble();
        }

        String nextLine(){
            return scanner.nextLine();
        }

        String next(){
            return scanner.next();
        }

        int[] nextIntegers(int count){
            int[] result = new int[count];
            for(int i = 0; i < count; ++i){
                result[i] = nextInteger();
            }
            return result;
        }

        long[] nextLongs(int count){
            long[] result = new long[count];
            for(int i = 0; i < count; ++i){
                result[i] = nextLong();
            }
            return result;
        }

        int[][] nextIntegers(int fields, int count){
            int[][] result = new int[fields][count];
            for(int c = 0; c < count; ++c){
                for(int i = 0; i < fields; ++i){
                    result[i][c] = nextInteger();
                }
            }
            return result;
        }
    }

    void noResult(){
        throw new NoResultException();
    }

    void noResult(String str){
        throw new NoResultException(str);
    }

    void run(){
        try{
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            out = new PrintWriter(outStream);
            solve();
            out.close();
            System.out.print(outStream.toString());
        } catch (NoResultException exc){
            System.out.print(null == exc.response ? noResultMessage : exc.response);
        }
    }

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

    public static class NoResultException extends RuntimeException{
        private String response;

        public NoResultException(String response) {
            this.response = response;
        }

        public NoResultException() {
        }
    }
}


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

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

class TaskE {
    static final long MODULO = (long) (1e9 + 7);
    static final long BIG = Long.MAX_VALUE - Long.MAX_VALUE % MODULO;

    public void solve(int testNumber, InputReader in, PrintWriter out) {
        long n = in.nextLong();
        int k = in.nextInt();
        long pk = 1;
        int pow = 0;
        while (pk <= n / k) {
            pk *= k;
            ++pow;
        }
        matrCache = new long[pow + 1][][];
        long at = 0;
        long[] ways = new long[k + 1];
        ways[k] = 1;
        while (at < n) {
            while (at + pk <= n) {
                long[][] matr = getMatr(digitSum(at, k) % k, k, pow);
                ways = mul(matr, ways);
                at += pk;
            }
            pk /= k;
            --pow;
        }
        long res = 0;
        for (long x : ways) res += x;
        res %= MODULO;
        out.println(res);
    }

    long[][][] matrCache;

    private long[][] getMatr(int pre, int k, int pow) {
        long[][] res = matrCache[pow];
        if (res == null) {
            if (pow == 0) {
                res = new long[k + 1][k + 1];
                for (int i = 0; i < k + 1; ++i) ++res[i][i];
                for (int i = 0; i < k + 1; ++i) {
                    ++res[pre][i];
                }
                --res[pre][pre];
            } else {
                res = new long[k + 1][k + 1];
                for (int i = 0; i < k + 1; ++i) ++res[i][i];
                for (int i = 0; i < k; ++i) {
                    res = mul(res, getMatr(i, k, pow - 1));
                }
            }
            matrCache[pow] = res;
        }
        long[][] rotated = new long[k + 1][k + 1];
        for (int i = 0; i <= k; ++i)
            for (int j = 0; j <= k; ++j) {
                int ii = (i == k) ? k : (pre + i) % k;
                int jj = (j == k) ? k : (pre + j) % k;
                rotated[ii][jj] = res[i][j];
            }
        return rotated;
    }

    private long[] mul(long[][] a, long[] b) {
        long[] c = new long[b.length];
        for (int i = 0; i < c.length; ++i) {
            long s = 0;
            for (int j = 0; j < c.length; ++j) {
                s += a[i][j] * b[j];
                if (s < 0) s -= BIG;
            }
            c[i] = s % MODULO;
        }
        return c;
    }

    private long[][] mul(long[][] a, long[][] b) {
        long[][] c = new long[b.length][b.length];
        for (int i = 0; i < c.length; ++i) {
            for (int k = 0; k < c.length; ++k) {
                long s = 0;
                for (int j = 0; j < c.length; ++j) {
                    s += a[i][j] * b[j][k];
                    if (s < 0) s -= BIG;
                }
                c[i][k] = s % MODULO;
            }
        }
        return c;
    }

    private int digitSum(long at, int k) {
        int res = 0;
        while (at > 0) {
            res += at % k;
            at /= k;
        }
        return res;
    }
}

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.util.*;
import static java.lang.Math.*;

public class E {
    static void p(Object ...args) {System.out.println(Arrays.deepToString(args));}
    static long MOD = 1_000_000_007;

    /*static int score(int a, int k) {
        int ans = 0;
        while( a > 0) {
            ans += a % k;
            a /= k;
        }
        return ans % k;
    }

    public static long slow(int N, int K) {
        long[] V = new long[N+1];
        for (int i = 0; i <= N; i++)
            V[i] = score(i, K);
        long[] dp = new long[N+1];
        for (int i = 0; i <= N; i++) {
            for (int j = 0; j < K; j++) {
                for (int a = i - 1; a >= 0; a--) {
                    if (V[a] == j) {
                        dp[i] += dp[a];
                        break;
                    }
                }
            }
            dp[i] += 1;
            dp[i] %= MOD;
        }
        return dp[N];
    }*/
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        long N = in.nextLong();
        int K = in.nextInt();

        long[][][] M = new long[100][][];
        for (int i = 2; i < M.length; i++)
            M[i] = makeMatrix(K, i);

        /*p("M[2]");
        for (int i = 0; i < M[2].length; i++)
            p(M[2][i]);
        p("M[3]");
        for (int i = 0; i < M[3].length; i++)
            p(M[3][i]);*/

        long[][][] moveBy = new long[100][][];
        long[][][] moveByK = new long[100][][];
        for (int i = 1; i < moveBy.length - 1; i++) {
            long[][] ans = new long[K+1][K+1];
            for (int j = 0; j < ans.length; j++)
                ans[j][j] = 1;
            for (int j = i - 1; j >= 1; j--)
                ans = multiply(ans, moveByK[j]);

            ans = multiply(ans, M[i+1]);
            moveBy[i] = ans;
            moveByK[i] = new long[K+1][K+1];
            for (int j = 0; j <= K; j++)
                moveByK[i][j][j] = 1;
            for (int j = 0; j < K-1; j++)
                moveByK[i] = multiply(moveByK[i], moveBy[i]);
        }
        /*p("moveBy[2]");
        for (int i = 0; i <= K; i++)
            p(moveBy[2][i]);*/

        long at = 0;
        long[][] f = new long[K+1][K+1];
        for (int i = 0; i < f.length; i++)
            f[i][i] = 1;
        //f = multiply(f, M[2]);
        //f = multiply(f, M[3]);
        long temp = N / K;
        for (int i = 1; temp > 0; i++) {
            for (int j = 0; j < temp % K; j++) {
                //p("mult by", i);
                f = multiply(moveBy[i], f);
            }
            temp /= K;
        }
        /*p("f");
        for (int i = 0; i < K+1; i++)
            p(f[i]);*/
        long[] start = new long[K+1];
        for (int i = 0; i < start.length; i++)
            start[i] = (1L<<(i)) % MOD;
        start[K] = 1;

        int position = (int)(N % K);
        p("taking: ", position);
        long ans = 0;
        for (int i = 0; i < start.length; i++)
            ans += (start[i] * f[i][position]) % MOD;
        ans %= MOD;

        /*long a2 = slow((int)N, K);
        if (ans != a2) {
            p(ans, a2);
            throw new RuntimeException();
        }*/
        System.out.println(ans);
    }
    static long[][] makeMatrix(int K, int a) {
        long[][] res = new long[K+1][K+1];

        int[] v = new int[2*K];
        v[2*K-1] = 0;
        for (int i = 2*K-2; i >= 0; i--) {
            if (i == K-1) {
                v[i] = (K + (K-a + v[i+1]) % K) % K;
            } else {
                v[i] = (K + (K-1 + v[i+1]) % K) % K;
            }
        }
        /*if (a == 2 || a == 3) {
            p(a, v);
        }*/
        for (int i = 0; i <= K; i++)
            res[K][i]++;
        for (int c = 0; c < K; c++) {
            for (int i = 0; i < K; i++) {
                boolean found = false;
                for (int j = c - 1 + K; j >= 0; j--) {
                    if (v[j] == i) {
                        found = true;
                        if (j < K) {
                            res[j][c] += 1;
                        } else {
                            for (int b = 0; b <= K; b++)
                                res[b][c] += res[b][j-K];
                        }
                        break;
                    }
                }
                if (!found) {
                    p(c, i, v);
                    throw new RuntimeException();
                }
            }
        }
        return res;
    }
    static long[][] multiply(long[][] A, long[][] B) {
        long[][] res = new long[A.length][A.length];
        for (int r = 0; r < A.length; r++)
            for (int c = 0; c < A.length; c++) {
                for (int i = 0; i < A.length; i++)
                    res[r][c] += (A[r][i] * B[i][c]) % MOD;
                res[r][c] %= MOD;
            }
        return res;
    }
 }


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

public class EMain {
    String noResultMessage = "NoResult";
    Parser in = new Parser();
    PrintWriter out;

    long n = in.nextLong();
    int k = in.nextInteger();

    Matrix[] upRow(Matrix[] row){
        Matrix[] result = new Matrix[k];
        for(int i = 0; i < k; ++i){
            Matrix m = Matrix.oneMatrix(k+1);
            for(int j = 0; j < k; ++j){
                m = Matrix.mul(m, row[(i+j)%k]);
            }
            result[i] = m;
        }
        return result;
    }

    public void solve() {

        Matrix[][] matrixes = new Matrix[100][k];

        for(int i = 0; i < k; ++i){
            Matrix m = Matrix.oneMatrix(k + 1);
            matrixes[0][i] = m;
            for(int j = 0; j <= k; ++j){
                m.set(j, i, 1);
            }
        }
        int[] digits = new int[100];
        int index = 0;
        long limit = n;
        digits[index++] = (int) (limit % k);
        for(int row = 1; row < 100; ++row){
            limit /= k;
            if(limit == 0)break;
            digits[index++] = (int) (limit % k);
            matrixes[row] = upRow(matrixes[row-1]);
        }

        Matrix result = Matrix.oneMatrix(k+1);
        int pos = 0;
        while(index-- > 0){
            while(digits[index]-- > 0){
                result = Matrix.mul(result, matrixes[index][pos++%k]);
            }
        }
        Vector vec = new Vector(k+1);
        vec.set(k, 1);
        out.println(Vector.mul(vec, result).sum());

    }

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

    static public class Matrix {
        int[][] data;

        public Matrix(int size) {
            this.data = new int[size][size];
        }

        Matrix(Matrix other) {
            int size = other.data.length;
            this.data = new int[size][];
            for(int i = 0; i < size; ++i){
                this.data[i] = Arrays.copyOf(other.data[i], size);
            }
        }
        public void set(int row, int column, int value){
            data[row][column] = value;
        }

        public static Matrix oneMatrix(int size){
            Matrix result = new Matrix(size);
            for(int i = 0; i < size; ++i){
                result.data[i][i] = 1;
            }
            return result;
        }

        public static Matrix mul(Matrix left, Matrix right){
            int size = left.data.length;
            assert size == right.data.length;
            Matrix result = new Matrix(size);
            for(int i = 0; i < size; ++i){
                for(int j = 0; j < size; ++j){
                    int val = 0;
                    for(int k = 0; k < size; ++k){
                        val += 1l * left.data[i][k] * right.data[k][j] % MOD;
                        val += MOD;
                        val %= MOD;
                    }
                    result.data[i][j] = val;
                }
            }
            return result;
        }

        static Matrix degree(Matrix matrix, long degree){
            Matrix result = Matrix.oneMatrix(matrix.data.length);
            while(degree > 0){
                if((degree & 1) == 1){
                    result = Matrix.mul(result, matrix);
                }
                result = Matrix.mul(result, result);
                degree >>= 1;
            }
            return result;
        }
    }

    static public class Vector{
        int[] data;

        public Vector(int size) {
            this.data = new int[size];
        }

        Vector(Vector other) {
            this.data = Arrays.copyOf(other.data, other.data.length);
        }

        public void set(int pos, int val){
            data[pos] = val;
        }

        int get(int pos){
            return data[pos];
        }

        public int sum(){
            long sum = 0;
            for(int i : data){
                sum += i;
            }
            sum %= MOD;
            sum += MOD;
            sum %= MOD;
            return (int) sum;
        }

        public static Vector mul(Vector vec, Matrix matrix){
            int size = vec.data.length;
            assert size == matrix.data.length;
            Vector result = new Vector(size);
            for(int i = 0; i < size; ++i){
                int val = 0;
                for(int j = 0; j < size; ++j){
                    val += 1l * vec.data[j] * matrix.data[j][i] % MOD;
                    val += MOD;
                    val %= MOD;
                }
                result.data[i] = val;
            }
            return result;
        }
    }

    static public class Parser{
        Scanner scanner;

        public Parser() {
            scanner = new Scanner(System.in).useLocale(Locale.ENGLISH);
        }

        public Parser(String str) {
            scanner = new Scanner(str).useLocale(Locale.ENGLISH);
        }

        long nextLong(){
            return scanner.nextLong();
        }

        int nextInteger(){
            return scanner.nextInt();
        }

        double nextDouble(){
            return scanner.nextDouble();
        }

        String nextLine(){
            return scanner.nextLine();
        }

        String next(){
            return scanner.next();
        }

        int[] nextIntegers(int count){
            int[] result = new int[count];
            for(int i = 0; i < count; ++i){
                result[i] = nextInteger();
            }
            return result;
        }

        long[] nextLongs(int count){
            long[] result = new long[count];
            for(int i = 0; i < count; ++i){
                result[i] = nextLong();
            }
            return result;
        }

        int[][] nextIntegers(int fields, int count){
            int[][] result = new int[fields][count];
            for(int c = 0; c < count; ++c){
                for(int i = 0; i < fields; ++i){
                    result[i][c] = nextInteger();
                }
            }
            return result;
        }
    }

    void noResult(){
        throw new NoResultException();
    }

    void noResult(String str){
        throw new NoResultException(str);
    }

    void run(){
        try{
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            out = new PrintWriter(outStream);
            solve();
            out.close();
            System.out.print(outStream.toString());
        } catch (NoResultException exc){
            System.out.print(null == exc.response ? noResultMessage : exc.response);
        }
    }

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

    public static class NoResultException extends RuntimeException{
        private String response;

        public NoResultException(String response) {
            this.response = response;
        }

        public NoResultException() {
        }
    }
}


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

public class Main {
	static final int N=1000005;
	static int a[]=new int[N];
	static int t[]=new int[N];
	static int ans=0;
	@SuppressWarnings("unchecked")
	static ArrayList<Integer>G[]=new ArrayList[N];
	static HashMap<ArrayList<Integer>,Integer>vis=new HashMap<ArrayList<Integer>,Integer>();
	static HashMap<String,Integer>book=new HashMap<String,Integer>();
	static int sz;
	static class cmp implements Comparator<Object>{
		@Override
		public int compare(Object o1,Object o2) {
			Integer p1=(Integer)o1;
			Integer p2=(Integer)o2;
			return p1>p2?1:-1;
		}
	}
	static int dfs(int u,int fa) {
		StringBuilder st=new StringBuilder(String.valueOf(u));
		st.append("#");
		st.append(String.valueOf(fa));
		if(book.containsKey(st.toString())) {
			return book.get(st.toString());
		}
		ArrayList<Integer>temp=new ArrayList<Integer>();
		for(int i=0;i<G[u].size();i++) if(G[u].get(i)!=fa) {
			temp.add(dfs(G[u].get(i),u));
		}
		temp.sort(new cmp());
		if(!vis.containsKey(temp)) {
			vis.put(temp, ++sz);
		}
		book.put(st.toString(),vis.get(temp));
		return vis.get(temp);
	}
	public static void main(String[] args){
		InputReader in = new InputReader(System.in);
	    PrintWriter out = new PrintWriter(System.out);
	    int n=in.nextInt();sz=0;
	    for(int i=0;i<n-1;i++) {
	    	int u=in.nextInt(),v=in.nextInt();
	    	if(G[u]==null) G[u]=new ArrayList<Integer>();
	    	if(G[v]==null) G[v]=new ArrayList<Integer>();
	    	G[u].add(v);G[v].add(u);
	    }
	    int ans=0;
	    HashMap<Integer,Integer>map=new HashMap<Integer,Integer>();
	    for(int i=1;i<=n;i++) {
	    	if(G[i].size()==4) continue;
	    	int id=dfs(i,-1);
	    	if(!map.containsKey(id)) {
	    		ans++;
	    		map.put(id, 1);
	    	}
	    }
	    out.println(ans);
	    out.flush();
	}
	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());
        }
    }
}


package codeforces;
import java.io.*;
import java.util.*;
public class Main {
	static final int N=100005;
	static int a[]=new int[N];
	static ArrayList<Integer>G[]=new ArrayList[N];
	static HashMap<ArrayList<Integer>,Integer>vis=new HashMap<ArrayList<Integer>,Integer>();
	static HashMap<String,Integer>book=new HashMap<String,Integer>();
	static int sz;
	static class cmp implements Comparator<Object>{
		@Override
		public int compare(Object o1,Object o2) {
			Integer p1=(Integer)o1;
			Integer p2=(Integer)o2;
			return p1>p2?1:-1;
		}
	}
	static int dfs(int u,int fa) {
		String st=u+"#"+fa;
		if(book.containsKey(st)) {
			return book.get(st);
		}
		ArrayList<Integer>temp=new ArrayList<Integer>();
		for(int i=0;i<G[u].size();i++) if(G[u].get(i)!=fa) {
			temp.add(dfs(G[u].get(i),u));
		}
		temp.sort(new cmp());
		if(!vis.containsKey(temp)) {
			vis.put(temp, ++sz);
		}
		book.put(st,vis.get(temp));
		return vis.get(temp);
	}
	public static void main(String[] args){
		InputReader in = new InputReader(System.in);
	    PrintWriter out = new PrintWriter(System.out);
	    int n=in.nextInt();sz=0;
	    for(int i=0;i<n-1;i++) {
	    	int u=in.nextInt(),v=in.nextInt();
	    	if(G[u]==null) G[u]=new ArrayList<Integer>();
	    	if(G[v]==null) G[v]=new ArrayList<Integer>();
	    	G[u].add(v);G[v].add(u);
	    }
	    int ans=0;
	    HashMap<Integer,Integer>map=new HashMap<Integer,Integer>();
	    for(int i=1;i<=n;i++) {
	    	if(G[i]==null) continue;
	    	if(G[i].size()==4) continue;
	    	int id=dfs(i,-1);
	    	if(!map.containsKey(id)) {
	    		ans++;
	    		map.put(id, 1);
	    	}
	    }
	    if(n==1) ans=1;
	    out.println(ans);
	    out.flush();
	}
	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());
        }
    }
}